content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def bot_text_agent(text):
"""
text agent responsible for any text processing to extract entities like GPE
arguments:
-- text: input text to be processed <string format>
returns:
-- weather agent response <ENTITY FOUND>
-- small talk answer <PRE-DEFIND TALK FOUND>
... | d4d8ecb83a7f045248ec195d879a024f1a314abb | 56,800 |
from datetime import datetime
def create_bq_table_name(site_name, delta_days=0,
time_partitioning_type=""):
"""return BigQuery table name"""
TABLE_PREFIX = environ['BQ_TABLE_PREFIX']
prefix = TABLE_PREFIX + site_name
"""
Using auto table partitioning
https://cloud.goo... | 0048bdb2845a9a492c4c52141cd0db801257d4df | 56,801 |
import os
def get(
url,
params,
tokens=shuffle(os.environ.get("RES_NINJA_TOKENS", "").split(os.pathsep)),
):
"""Return the text of a GET requests.
The request is cached.
Use the environmental variable: `LRU_CACHE_MAXSIZE` to set the maximum size
of the LRU cache, the default value is 2048
... | acfd706e660e4443cb4b046325d41fc59e70f78f | 56,802 |
def batch_neighbors(queries, supports, q_batches, s_batches, radius):
"""
Computes neighbors for a batch of queries and supports
:param queries: (N1, 3) the query points
:param supports: (N2, 3) the support points
:param q_batches: (B) the list of lengths of batch elements in queries
:param s_ba... | 5226fe185db206d2d1384085b10e3fc79528f6de | 56,803 |
def add_state_name_col(df):
"""
Add a column of corresponding state names to a dataframe
Params (df) a DataFrame with a column called 'abbrev' that has state abbreviations
Return a copy of original DataFrame with extra column
"""
new_df = df.copy()
names_map = {'CA': 'California',
... | 8e1674006bdccf8a0c5c22dafd7231dd762d725f | 56,804 |
def ex6():
"""
Example 6
Minimizing the Tardiness
file name: Example6.py
Copyright Log Opt Co., Ltd.
Consider a 4-activity problem with one machine resource.
The due dates and processing times (durations) of the activities are kept in the dictionaries
due={1:5,2:9,3:6,4:4} and
dur... | 62c66b693972d17b24bc6dc0a008ef164ed1b26a | 56,805 |
import os
def return_omegaconf_modified(
modification_full: dict = {}, rel_path="config", name_yaml="unittest.yaml"
):
"""read the default config of config/default.yaml and apply deep modified dict.
returns:
omegaconf.Omegaconfig:
"""
hydra.core.global_hydra.GlobalHydra.instance().clear()... | 616b0f714ed3d43990f6a9534473ebf87d928d82 | 56,806 |
import logging
def track(params_file, directions="det", max_angle=30., sphere=None,
seed_mask=None, n_seeds=1, random_seeds=False, stop_mask=None,
stop_threshold=0, step_size=0.5, min_length=10, max_length=1000,
odf_model="DTI"):
"""
Tractography
Parameters
----------
... | 68b003c5f536826f17bbc509153d89cadb1b2b1a | 56,807 |
def GlobalAveragePooling2D(input, n_class, name):
"""
replace Fully Connected Layer.
https://www.facebook.com/groups/smartbean/permalink/1708560322490187/
https://github.com/AndersonJo/global-average-pooling/blob/master/global-average-pooling.ipynb
:param input: a tensor of input
:param n_class:... | aba8b1566e61d86b9e494d16179d3a6cd73866ff | 56,808 |
def bill_calculator(load_profile, tariff, export_tariff):
"""
Not vectorized for now. Next step will be pass in multiple profiles for the same tariff
2 styles of NEM: Full retail and fixed schedule value.
To-do
-Both energy and demand calcs (anything that uses piecewise calculator) doesn't go belo... | c9741f5df7613c98775a4e22779478fc39d82f0e | 56,809 |
def angularfreq(nsamples, samplerate):
""" Compute angular frequencies """
angfreq = np.arange(nsamples, dtype=np.float32)
angfreq[-nsamples/2 + 1:] -= nsamples
angfreq *= samplerate * PI2 / nsamples
return angfreq | daf4cdd8591580f291a086f3316b10ec2565f356 | 56,810 |
def from_doc(doc):
"""
Read stub from doc
"""
return Stub(
get(Doc.id_path, doc),
get(Doc.output_path, doc),
get(Doc.created, doc),
get(Doc.modified, doc),
get(Doc.title, doc),
get(Doc.meta_summary, doc)
) | ccb906285635b1dace9ce3d953af0c1f8bd1f1bd | 56,811 |
def _allocation_request_for_provider(ctx, requested_resources, provider):
"""Returns an AllocationRequest object containing AllocationRequestResource
objects for each resource class in the supplied requested resources dict.
:param ctx: placement.context.RequestContext object
:param requested_resources:... | 2dd9415a160f203ee65f604336be9ddee5187eb7 | 56,812 |
def create_turkey_season(source_df, target_df, feature_name):
"""
Winter: December - February
Spring: March - May
Summer: June - August
Autumn: September - November
"""
month_to_season_map = {
"jan": "winter",
"feb": "winter",
"mar": "spring",
"apr": "sprin... | 65f996d80554a35fff6341ca500a0c09c64186bd | 56,813 |
def evaluate_poly(poly, x):
"""
Computes the polynomial function for a given value x. Returns that value.
Example:
# >>> poly = (0.0, 0.0, 5.0, 9.3, 7.0) # f(x) = 7x^4 + 9.3x^3 + 5x^2
# >>> x = -13
# >>> print evaluate_poly(poly, x) # f(-13) = 7(-13)^4 + 9.3(-13)^3 + 5(-13)^2
180339.9
... | 52c28c0e511731e9e40ccd54c5c8c976fcc99324 | 56,814 |
def render_User_avatar(self, h, comp, model, *args):
"""Render a user's avatar"""
with h.span(class_='avatar', title='%s' % (self.data.fullname)):
avatar = self.get_avatar()
if avatar:
h << h.img(src=avatar)
else:
h << h.i(class_='ico-btn icon-user')
return h.... | c192b415cb297aedf22d626418ab58d159e7815a | 56,815 |
def W3(DD,RR,DR,RD,Ndd,Nrr,Ndr,Nrd):
"""Returns the Landy & Scalay estimator for the cross-correlation
and its error. The pair counts DD, RR, DR, RD are not required to
be normalized. Ndd,Nrr,Ndr,Nrd are the normalizations
factors for each pair count
Parameters
----------
DD : ndarray
... | 49fed635e32d810278f71eae98ebc65ca636664f | 56,816 |
def energy_decay_curve_chu(
data,
sampling_rate,
freq='broadband',
noise_level='auto',
is_energy=False,
time_shift=True,
channel_independent=False,
normalize=True,
plot=False):
""" Implementation of the "subtraction of noise"-method after Chu ... | 837203c3df2caae515a47df02018556e1413b9b9 | 56,817 |
def _reset_hard_to_refs_prefixed_ref(git, remote_name, ref, raises=True):
""" deals with the git reset --hard command for long name ref (on the format 'refs/xxx') """
assert ref.startswith("refs/")
# Check the ref format to retrieve the effective ref name to switch on
if ref.startswith("refs/remotes") a... | c362093006e77c2965f9ce76ec2e85c8b45510a5 | 56,818 |
import typing
def financial_statement_full_as_reported(
apikey: str,
symbol: str,
period: str = "annual",
) -> typing.List[typing.Dict]:
"""
Query FMP /financial-statement-full-as-reported/ API.
Company's "as reported" full income statement.
:param apikey: Your API key.
:param symbol:... | 801c084de98eb640691136c79f5796c32f4ff4ab | 56,819 |
def about(request):
"""
Share further details about the project.
"""
context = {'client_id': settings.OPENHUMANS_CLIENT_ID,
'oh_proj_page': settings.OH_ACTIVITY_PAGE}
return render(request, 'main/about.html', context=context) | c738d29d1eed932dfe59dfc4a1c64c8ab6253dc3 | 56,820 |
def str2bool(v):
"""
Used to parse boolean args
@link https://stackoverflow.com/a/43357954/3443137
"""
if isinstance(v, bool):
return v
if v.lower() in ('yes', 'true', 't', 'y', '1'):
return True
elif v.lower() in ('no', 'false', 'f', 'n', '0'):
return False
else:
... | 18d7477dd152580aeddc9acd10d0ff5c6b5c166e | 56,821 |
import warnings
def kappa_t(wair,temp,pres,airf=None,dhum=None,dliq=None,chkvals=False,
chktol=_CHKTOL,airf0=None,dhum0=None,dliq0=None,chkbnd=False,
mathargs=None):
"""Calculate wet air isothermal compressibility.
Calculate the isothermal compressibility of wet air.
:arg float wair: Tot... | 05bb89a2049928df1f66605b5f52207ac7cd8a90 | 56,822 |
def numpy_to_Point(this_numpy):
"""Convert a numpy array into a geometry_msgs/Point32
Arguments:
this_numpy: a numpy array having one 3 element dimension (so that it
can be squeezed to (3,) size) to populate a message from
Returns:
this_point32: geometry_msgs/Point32 message wi... | 7a350307fc9e285279fc570c415cef915a343fa1 | 56,823 |
def value_is_float_not_int(value):
"""Return if value is a float and not an int"""
# this is klugy and only needed to display deprecation warnings
try:
int(value)
return False
except ValueError:
try:
float(value)
return True
except ValueError:
... | f08f55dfc5e8b4eefef102f7fe097e4285d9dc7c | 56,824 |
from ucsmsdk.mometa.callhome.CallhomeProfile import CallhomeProfile
def callhome_profile_create(handle, name, format="xml", max_size="1000000",
level="debug", alert_groups=None,
descr=None, **kwargs):
"""
Creates callhome profile.
Args:
ha... | 0ac6bbcb9bdfa5372cdb149a28776b7df5584a79 | 56,825 |
def debug_csrf_failure(request, reason=""):
"""
raised own CsrfFailure() exception to get the normal debug page on
Csrf failures.
See also:
https://docs.djangoproject.com/en/1.3/ref/contrib/csrf/#rejected-requests
More Info: See DocString above.
"""
if not settings.DEBUG:
... | 8a435faebbc89a0bb94201be6b91f41beed1a984 | 56,826 |
def add_noise(moves, noise_p, param):
"""Adds noise to the movement data.
"""
return np.array(
[[moves[i, j] + np.sqrt(noise_p) * np.random.randn(len(moves[i, j]))
for j in xrange(param['N_m'])]
for i, _s in enumerate(param['scales'])]) | bcb5d127f73286efd19a11401768538d17af1e1c | 56,827 |
def policy_settings(request):
"""TLS termination policy settings"""
return request.getfixturevalue(request.param) | 3a65251ea7866e25c02bf8354cc7cc9bbb5552e8 | 56,828 |
import string
def process_text(text, stem=True):
""" Tokenize text and stem words removing punctuation
"""
text = text.translate(string.punctuation)
tokens = word_tokenize(text)
if stem:
stemmer = PorterStemmer()
tokens = [stemmer.stem(t) for t in tokens]
return tokens | 7084a614cf192aa400a7bef93f6b469c37348c70 | 56,829 |
import random
def generate_random_DC_single_force_coupled_tensor():
"""Function to generate random DC-single-force coupled tensor (M_11,M_22,M_33,M_12,M_13_M_23,F_x,F_y,F_z) using normal distribution projected onto a 3-sphere method. (Based on Pugh 2015,Appendix B and Muller, 1959; Marsaglia, 1972).
Returns a... | 565c2b40bc49ee0c194d9da25fe2e5d1dfa65c41 | 56,830 |
def yenc_decode(lines):
"""Decodes a yEnc-encoded fileobj.
Should use python-yenc 0.4 for this, but it's not py3.3 compatible.
"""
data = yenc_strip([l.decode('ISO-8859-1') for l in lines])
if data:
yenc, data = yenc_check(data)
ybegin, ypart, yend = yenc
if ybegin and yen... | 153f96a78f97503cfbb3b1a6dc6d21f1e29159a6 | 56,831 |
def create_zeros_slot(primary, name, dtype=None, colocate_with_primary=True):
"""Create a slot initialized to 0 with same shape as the primary object.
Args:
primary: The primary `Variable` or `Tensor`.
name: Name to use for the slot variable.
dtype: Type of the slot variable. Defaults to the type of `... | 3b2a5d53475dcf816c2a75c318add085ace36b35 | 56,832 |
def process_lower(cont):
""" Make the value in lowercase """
return cont.lower() | f863852b0aff952bce080e20360d6fcc571acc21 | 56,833 |
def get_colormap():
"""Returns the current AgML colormap."""
global _COLORMAPS, _COLORMAP_CHOICE
return _COLORMAPS[_COLORMAP_CHOICE] | 986d2b92a71228fdfa21435f44ca99965702e94c | 56,834 |
def dewarp_line(line,show=0,order=3):
"""Dewarp the baseline of a line based in estimate_baseline.
Returns the dewarped image."""
line = line*1.0/amax(line)
line = r_[zeros(line.shape),line]
h,w = line.shape
baseline = estimate_baseline(line,order=order)
ys = polyval(baseline,arange(w))
... | 1e47c2e704e95d98766af6261aee7b2ac45ecc5f | 56,835 |
def load_settings(filename, path='/', ignore=()):
"""
By default loads all settings from path
'/general/data_collection/Settings/'
or for example to load animal ID, use:
path='/General/animal/'
ignore - tuple - any paths including any element of ignore are returned as None
"""
f... | 108a3b7ab6e83efbc2e2faac40873697722d13a5 | 56,836 |
def npl_loan_detail(request, pk):
"""
List the data a specific EBA Loan
"""
try:
loan = Loan.objects.get(pk=pk)
except Loan.DoesNotExist:
return Response(status=status.HTTP_404_NOT_FOUND)
serializer = NPL_LoanDetailSerializer(loan)
return Response(serializer.data) | ce7e5597d40658069ed5cd6c9765e661ef84c55c | 56,837 |
def cli_key_script_name():
"""
Return the CLI script basename
"""
return "cli_salt_key.py" | 5e4b1116b21e66e1642f5046f65010a0ffc78d2f | 56,838 |
import urllib
import logging
def run_inference_on_image(image_url):
"""Runs inference on an image.
Args:
image: Image file name.
Returns:
Nothing
"""
# Read image from URL
user_agent_header = 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/535.19 (KHTML, like Gecko) Ubuntu/12.04 Chromium/18.0.1025... | ca2a2eeb1c4daaf79d9479d208c274189dc6e8d8 | 56,839 |
import re
def generate_model(formula):
"""
This function will invoke PySMT APIs to solve the provided formula and return the byte list of the model
Arguments:
formula: smtlib formatted formula
"""
emitter.debug("extracting z3 model")
model = get_model(formula)
... | bc3df82951cc7b385a865255a3211c80b0177e1b | 56,840 |
def main() -> int:
"""
Consider only horizontal and vertical lines.
At how many points do at least two lines overlap?
"""
l, g = parse_input()
lines: dict[tuple[int], tuple[int]] = l
grid: list[list[int]] = g
for line in lines:
if line[0][0] == line[1][0]:
mini = min(line[0][1], line[1][1])
maxi = max... | 89a3debac8f9b598c9bef90ce45a1d0927f9bac6 | 56,841 |
def U_XX(j, n):
"""Makes a sequence of operations for XX basis.
Args:
j (int): Position of 'HH'.
n (int): Length of the sequence.
Returns:
str: Sequence of operations.
"""
assert j < n - 1
assert n > 2
return 'I' * j + "HH" + 'I' * (n - j - 2) | b08a985be8d3105846e320bd9cc3a3548b4bd8eb | 56,842 |
def get_bootstrap_setting(setting, default=None):
"""
Read a setting
"""
return BOOTSTRAP4.get(setting, default) | c60bb97721ad485d7929dd7edea5182f3473bb2e | 56,843 |
from typing import Union
from typing import Optional
from typing import Dict
from typing import Any
def compile(
sir: Union[serialization.SIR.SIR, str, bytes],
*,
unit_info: Optional[Dict[str, Any]] = None,
**kwargs,
):
"""Compile SIR to source code.
This is a convenience function which insta... | 45c0d46a887dd9f7261259512f2a90d04fc5b1b5 | 56,844 |
import os
import sys
import urllib
def maybe_download(imageId, url):
"""Download the data from Yann's website, unless it's already here."""
if not os.path.exists(IMAGE_DIR):
os.makedirs(IMAGE_DIR)
#filepath = os.path.join(IMAGE_DIR, filename)
urlfilename = url.split('/')[-1].split("?")[0].strip()
ext=ur... | 9e1be5bdf5917c12834437e2d6e10353f3e616d3 | 56,845 |
def forgot_password():
"""
User forgot password
Input:
email
Output:
200 and a reset password email is sent to user
400 if email not exist
"""
data = request.get_json()
if not data or not data.get("email"):
return jsonify(error="request body must contain emai... | b29ff753ef26feab1289e1ffe9108a2cd9386dfd | 56,846 |
def mape(y_true, y_pred):
"""
Mean absolute percentage error regression loss.
Args:
y_true ([np.array]): test samples
y_pred ([np.array]): predicted samples
Returns:
[float]: mean absolute percentage error
"""
diff = K.abs((y_true - y_pred) / K.clip(K.abs(y_true), K.eps... | 3672984361c31a3054eb962d61a4f7f349760b77 | 56,847 |
def analyze():
"""Analyze the frame and return the results"""
if not request.is_json:
return jsonify(error='Request must be json'), 400
try:
frame = data_uri_to_cv2_img(request.json['frame'])
except: # pylint: disable=bare-except
return jsonify(error='Could not decode frame'), ... | c0cb538f5a306b696b55b81c8dc9c344f0629bb7 | 56,848 |
def train_and_eval(trial: optuna.Trial, ex_dir: str, seed: [int, None]):
"""
Objective function for the Optuna `Study` to maximize.
.. note::
Optuna expects only the `trial` argument, thus we use `functools.partial` to sneak in custom arguments.
:param trial: Optuna Trial object for hyper-para... | d92a3279ecfa741f1d852afd3bfb277da2654f61 | 56,849 |
import time
import copy
import io
import sys
def dict_ndl(events, alphas, betas, lambda_=1.0, *,
weights=None, inplace=False, remove_duplicates=None,
make_data_array=False, verbose=False):
"""
Calculate the weights for all_outcomes over all events in event_file.
This is a pure p... | c6719d1a12be52a190f4a456b9fe6c61bd4982e4 | 56,850 |
def duplicate(my_list):
"""Return a new list that repeats the input twice"""
return my_list + my_list | 569f061ff02e996dd3c1a7030aed2934e61987f7 | 56,851 |
def get_predicted_changes(query_params):
""" Get a list of predicted profitable changes.
"""
order = query_params.get('order_by')
if order is not None:
order = order.split(',')
else:
order = ['date']
all_predictions = predictions.get_predictions(
instrument=query_params.g... | 15150370309f1f4ba98a1df0e9977fcfb4d0cf99 | 56,852 |
def _get_default_generators(
options, in_memory = False
):
"""Initialize default list of stats generators.
Args:
options: A StatsOptions object.
in_memory: Whether the generators will be used to generate statistics in
memory (True) or using Beam (False).
Returns:
A list of stats generator ... | fb92c7f5129685ccfadd356ee4bba9bf39cad560 | 56,853 |
def ucfirst(string):
"""Return string with first letter in upper case."""
if len(string) < 2:
return string.upper()
else:
return string[:1].upper() + string[1:] | 19c9be463e8c45db9ce7b5dfc91f7260bea9a81d | 56,854 |
from typing import Callable
from re import T
def random_method(decorated: Callable[..., T]) -> Callable[..., T]:
"""Decorator usable on any method within a class that will provide an isolated torch random context.
The decorator will store a `_random_instance` property on the object in order to persist succes... | 1df1f654c8de146b11dd7189196ec4d403f23c0f | 56,855 |
def get_word_counter(word_vocab):
"""
Convert a list of tuple of words and their frequencies in word vocabulary to dictionary.
Key is word and value is its frequency.
Args:
word_vocab: A list of tuple of words and their frequencies.
Returns: A dictionary with word as the key and its frequenc... | 8e76652c721d9ca175f79d9bb0acfccfb90da647 | 56,856 |
import copy
def cost_backlink(in_source_data,
in_cost_raster,
max_distance=None,
source_cost_multiplier=None,
source_start_cost=None,
source_resistance_rate=None,
source_capacity=None,
source_... | 27708dca1a2611af554a5acb786bdff737a3eb22 | 56,857 |
import torch
def format_metric(val):
"""Format a tensor/number as a float with 4 digits"""
if isinstance(val, torch.Tensor):
val = val.detach().data
return str('{:.4f}'.format(val)) | 337e266bca4ff0433e2c69864b1a493976d12c44 | 56,858 |
def estimate_value_from_state_action_ratios(
data,
gamma,
state_action_ratio_fn):
"""Estimates value of policy given data and state-action density ratios.
Args:
data: The experience data to base the estimate on.
gamma: Discount to use in the value calculation.
state_action_ratio_fn: A funct... | 01e516fd72a175648d069f559430b8a88d613574 | 56,859 |
import pickle
def load_ontology(ontology_file):
""" loads an ontology pickle file """
ontology = pickle.load(open(ontology_file, 'rb'))
return ontology | 8e3e9c9017bee76795a98435a68d3f01fa0d40e9 | 56,860 |
def plot_target_belief(g, folder_name, my_layout, b_target: dict, t: int):
"""Plot target belief"""
V, n = ext.get_set_vertices(g)
rgba_color = (255, 0, 0, 1)
g.vs["color"] = "white"
for v in V:
v_idx = ext.get_python_idx(v)
b = b_target[v, t]
c = b/1
if 0.001 < c <... | 6a00a74e600241929d5cb9993ec1a07867ddf41a | 56,861 |
def ToPropertyPb(name, values):
"""Creates type-specific entity_pb.PropertyValues.
Determines the type and meaning of the PropertyValue based on the Python
type of the input value(s).
NOTE: This function does not validate anything!
Args:
name: string or unicode; the property name
values: The values... | f12d69b39607882ed8fe20d2c4ad9b14696a15c2 | 56,862 |
def proc_nslkdd(df_tr, df_te):
"""Load the NSL-KDD dataset from the data/ folder. Note you need to download the data
and add it to the folder.
:return Four Numpy arrays with X_tr, y_tr, X_te and y_te
"""
df_tr = df_tr.sample(frac=1).reset_index(drop=True).rename(columns={"class": "target"})
df... | 76463f6621c7beb09966793ef4954cf711be290d | 56,863 |
def recode_factor(
_x,
*args,
_default=None,
_missing=None,
_ordered=False,
**kwargs,
):
"""Recode a factor
see recode().
"""
values = _args_to_recodings(*args, **kwargs)
recoded = recode.dispatched.dispatch(Series)(
_x,
values,
_default=_default,
... | 820de4a8c29f3efd121d907d63c9715c2ca06ae4 | 56,864 |
def randomly_sample_window_from_signal(original_signal, window_len, random_seed_val=None):
"""
data_preprocessing_utils.randomly_sample_window_from_signal: returns the data sample referenced by index in self.curr_subset_sample_index_map
- Inputs:
* original_signal (numpy ndarray): an array o... | bc887309ad1955a67fa245eb20db45d5c43ccb1e | 56,865 |
def num_atom_features():
"""
This function returns the number of atomic features that are available by this module.
Returns
-------
n_features : int
length of atomic feature vector.
"""
m = Chem.MolFromSmiles('CC')
alist = m.GetAtoms()
a = alist[0]
return len(atom_featur... | 92a7b6cc16505a49b03033c560815a3f49e4f089 | 56,866 |
from oggm.core.massbalance import LinearMassBalance, ConstantMassBalance
from oggm.core.centerlines import line_inflows
def gridded_mb_attributes(gdir):
"""Adds mass-balance related attributes to the gridded data file.
This could be useful for distributed ice thickness models.
The raster data are added t... | 60d690036450376f8f9209754225028663f0faff | 56,867 |
from typing import Iterator
def get_variable_slices(
source_code: str,
lang: Lang,
slice_predicate: SlicePredicate = None,
include_noneffective: bool = True) -> Iterator[ProgramSlice]:
"""
For each function and variable in a specified source code generate list of Program Slices... | c74cb5c586bdd208f904c4209b80018524440a6a | 56,868 |
def NECout():
"""Test read of NEC .out file."""
basefile = 'Lofar-dipole-FREE.out'
fileloc = NECdir+basefile
atvfd = NECread.readNECout_tvecfuns(fileloc)
antFF = RadFarField(atvfd)
return antFF | 2049fe87c25c961fd6f69431fc76de4d13f150cc | 56,869 |
import argparse
def check_arg():
"""Make the parsing of CLI call
Returns:
[tupla] -- [Namespaces of the parameters passed to the cli]
"""
parse = argparse.ArgumentParser(
prog="git-sync",
usage="%(prog)s [-h|--help] ",
description="keep sync remote git repo with a loca... | 5277583ee6c191af6d32b2bc466005ede7b4aea2 | 56,870 |
def exsafeSlot(*slargs, **slkwargs):
"""Wrapper around ``PyQt5.QtCore.pyqtSlot`` which intercepts exceptions and stops the execution in a controlled manner"""
def wrapper(func):
return QtCore.pyqtSlot(*slargs,**slkwargs)(exsafe(func))
return wrapper | 0353cffc87b94b6387af9c89103ecd6c1bb32c2f | 56,871 |
def goto(avIdShort):
""" Teleport to the avId specified. """
avId = 100000000+avIdShort # To get target doId.
toon = simbase.air.doId2do.get(avId)
if not toon:
return "Unable to teleport to target, they are not currently on this district."
spellbook.getInvoker().magicWordTeleportRequests.app... | b064727d8cfbbc20102e2e8fd9b1e07ec24141b0 | 56,872 |
def _get_mongo_expression_for_type_filter(requested_file_types):
"""
Construct and return pymongo expression dict for the named content type categories.
The named content categories are the keys of the FILES_AND_UPLOAD_TYPE_FILTERS setting that are not 'OTHER':
'Images', 'Documents', 'Audio', and 'Code... | 094732cdc9f204ab110c14a87687064773d7d089 | 56,873 |
import os
import shutil
def install_dir(pkgpath, install_path, register_func, delete_after_install=False):
"""Install plugin from specified directory.
install_path and register_func are same as :func:`install_plugin`.
:param delete_after_install: Delete pkgpath after install (used in :func:`install_from_... | 83fca283b79eb8e1169c465ddb921db3b81f8615 | 56,874 |
def segs2nodes(segs, logFileName, error = False):
"""inputs a segment dataframe, brings in references that were calculated, and calculates x,y, and z values for base and top"""
""" If no rows need calculating the code skips the calculation process and outputs the input dataframe, this is to be efficient when wh... | ed6d0ff211bf94e39b8508c67671711f35956e73 | 56,875 |
def _run_cmd(cmd):
"""Run a shell command `cmd` and return its output."""
return check_output(cmd, shell=True).decode("utf-8") | b936b294ac14e163dca60a9d925f6714b7e0b12e | 56,876 |
import random
def new_viable_indiv(payload):
"""
Return a new indiv, create from given individuals
crossing in given configuration, eventually mutated.
Indiv is viable.
Payload argument must be a 2tuple that contain individuals and configuration.
(multithreading compatibility)
"""
in... | 3c6e324d1574143f1c69016891a1e981e0ec3281 | 56,877 |
import os
def generate_data_files(dirs=['launch', 'gazebo/worlds', 'gazebo/models']):
"""
Generate recursive list of data files, without listing directories in the output.
"""
data_files = []
for path, _, files in chain.from_iterable(os.walk(dir) for dir in dirs):
install_dir = path[len('g... | 5ea2a021939caf24287ccee24b27d4373594e433 | 56,878 |
def get_filename(name):
"""Return absolute path to a picture located in the current package.
:param name: name of an image located in language folders
:type name: str
:return: absolute image path
:rtype: str
"""
return osp.join(osp.dirname(osp.abspath(__file__)), 'assets', name) | 3529aaa089257ab5e394081456a57931bcbc49b2 | 56,879 |
def _setup_browser(dl_dir, mime_type):
"""Setup Firefox headless browser.
Parameters
----------
dl_dir : str
Path to the download dir.
mime_type : str
MIME-type that can be automatically downloaded.
Returns
-------
browser : selenium.webdriver.firefox.webdriver.WebDrive... | a759a8bf05217f93caf587017b39ae2ea7e47725 | 56,880 |
import re
def get_csrf_token(res):
"""Extract the CSRF token from a response."""
for header in res.headers:
m = re.search('token=(.+?);', header[1])
if m:
return m.group(1)
raise RuntimeError('Could not find CSRF token in response headers: ' + str(res.headers)) | 2c2670a6909ed87d60b44a5cf1cbaeffdc4fc653 | 56,881 |
def interpolate_evaluation_dose_at_distance(
evaluation_interpolation,
axes_reference_to_be_checked,
coordinates_at_distance_shell,
):
"""Determine the evaluation dose for the points a given distance away for
each reference coordinate.
"""
all_points = add_shells_to_ref_coords(
axes_... | 64e2be10cf04436d90789487cdb9c66cbafe3927 | 56,882 |
def direction_of_climbing(**kwargs):
"""
Uses the Nose tracking point to determine the direction of climbing.
When starting a new project the user gets the option to define how the direction of climbing should be determined:
- direction of movement in the video (2 variants, see below)
... | f55198ec1f94302367d689c8769bd578ff22f1e7 | 56,883 |
from typing import Union
def _auto_prefix_kg(value: float, power: Union[int, float]) -> str:
"""
Just like _auto_prefix but handles the one special case for "kg" because it already
has a prefix of "k" as an SI base unit. The difference is the comparison of
'power_of_ten'/1000 vs 'power_of_ten'.
""... | 3f9ec2dbc1cbde25b3865d5ce4617f7064354348 | 56,884 |
from pathlib import Path
import os
def path_to_db_path(path: Path):
"""Converts a pathlib.Path to a DBFS path"""
db_path = str(path).replace("\\", "/")
db_path = os.path.splitext(db_path)[0]
return db_path | 023703da2652f64de39491a64252a692d7aef886 | 56,885 |
import os
def get_file_name_without_extension(path):
"""
>>> get_file_name_without_extension('yuv/src01_hrc01.yuv')
'src01_hrc01'
>>> get_file_name_without_extension('yuv/src01_hrc01')
'src01_hrc01'
>>> get_file_name_without_extension('abc/xyz/src01_hrc01.yuv')
'src01_hrc01'
>>> get_f... | 41205075cdbae83cd951a82fffd4448ce2319762 | 56,886 |
from typing import OrderedDict
def wrap_estimator(cls,
bases,
name=None,
module=None,
default_params=None,
is_generic=True,
custom_params=None):
"""
Creates a `sklearn`-compatible wrapper class fr... | b4ba0415864ba4ae652c8eca04b5aa1d3e92beec | 56,887 |
def create_flat_view(array):
"""返回数组的一维视图"""
flat_view = array.view()
flat_view.shape = array.size
return flat_view | 694953f72ad279f347bdc666f73ca21d843046e3 | 56,888 |
def create_to_idx_dict(source):
""" Creates a dictionary of item-specific indices form a tuple of lists. """
idx_dict = dict()
for i in source:
if i not in idx_dict:
idx_dict[i] = len(idx_dict)
return idx_dict | 0c8de2455b4fa78b4c29b75879c87f1ee2a2de40 | 56,889 |
from scipy.dsp import correlate
def xcorr(data, target, **kwargs):
"""
Cross-correlate two 1D.dsps.
Notes
-----
Detrend / taper first?
"""
shift = np.argmax(correlate(data, target)) - len(target) #+ 10
datan = np.zeros(len(data))# - shift)
if shift > 0:
datan[ :-shift] = data[shift: ... | 46a0be27758a25f4e24634a1a33b6bd38d41c906 | 56,890 |
from datetime import datetime
import time
def get_term_index(term_partial,
term_field="text",
core="docs",
req_url:str=None,
limit=opasConfig.DEFAULT_LIMIT_FOR_SOLR_RETURNS,
offset=0,
start_at=None, # a ... | 4e9070ba942393daa65d00e6ad2a45370aacc4ba | 56,891 |
def read(path):
"""
read wave data like matlab's audioread
"""
return sf.read(path)[0] | e781ba05cfd50a6b0fb7537c65d5f424f2f5f16a | 56,892 |
def decode(token):
"""Decode data in jwt token."""
return jwt.decode(token, app.config['JWT_SECRET'], algorithms=['HS256']) | ec62f6ced3778604ec35bc9e95ea18b5bdc5d7ee | 56,893 |
def get_reduce_out_shape(src_shape, axis=None, keepdims=False):
"""Get the output shape for the reduction OPs
Parameters
----------
src_shape : tuple of int or tvm.expr.IntImm
axis : None or int or tuple of int
keepdims : bool
Returns
-------
dst_shape : tuple of int or tvm.expr.... | 99d8bf7cbf4217d2cdeb511ca3c9ffd1d74c6b3c | 56,894 |
def init_mps_allzero(nsites, physdim, left_label='left',
right_label='right', phys_label='phys'):
"""
Create an MPS with `nsites` sites in the "all zero" state |00..0>.
Parameters
----------
nsites : int
physdim : int or list of ints
left_label : str
right_label : s... | 9bc7483d329fb15ee0f56c11e7fea7c8ad4c8e84 | 56,895 |
def get_input_geo(geo):
"""Similar to get_input_peer, but for geo points"""
if not isinstance(geo, TLObject):
_raise_cast_fail(geo, 'InputGeoPoint')
if type(geo).SUBCLASS_OF_ID == 0x430d225: # crc32(b'InputGeoPoint')
return geo
if isinstance(geo, GeoPoint):
return InputGeoPoin... | 82c3f8b59d331c018359f8500f1635b9bbfd9579 | 56,896 |
import inspect
def post_process_subclass_of(response, verbose=0):
"""
postprocess the response of the "subclass of" query
:param dict response: api response
:rtype: set of tuples
:return: {(wd_uri, wd_uri)}
"""
set_of_relations = set()
for info in response['results']['bindings']:
... | f7fa3b689ab9ddbfbcf69d8035ed4efa34576173 | 56,897 |
def _Fprime(mu, r0, vr0, inv_a, x):
"""Compute the first derivative of the Kepler equation in Universal
variables formulation
Parameters
----------
mu : float
Gravitational parameter [AU^3/days^2][description]
r0 : float
Modulus of the initial radio vector
vr0 : float
... | 8eac6cc6a8ed57565bf97313358ab6fc5c046186 | 56,898 |
def homepage():
"""List all available api routes."""
return (
f"Welcome to Hawaii - Climate Page<br/>"
f"<br/>"
f"This site has data from 01-01-2010 to 08-23-2017<br/>"
f"<br/>"
f"Available Pages:<br/>"
f"<br/>"
f"<br/>"
f" Station Information<br/... | 5c781d229d475ab4253b21c8f5002a020928fae9 | 56,899 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.