content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def run_help_command():
"""Execute the 'help' subcommand."""
if len(sys.argv) < 3:
help.print_help(sys.stdout)
sys.exit(0)
else:
help_command = sys.argv[2]
if help_command == 'review':
help.print_review_help(sys.stdout)
sys.exit(0)
elif help_co... | 5,355,900 |
def calc_and_save_eta(steps, time, start, i, epoch, num_epochs, filename):
"""
Estimates the time remaining based on the elapsed time and epochs
:param steps: number of steps in an epoch
:param time: current time
:param start: start time
:param i: iteration through this epoch
:param epoch: e... | 5,355,901 |
def main():
""" Пример использования bots longpoll
https://vk.com/dev/bots_longpoll
"""
vk_session = vk_api.VkApi(token='your_group_token')
longpoll = VkBotLongPoll(vk_session, 'your_group_id')
for event in longpoll.listen():
if event.type == VkBotEventType.MESSAGE_NEW:
... | 5,355,902 |
def load_json():
"""Load the translation dictionary."""
try:
with open(JSON_FILENAME, "r", encoding="utf8") as file:
known_names = json.load(file)
if "version" in known_names:
if known_names.get("version") < JSON_VERSION:
print("Unkown version:... | 5,355,903 |
def get_username() -> str:
"""
Prompts the user to enter a username and then returns it
:return: The username entered by the user
"""
while True:
print("Please enter your username (without spaces)")
username = input().strip()
if ' ' not in username:
return usernam... | 5,355,904 |
def test_dissimilarity_fn():
"""
Testing computed dissimilarity function by comparing to precomputed, the dissimilarity function can be either normalized cross correlation or sum square error function.
"""
# lncc diff images
tensor_true = np.array(range(12)).reshape((2, 1, 2, 3))
tensor_pred = ... | 5,355,905 |
def fixture_set_token(monkeypatch: typing.Any, token: str) -> None:
"""Set the token environment variable."""
monkeypatch.setenv("LABELS_TOKEN", token) | 5,355,906 |
def remove__defjob(args):
"""
:param argparse.Namespace args: should supply all the command-line options
:rtype:
"""
req_url = apiurl(args, "/machines/{machine_id}/defjob/".format(machine_id=args.id))
# print(req_url);
r = requests.delete(req_url)
if r.status_code == 200:
rj =... | 5,355,907 |
def test_error_repr() -> None:
"""It has a string representation."""
content = ["foo", "bar"]
traceback = error.Traceback(content)
expected_output = f"Traceback(content={content})"
output = repr(traceback)
assert output == expected_output | 5,355,908 |
def condition(f):
"""
Decorator for conditions
"""
@wraps(f)
def try_execute(*args, **kwargs):
try:
res, m = f(*args, **kwargs)
m.conditions_results.append(res)
return m
except Exception as e:
raise ConditionError(e)
return try_ex... | 5,355,909 |
def get_spatial_anomalies(
coarse_obs_path, fine_obs_rechunked_path, variable, connection_string
) -> xr.Dataset:
"""Calculate the seasonal cycle (12 timesteps) spatial anomaly associated
with aggregating the fine_obs to a given coarsened scale and then reinterpolating
it back to the original spatial re... | 5,355,910 |
def get_pip_package_name(provider_package_id: str) -> str:
"""
Returns PIP package name for the package id.
:param provider_package_id: id of the package
:return: the name of pip package
"""
return "apache-airflow-providers-" + provider_package_id.replace(".", "-") | 5,355,911 |
def test_second_phase(players):
"""Verify that the second phase of the algorithm produces a valid set of
players with appropriate matches."""
players = first_phase(players)
assume(any(len(p.prefs) > 1 for p in players))
with warnings.catch_warnings(record=True) as w:
players = second_phase... | 5,355,912 |
def func_asymmetry_f_b(z, flag_z: bool = False):
"""Function F_b(z) for asymmetry factor.
"""
f_a , dder_f_a = func_asymmetry_f_a(z, flag_z=flag_z)
res = 2*(2*numpy.square(z)-3)*f_a
dder = {}
if flag_z:
dder["z"] = 8 * z * f_a + 2*(2*numpy.square(z)-3)*dder_f_a["z"]
return res, dder | 5,355,913 |
def verify_codegen(
module, num_vitis_ai_modules=1, params=None, target="llvm", dpu_target="DPUCADX8G"
):
"""Check Vitis-AI codegen against a known good output."""
module = build_module(module, target, params=params, dpu_target=dpu_target)
vitis_ai_modules = extract_vitis_ai_modules(module)
assert ... | 5,355,914 |
def momentum(state):
"""
solve for momentum for taup1
"""
vs = state.variables
"""
time tendency due to Coriolis force
"""
vs.update(tend_coriolisf(state))
"""
wind stress forcing
"""
vs.update(tend_tauxyf(state))
"""
advection
"""
vs.update(momentum_ad... | 5,355,915 |
def parse_args():
"""Command-line argument parser for generating scenes."""
# New parser
parser = ArgumentParser(description='Monte Carlo rendering generator')
# Rendering parameters
parser.add_argument('-t', '--tungsten', help='tungsten renderer full path', default='tungsten', type=str)
parse... | 5,355,916 |
def unique_id(token_id):
"""Return a unique ID for a token.
The returned value is useful as the primary key of a database table,
memcache store, or other lookup table.
:returns: Given a PKI token, returns it's hashed value. Otherwise, returns
the passed-in value (such as a UUID token ID ... | 5,355,917 |
def encode_aval_types(df_param: pd.DataFrame, df_ret: pd.DataFrame, df_var: pd.DataFrame,
df_aval_types: pd.DataFrame):
"""
It encodes the type of parameters and return according to visible type hints
"""
types = df_aval_types['Types'].tolist()
def trans_aval_type(x):
... | 5,355,918 |
def render_app_children(node: WxNode, context: WxRenderingContext):
"""Renders App children"""
render_children(node, context, lambda x, n, ctx: WxRenderingContext({
'xml_node': x,
'parent_node': n,
'node_globals': InheritedDict(node.node_globals)
})) | 5,355,919 |
def first(iterable, default=None):
"""
Returns the first item or a default value
>>> first(x for x in [1, 2, 3] if x % 2 == 0)
2
>>> first((x for x in [1, 2, 3] if x > 42), -1)
-1
"""
return next(iter(iterable), default) | 5,355,920 |
def generate_uuid_from_wf_data(wf_data: np.ndarray, decimals: int = 12) -> str:
"""
Creates a unique identifier from the waveform data, using a hash. Identical arrays
yield identical strings within the same process.
Parameters
----------
wf_data:
The data to generate the unique id for.
... | 5,355,921 |
def get_date_of_x_cases_reached(df, x):
"""
Determines the date hit n number of cases were reached
:param df: pandas df
:param x {int}: number of cases
"""
pass | 5,355,922 |
def display_quantiles(prediction_list, prediction_length, target_ts=None):
"""
Display average prediction value with 80% confidence interval compared to
target values.
:param prediction_list: list of predictions for stock prices over time at 0.1, 0.5, 0.9 quantiles
:prediction_length: how far in... | 5,355,923 |
def bridge(int, flag, unw, bridge, width, xmin='-', xmax='-', ymin='-', ymax='-', logpath=None, outdir=None,
shellscript=None):
"""
| Phase unwrap new regions with bridges to regions already unwrapped
| Copyright 2010, Gamma Remote Sensing, v1.5 clw 4-Nov-2010
Parameters
----------
i... | 5,355,924 |
def all_codes(number):
"""
:param: number - input integer
Return - list() of all codes possible for this number
TODO: complete this method and return a list with all possible codes for the input number
"""
pass | 5,355,925 |
def aggregate(table, key, aggregation=None, value=None, presorted=False,
buffersize=None, tempdir=None, cache=True):
"""Group rows under the given key then apply aggregation functions.
E.g.::
>>> import petl as etl
>>>
>>> table1 = [['foo', 'bar', 'baz'],
... ... | 5,355,926 |
def show_mpls_bypass_lsp_name_extensive_rpc(self, show_lsp_input_info=None, api_timeout=''):
"""
This is an auto-generated method for the PySwitchLib.
**Supported Versions**:
* SLXOS: 17r.1.01a, 17r.2.00, 17s.1.02
**Child Instance Keyword Argument Tuple(s)**:
:type show_lsp_input_inf... | 5,355,927 |
def most_similar(sen, voting_dict):
"""
Input: the last name of a senator, and a dictionary mapping senator names
to lists representing their voting records.
Output: the last name of the senator whose political mindset is most
like the input senator (excluding, of course, the input se... | 5,355,928 |
def overlay_spectra(model, dataset):
""" Run a series of diagnostics on the fitted spectra
Parameters
----------
model: model
best-fit Cannon spectral model
dataset: Dataset
original spectra
"""
best_flux, best_ivar = draw_spectra(model, dataset)
coeffs_all, covs,... | 5,355,929 |
def fixed_ro_bci_edge(ascentlat, lat_fixed_ro_ann,
zero_bounds_guess_range=np.arange(0.1, 90, 5)):
"""Numerically solve fixed-Ro, 2-layer BCI model of HC edge."""
def _solver(lat_a, lat_h):
# Reasonable to start guess at the average of the two given latitudes.
init_guess = ... | 5,355,930 |
def delete_projects(
*, projects,
db_name='smartshark',
db_user=None,
db_password=None,
db_hostname='localhost',
db_port=27017,
db_authentication_db=None,
db_ssl=False,
):
"""
Delete a list of project from a database.
:param projects: ... | 5,355,931 |
def prepend(list, item):
"""
Return a list with the given item added at the beginning. (Not
recursive.)
"""
pass | 5,355,932 |
def fresh_jwt_required(fn):
"""
A decorator to protect a Flask endpoint.
If you decorate an endpoint with this, it will ensure that the requester
has a valid and fresh access token before allowing the endpoint to be
called.
See also: :func:`~flask_jwt_extended.jwt_required`
"""
@wraps(... | 5,355,933 |
def random_small_number():
"""
随机生成一个小数
:return: 返回小数
"""
return random.random() | 5,355,934 |
def get_sample(df, col_name, n=100, seed=42):
"""Get a sample from a column of a dataframe.
It drops any numpy.nan entries before sampling. The sampling
is performed without replacement.
Example of numpydoc for those who haven't seen yet.
Parameters
----------
df : p... | 5,355,935 |
def gen_mail_content(content, addr_from):
"""
根据邮件体生成添加了dkim的新邮件
@param content: string 邮件体内容
@return str_mail: 加上dkim的新邮件
"""
try:
domain = addr_from.split('@')[-1]
dkim_info = get_dkim_info(domain)
if dkim_info:
content = repalce_mail(content, addr... | 5,355,936 |
def autocov(ary, axis=-1):
"""Compute autocovariance estimates for every lag for the input array.
Parameters
----------
ary : Numpy array
An array containing MCMC samples
Returns
-------
acov: Numpy array same size as the input array
"""
axis = axis if axis > 0 ... | 5,355,937 |
def get_args(argv=None):
"""Parses given arguments and returns argparse.Namespace object."""
prsr = argparse.ArgumentParser(
description="Perform a conformational search on given molecules."
)
group = prsr.add_mutually_exclusive_group(required=True)
group.add_argument(
'-m', '--molec... | 5,355,938 |
def _optimize_rule_mip(
set_opt_model_func,
profile,
committeesize,
resolute,
max_num_of_committees,
solver_id,
name="None",
committeescorefct=None,
):
"""Compute rules, which are given in the form of an optimization problem, using Python MIP.
Parameters
----------
set_o... | 5,355,939 |
def Zuo_fig_3_18(verbose=True):
"""
Input for Figure 3.18 in Zuo and Spence \"Advanced TEM\", 2017
This input acts as an example as well as a reference
Returns:
dictionary: tags is the dictionary of all input and output paramter needed to reproduce that figure.
"""
# INPUT
# Creat... | 5,355,940 |
def test_sqlcreds_connection(sql_creds):
"""
Simple test to ensure that the generated creds can connect to the database
The sql_creds fixture necessarily uses username and password (no Windows auth)
"""
df = pd.read_sql(con=sql_creds.engine, sql="SELECT TOP 1 * FROM sys.objects")
assert df.sh... | 5,355,941 |
def subscribe_feed(feed_link: str, title: str, parser: str, conn: Conn) -> str:
"""Return the feed_id if nothing wrong."""
feed_id = new_feed_id(conn)
conn.execute(
stmt.Insert_feed,
dict(
id=feed_id,
feed_link=feed_link,
website="",
title=titl... | 5,355,942 |
def MaybeLogReleaseChannelDefaultWarning(args):
"""Logs a release channel default change message for applicable commands."""
if (not _IsSpecified(args, 'cluster_version') and
not _IsSpecified(args, 'release_channel') and
(hasattr(args, 'enable_autoupgrade') and
cmd_util.GetAutoUpgrade(args)) and
... | 5,355,943 |
def run(fname):
"""
Create a new C file and H file corresponding to the filename "fname",
and add them to the corresponding include.am.
This function operates on paths relative to the top-level tor directory.
"""
# Make sure we're in the top-level tor directory,
# which contains the src di... | 5,355,944 |
def process_grid(procstatus, dscfg, radar_list=None):
"""
Puts the radar data in a regular grid
Parameters
----------
procstatus : int
Processing status: 0 initializing, 1 processing volume,
2 post-processing
dscfg : dictionary of dictionaries
data set configuration. Acc... | 5,355,945 |
def float_to_16(value):
""" convert float value into fixed exponent (8) number
returns 16 bit integer, as value * 256
"""
value = int(round(value*0x100,0))
return value & 0xffff | 5,355,946 |
def create_keras_one_layer_dense_model(*,
input_size,
output_size,
verbose=False,
**kwargs
):
"""
Notes:
https://www.tensorflow.org/tutorials/keras/save_and_load
"""
# ...................................................
# Create model
model = Seq... | 5,355,947 |
def test_list_base64_binary_enumeration_2_nistxml_sv_iv_list_base64_binary_enumeration_3_4(mode, save_output, output_format):
"""
Type list/base64Binary is restricted by facet enumeration.
"""
assert_bindings(
schema="nistData/list/base64Binary/Schema+Instance/NISTSchema-SV-IV-list-base64Binary-... | 5,355,948 |
def API_encrypt(key, in_text, formatting:str = "Base64", nonce_type:str = "Hybrid"):
""" Returns: Input Text 147 Encrypted with Input Key. """
try:
# Ensure an Appropriate Encoding Argument is Provided.
try: encoding = FORMATS[formatting]
except: raise ValueError("Invalid Encoding Argume... | 5,355,949 |
def convert_log_dict_to_np(logs):
"""
Take in logs and return params
"""
# Init params
n_samples_after_warmup = len(logs)
n_grid = logs[0]['u'].shape[-1]
u = np.zeros((n_samples_after_warmup, n_grid))
Y = np.zeros((n_samples_after_warmup, n_grid))
k = np.zeros((n_samples_af... | 5,355,950 |
def get_parent_dir():
"""Returns the root directory of the project."""
return os.path.abspath(os.path.join(os.getcwd(), os.pardir)) | 5,355,951 |
def step_erase_licenses(context):
"""Erases the J-Link's licenses.
Args:
context (Context): the ``Context`` instance
Returns:
``None``
"""
jlink = context.jlink
assert jlink.erase_licenses() | 5,355,952 |
def map_links_in_markdownfile(
filepath: Path,
func: Callable[[Link], None]
) -> bool:
"""Dosyadaki tüm linkler için verilen fonksiyonu uygular
Arguments:
filepath {Path} -- Dosya yolu objesi
func {Callable[[Link], None]} -- Link alan ve değiştiren fonksiyon
Returns:
bool -... | 5,355,953 |
def test_runner_should_iterate_all_steps_in_a_scenario(
hook_registry, default_config, mocker
):
"""The Runner should iterate all Steps in a Scenario"""
# given
runner = Runner(default_config, None, hook_registry)
runner.run_step = mocker.MagicMock()
runner.run_step.return_value = State.PASSED
... | 5,355,954 |
def half_cell_t_2d_triangular_precursor(p, t):
"""Creates a precursor to horizontal transmissibility for prism grids (see notes).
arguments:
p (numpy float array of shape (N, 2 or 3)): the xy(&z) locations of cell vertices
t (numpy int array of shape (M, 3)): the triangulation of p for which the ... | 5,355,955 |
async def stop_runner() -> None:
"""Stop the runlevel-pursuing runner task."""
daemons.cancel(daemons.Service.RUNLEVEL) | 5,355,956 |
def main():
"""Main function that calls the JCDecaux API and writes to database.
Function retrieves JSON data fromthe JCDecaux API.
The JSON data is parsed and validated.
The data is inserted into a remote database."""
# MySQL connection
conex = mysql.connector.connect(user='root', password='... | 5,355,957 |
def backup(source, target, update_log_table, use_rsync, verbose, debug, dry_run):
"""
Back up a source directory to a target directory.
This function will accept a source and target directories, most often
on separate external hard drives, and copy all files from the source
to the target that are e... | 5,355,958 |
def count_datavolume(sim_dict):
"""
Extract from the given input the amount of time and the memory you need to
process each simulation through the JWST pipeline
:param dict sim_dict: Each key represent a set of simulations (a CAR activity for instance)
each value is a list of ... | 5,355,959 |
def get_exception_class_by_code(code):
"""Gets exception with the corresponding error code,
otherwise returns UnknownError
:param code: error code
:type code: int
:return: Return Exception class associated with the specified API error.
"""
code = int(code)
module_classes = inspect.getme... | 5,355,960 |
def context():
"""Return an instance of the JIRA tool context."""
return dict() | 5,355,961 |
def plot_decision_boundary_distances(model, X, Y, feat_crosses=None, axis_lines=False, save=False):
"""
Plots decision boundary
Args:
model: neural network layer and activations in lambda function
X: Data in shape (num_of_examples x features)
feat_crosses: list of tuples show... | 5,355,962 |
def dist_to_group(idx: int, group_type: str, lst):
"""
A version of group_count that allows for sorting with solo agents
Sometimes entities don't have immediately adjacent neighbors.
In that case, the value represents the distance to any neighbor, e.g
-1 means that an entity one to the left or righ... | 5,355,963 |
def label_encode(dataset, column):
"""
This will encode a binary categorical variable.
Column needs to be a string
"""
labelencoder_X = LabelEncoder()
dataset[column] = labelencoder_X.fit_transform(dataset[column])
return | 5,355,964 |
def get_nodes_rating(start: AnyStr,
end: AnyStr,
tenant_id: AnyStr,
namespaces: List[AnyStr]) -> List[Dict]:
"""
Get the rating by node.
:start (AnyStr) A timestamp, as a string, to represent the starting time.
:end (AnyStr) A timestamp, a... | 5,355,965 |
def f(OPL,R):
""" Restoration function calculated from optical path length (OPL)
and from rational function parameter (R). The rational is multiplied
along all optical path.
"""
x = 1
for ii in range(len(OPL)):
x = x * (OPL[ii] + R[ii][2]) / (R[ii][0] * OPL[ii] + R[ii][1])
return x | 5,355,966 |
def test_add():
"""Test required to make the CI pass"""
assert 2 + 2 == 4 | 5,355,967 |
def _str_conv(number, rounded=False):
"""
Convenience tool to convert a number, either float or int into a string.
If the int or float is None, returns empty string.
>>> print(_str_conv(12.3))
12.3
>>> print(_str_conv(12.34546, rounded=1))
12.3
>>> print(_str_conv(None))
<BLANKLINE... | 5,355,968 |
def load_img(img: Any):
"""
Load an image, whether it's from a URL, a file, an array, or an already
in-memory image.
"""
raise ValueError(f"Can not load object of type {type(img)} as image.") | 5,355,969 |
def configure_service():
"""Configure the GlusterFS filesystems"""
generate_etc_hosts()
modify_cassandra_yaml()
modify_jvm_options()
create_dirs()
add_cassandra_to_systemd() | 5,355,970 |
def build_eval_graph(input_fn, model_fn, hparams):
"""Build the evaluation computation graph."""
dataset = input_fn(None)
batch = dataset.make_one_shot_iterator().get_next()
batch_holder = {
"transform":
tf.placeholder(
tf.float32,
[1, 1, hparams.n_parts, hparams.n_d... | 5,355,971 |
def test_timeout():
"""
Test is the timeout exception is raised with proper message.
"""
lock = get_connection(1, 5, 15)
collection = str(random.random())
with pytest.raises(MongoLockTimeout) as excinfo:
with lock(collection):
for i in range(15):
with lock(col... | 5,355,972 |
def _encodeLength(length):
"""
Encode length as a hex string.
Args:
length: write your description
"""
assert length >= 0
if length < hex160:
return chr(length)
s = ("%x" % length).encode()
if len(s) % 2:
s = "0" + s
s = BinaryAscii.binaryFromHex(s)
le... | 5,355,973 |
def check_mask(mask):
# language=rst
"""
Check if the 2d boolean mask is valid
:param mask: 2d boolean mask array
"""
if(jnp.any(mask) == False):
assert 0, 'Empty mask! Reduce num'
if(jnp.sum(mask)%2 == 1):
assert 0, 'Need masks with an even number! Choose a different num' | 5,355,974 |
def stemmer(stemmed_sent):
"""
Removes stop words from a tokenized sentence
"""
porter = PorterStemmer()
stemmed_sentence = []
for word in literal_eval(stemmed_sent):
stemmed_word = porter.stem(word)
stemmed_sentence.append(stemmed_word)
return stemmed_sentence | 5,355,975 |
def _queue_number_priority(v):
"""Returns the task's priority.
There's an overflow of 1 bit, as part of the timestamp overflows on the laster
part of the year, so the result is between 0 and 330. See _gen_queue_number()
for the details.
"""
return int(_queue_number_order_priority(v) >> 22) | 5,355,976 |
def test_generator_aovs(path):
"""Generate a function testing given `path`.
:param path: gproject path to test
:return: function
"""
def test_func(self):
"""test render pass render layer and AOV particularities
"""
assert path in g_parsed
p = g_parsed[path]
... | 5,355,977 |
def delimited_list(
expr: Union[str, ParserElement],
delim: Union[str, ParserElement] = ",",
combine: bool = False,
min: OptionalType[int] = None,
max: OptionalType[int] = None,
*,
allow_trailing_delim: bool = False,
) -> ParserElement:
"""Helper to define a delimited list of expressions... | 5,355,978 |
def get_minion_node_ips(k8s_conf):
"""
Returns a list IP addresses to all configured minion hosts
:param k8s_conf: the configuration dict
:return: a list IPs
"""
out = list()
node_tuple_3 = get_minion_nodes_ip_name_type(k8s_conf)
for hostname, ip, node_type in node_tuple_3:
out.a... | 5,355,979 |
def main(argv):
"""
Main function to run strategic_svm.py. Set up SVM classifier, perform
and evaluate attack, deploy defense and perform strategic attack. Resutls
and adv. sample images are also saved on each task.
"""
# Parse arguments and store in model_dict
model_dict = svm_model_dict_c... | 5,355,980 |
def calculate_ri(column):
"""
Function that calculates radiant intensity
"""
return float(sc.h * sc.c / 1e-9 * np.sum(column)) | 5,355,981 |
def find_kw_in_lines(kw, lines, addon_str=' = '):
"""
Returns the index of a list of strings that had a kw in it
Args:
kw: Keyword to find in a line
lines: List of strings to search for the keyword
addon_str: String to append to your key word to help filter
Return:
i: In... | 5,355,982 |
def delete_group(current_session, groupname):
"""
Deletes a group
"""
projects_to_purge = gp.get_group_projects(current_session, groupname)
remove_projects_from_group(current_session, groupname, projects_to_purge)
gp.clear_users_in_group(current_session, groupname)
gp.clear_projects_in_group... | 5,355,983 |
def label_smoothed_nll_loss(lprobs, target, epsilon: float = 1e-8, ignore_index=None):
"""Adapted from fairseq
Parameters
----------
lprobs
Log probabilities of amino acids per position
target
Target amino acids encoded as integer indices
epsilon
Smoothing factor between... | 5,355,984 |
def ParseFieldDefRequest(post_data, config):
"""Parse the user's HTML form data to update a field definition."""
field_name = post_data.get('name', '')
field_type_str = post_data.get('field_type')
# TODO(jrobbins): once a min or max is set, it cannot be completely removed.
min_value_str = post_data.get('min_v... | 5,355,985 |
async def get_museum_session_key() -> str:
"""
Retrieve a session key for the MuseumPlus service, generating a new
one if necessary.
:returns: Session key
"""
# We might have an active session key stored locally.
key_path = get_session_key_file_path()
try:
session_time = key_pat... | 5,355,986 |
def sftp_fail_cases(s1, s2):
"""
Test to verify negative scenarios
Description : Verify the negative scenarios when user source
path of the file is invalid and when destination
path is invalid
"""
print("\n############################################\n")
print... | 5,355,987 |
def parse_date(regexen, date_str):
"""
Parse a messy string into a granular date
`regexen` is of the form [ (regex, (granularity, groups -> datetime)) ]
"""
if date_str:
for reg, (gran, dater) in regexen:
m = re.match(reg, date_str)
if m:
try:... | 5,355,988 |
def floatScrollBar(*args, **kwargs):
"""
Create a scroll bar control that accepts only float values and is bound by a minimum and maximum value.
Returns: `string` Full path name to the control.
"""
pass | 5,355,989 |
def create_web_config(new_dir, filename):
"""
The function searches for the specified *filename* in *config* directory of this module
and, if that file exists, copies it to the *new_dir* directory.
Args:
new_dir (str): Config file *filename* will be created in this directory.
filename (... | 5,355,990 |
def scrape_inmates(example_url, force):
"""
Scrape Dane County inmate database
"""
d = DaneCountyInmatesDriver()
if example_url:
inmates = [example_url]
else:
inmates = d.inmates()
path = f"./inmates/13"
os.makedirs(path, exist_ok=True)
long_ago = datetime.now() - t... | 5,355,991 |
def pytest_addoption(parser):
"""Add an option to run tests against a real AWS account instead of the Stubber."""
parser.addoption(
"--use-real-aws-may-incur-charges", action="store_true", default=False,
help="Connect to real AWS services while testing. WARNING: THIS MAY INCUR "
"CH... | 5,355,992 |
def PreNotebook(*args, **kwargs):
"""PreNotebook() -> Notebook"""
val = _controls_.new_PreNotebook(*args, **kwargs)
return val | 5,355,993 |
def handle_cf_removed_obj_types(instance, action, pk_set, **kwargs):
"""
Handle the cleanup of old custom field data when a CustomField is removed from one or more ContentTypes.
"""
if action == 'post_remove':
instance.remove_stale_data(ContentType.objects.filter(pk__in=pk_set)) | 5,355,994 |
def user_voted(message_id: int, user_id: int) -> bool:
"""
CHECK IF A USER VOTED TO A DETECTION REPORT
"""
return bool(
c.execute(
"""
SELECT *
FROM reports
WHERE message_id=? AND user_id=?
""",
(message_id, user_id),
... | 5,355,995 |
def test_from_date(months):
"""Test the from_date method.
"""
assert ttcal.Month.from_date(date(2012, 7, 10)) == months[2]
assert ttcal.Month.from_date(date(2012, 10, 20)) == months[1] | 5,355,996 |
def get_values(wsdl_url, site_code, variable_code, start=None, end=None,
suds_cache=("default",), timeout=None, user_cache=False):
"""
Retrieves site values from a WaterOneFlow service using a GetValues request.
Parameters
----------
wsdl_url : str
URL of a service's web ser... | 5,355,997 |
def GetDot1xInterfaces():
"""Retrieves attributes of all dot1x compatible interfaces.
Returns:
Array of dict or empty array
"""
interfaces = []
for interface in GetNetworkInterfaces():
if interface['type'] == 'IEEE80211' or interface['type'] == 'Ethernet':
if (interface['builtin'] and
... | 5,355,998 |
def get_v_l(mol, at_name, r_ea):
"""
Returns list of the l's, and a nconf x nl array, v_l values for each l: l= 0,1,2,...,-1
"""
vl = generate_ecp_functors(mol._ecp[at_name][1])
v_l = np.zeros([r_ea.shape[0], len(vl)])
for l, func in vl.items(): # -1,0,1,...
v_l[:, l] = func(r_ea)
r... | 5,355,999 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.