content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def calc_overlap(row):
"""
Calculates the overlap between prediction and
ground truth and overlap percentages used for determining
true positives.
"""
set_pred = set(row.predictionstring_pred.split(' '))
set_gt = set(row.predictionstring_gt.split(' '))
# Length of each and intersection
... | 5,322,900 |
def test_list_normalized_string_length_1_nistxml_sv_iv_list_normalized_string_length_2_1(mode, save_output, output_format):
"""
Type list/normalizedString is restricted by facet length with value 6.
"""
assert_bindings(
schema="nistData/list/normalizedString/Schema+Instance/NISTSchema-SV-IV-list... | 5,322,901 |
def test_associate_user_in_company(logged_client, user):
"""
Should redirect and send a success message after associating the user
"""
company = CompanyFactory.create()
ASSOCIATE_URL = reverse('companies:associate', kwargs={'company': company.id})
response = logged_client.post(ASSOCIATE_URL, d... | 5,322,902 |
def delete_all():
""" Clear the config list """
def check_path(folder=None):
""" Check if the folder exist and return boolean """
return isdir(folder._fullpath)
# Clear the config list:
kill_list = [elem for elem in config['Elements'] if elem._hide == 0 or check_path(elem) == 0]
if... | 5,322,903 |
def get_range(l_list,l_position):
""" Obtaining range of points in list (optionally at position inside of list)"""
l_range = 0
l_abs_range = 0
l_max = 0
l_min = 0
ll_list = []
counter = 0
if l_position == None:
ll_list = l_list
else:
while counter < len(l_list)... | 5,322,904 |
def equalise_paragraphs(a_para, b_para, sentence_ratio=DEFAULT_SENTENCE_RATIO, lowercase_glued=DEFAULT_LOWERCASE_GLUED,
stop_chars=DEFAULT_STOP_CHARS):
"""
Glues together two collections of sentences so that they're of similar
word-length. Discards sentences it cannot make parallel.
... | 5,322,905 |
def build_summary_rendering_context(schema_json, answer_store, metadata):
"""
Build questionnaire summary context containing metadata and content from the answers of the questionnaire
:param schema_json: schema of the current questionnaire
:param answer_store: all of the answers to the questionnaire
... | 5,322,906 |
def _bucket_from_workspace_name(wname):
"""Try to assert the bucket name from the workspace name.
E.g. it will answer www.bazel.build if the workspace name is build_bazel_www.
Args:
wname: workspace name
Returns:
the guessed name of the bucket for this workspace.
"""
revlist = [... | 5,322,907 |
def load_results_with_table_definition(
result_files, table_definition, table_definition_file, options
):
"""
Load results from given files with column definitions taken from a table-definition file.
@return: a list of RunSetResult objects
"""
columns = extract_columns_from_table_definition_file... | 5,322,908 |
def main():
"""
Instanitates and trains Model
"""
lr = 1e-4
batch_size = 64
n_epochs = 10
steps = 30
train_data, test_data = preprocess_data()
model = RNN(units=64, n_layers=2)
# build
model.compile(optimizer=tf.keras.optimizers.Adam(lr),
loss=tf.kera... | 5,322,909 |
def CIFAR10(flatten=True, split=[1.0, 0.0, 0.0]):
"""Returns the CIFAR10 dataset.
Parameters
----------
flatten : bool, optional
Convert the 3 x 32 x 32 pixels to a single vector
split : list, optional
Description
Returns
-------
cifar : Dataset
Description
... | 5,322,910 |
def plot_change_trend(trend_data, pid_data, pid, interval=None):
"""Plots 4 subplots showing project budget and duration forecast change trend
Generates image of 4 subplots, no objects are returned.
:param trend_data: pd.DataFrame, the cleaned dataset of all project change
records (... | 5,322,911 |
def _cut_daytime(visi, tmstp):
"""Returns visibilities with night time only.
Returns an array if a single night is present.
Returns a list of arrays if multiple nights are present.
"""
tstp = tmstp[1] - tmstp[0] # Get time step
risings = ch_eph.solar_rising(tmstp[0], tmstp[-1])
settings =... | 5,322,912 |
def test_box_holds_on_to_its_value():
"""
:boxes ( box -> ) import
:x def
x box :b def
{b ->}, {x}, =
{b ->}, {x}, =
{b ->}, {x}, =
""" | 5,322,913 |
def make_empirical_distributions(paramlist, params, chain,
burn=0, nbins=50):
"""
Utility function to construct empirical distributions.
:param paramlist: a list of parameter names,
either single parameters or pairs of parameters
:pa... | 5,322,914 |
def decay(epoch):
""" This method create the alpha"""
# returning a very small constant learning rate
return 0.001 / (1 + 1 * 30) | 5,322,915 |
def nopen(options):
"""Upload noserver to the target and have it call back"""
addr = get_details_for_etag(options)
if addr is None:
logging.error("ERROR: No entry for ETag [%s] in %s." %
(options.etag, options.etag_file))
logging.error(" Perhaps you should run wit... | 5,322,916 |
def timer_function(function):
"""Print time taken to execute a function"""
@functools.wraps(function)
def inner_function(name):
start = time.perf_counter()
function(name)
end = time.perf_counter()
total = end-start
print(start, end)
print(f"The function finish... | 5,322,917 |
def blob_delete(cache, key, namespace):
# type: (Any, str, Optional[str]) -> bool
"""Delete stored values from memcache"""
chunk_keys = blob_get_chunk_keys(cache, key, namespace=namespace)
if not chunk_keys:
# Keys are not set, no need to remove them.
return True
keys_to_delete = list(chunk_keys)
... | 5,322,918 |
def shape_equality_robust_statistic(𝐗, args):
""" GLRT test for testing a change in the shape of
a deterministic SIRV model.
Inputs:
* 𝐗 = a (p, N, T) numpy array with:
* p = dimension of vectors
* N = number of Samples at each date
* T ... | 5,322,919 |
async def action(bot, msg):
"""**!8ball**
Responds to a yes-no question."""
answer = random.choice(answers)
await bot.send_message(msg.channel, answer) | 5,322,920 |
def refresh_asr(items):
"""刷新数据浏览器项目数据"""
with AdvanceSearcher() as api:
pos_list = api.pos_list
for pos in pos_list:
name = api.level_to_name(pos)
if name not in items:
continue
api.to_level(pos)
coll = get_coll(name)
i... | 5,322,921 |
def get_attrib_uri(json_dict, attrib):
""" Get the URI for an attribute.
"""
url = None
if type(json_dict[attrib]) == str:
url = json_dict[attrib]
elif type(json_dict[attrib]) == dict:
if json_dict[attrib].get('id', False):
url = json_dict[attrib]['id']
elif json... | 5,322,922 |
def test_valdshortline():
"""Test code paths and cases in vald.ValdShortLine().
"""
for vslstr in vald_short_line_strings:
vsl = ValdShortLine(vslstr)
assert isinstance(vsl, ValdShortLine)
assert vsl.__str__() == vslstr
assert vsl.__repr__() == type(vsl).__name__ + f'({vslstr... | 5,322,923 |
def set_model_params(module, params_list, start_param_idx=0):
""" Set params list into model recursively
"""
param_idx = start_param_idx
for name, param in module._parameters.items():
module._parameters[name] = params_list[param_idx]
param_idx += 1
for name, child in module._module... | 5,322,924 |
def push(local_path, remote_path):
"""Upload a file to the device.
Arguments:
local_path(str): Path to the local file to push.
remote_path(str): Path or directory to store the file on the device.
Returns:
Remote path of the file.
Example:
>>> write('./filename', 'cont... | 5,322,925 |
def main(_) -> None:
"""Train and evaluate the Ranking model."""
params = train_utils.parse_configuration(FLAGS)
mode = FLAGS.mode
model_dir = FLAGS.model_dir
if 'train' in FLAGS.mode:
# Pure eval modes do not output yaml files. Otherwise continuous eval job
# may race against the train job for writin... | 5,322,926 |
def export_shapes(model, path=Path('.')):
"""Export a hydamo class to shape-files."""
path = Path(path)
path.mkdir(exist_ok=True)
for attribute in ATTRIBUTES:
to_file(model, attribute, length=False, path=path)
to_file(model, "branches", length=True, path=path) | 5,322,927 |
def concatIDF(idfObjectList, param):
"""Create tab separated strings from input yaml parameter objects"""
outString = ""
for obj in idfObjectList:
outString += "\t" + str(noneClean(obj.params[param]))
return outString | 5,322,928 |
def super_class_property(*args, **kwargs):
"""
A class decorator that adds the class' name in lowercase as a property of
it's superclass with a value constructed using the subclass' constructor with
the given arguments. So for example:
class A:
pass
@super_class_property(foo=5)
class B(A):
... | 5,322,929 |
def run_deferred_and_advance_now_until(ctx, u, until):
"""
Find all rows in the deferred table where the run_at time has passed for the given user and
run the deferred action. gametime.now is set to the deferred actions run_at value to simulate
the production environment when run from a cronjob.
NOT... | 5,322,930 |
def get_group_type_by_name(context, name):
"""Retrieves single group type by name."""
if name is None:
msg = _("name cannot be None")
raise exception.InvalidGroupType(reason=msg)
return db.group_type_get_by_name(context, name) | 5,322,931 |
def hdfs_to_local(hdfs_path, local_path, is_txt=True):
"""copy hdfs file to local
param:
* hdfs_path: hdfs file or dir
* local_path: local file or dir
return:
* res: result message
"""
res = ''
if is_txt:
f = os.popen("hadoop dfs -text {} > {}".format(hdfs_path, local_path))... | 5,322,932 |
def register_tortoise_exception(
app: FastAPI,
add_exception_handlers: bool = False,
) -> None:
""" rewrite from tortoise.contrib.fastapi import register_tortoise
"""
if add_exception_handlers:
@app.exception_handler(DoesNotExist)
async def doesnotexist_exception_handler(requ... | 5,322,933 |
def test_tcp_sizes(server_ip_address,
dev,
timeout):
"""Perform the TCP stress test.
"""
print("run.py: opening socket")
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Wait for the TCP test to start.
dev.expect("listening on {}\r\n".format(TCP... | 5,322,934 |
def norm_m(matrix, norm):
"""
Normaliza la matriz pasada con un formato float64 bits
tipo de nomalizacion l1
:param matrix: {array-like, sparse matrix}, shape [n_samples, n_features]
The data to normalize, element by element.
scipy.sparse matrices should be in CSR format to avoid an un-necessar... | 5,322,935 |
def test_check_input_nolandmask():
"""Test that the check input can run without a landmap."""
# call checker function
chmap, landmap, basevalues, time_window = mob.check_inputs(chmask,
[0], 1)
# assert types
assert isinstance(chmap, np.n... | 5,322,936 |
def user_from_dict(user_dictionary: dict):
"""
The function converts a dictionary of User to a User object.
:param user_dict: A dictionary that contains the keys of a User.
:type user_dict: dict
:rtype: ibmpairs.query.User
:raises Exception: if not a dict.... | 5,322,937 |
def plotq1(xc, qsoln, auxsoln, time, ini_params, m ):
"""Default plotting file.
This routine provides a handle that a user can swap out in a single
application. Here, we provide a minimal working example that allows one
to plot results. For most problems, a user will likely want to swap this
out ... | 5,322,938 |
def bot_events_startup_complete(bot, trigger):
"""All events registered as required for startup have completed"""
spicebot.events.trigger(bot, spicebot.events.BOT_LOADED, "All registered modules setup procedures have completed") | 5,322,939 |
def lind_safe_fs_getdents(args):
""" Safely wrap the getdents call.
See dispatcher.repy for details.
Check the handle and count for consistancy,
then call the real getdents dispatcher.
"""
handle = args[0]
count = args[1]
check_valid_fd_handle(handle)
assert isinstance(count, int... | 5,322,940 |
def parser(): # parsing the whole circuit into lists of objects
""" Start of Parse .nodes """
file = open("{}.nodes".format(fileName))
lines = file.readlines()
saved = 0
node_list = [] # List of all nodes for the current circuit
# Locate NumNodes + NumTerminals
... | 5,322,941 |
def graph_from_mol_new(sdf_file, mol2_file, key, cache_path, path_marker):
"""
1. add acsf descriptor
:param sdf_file:
:param mol2_file:
:param key:
:param cache_path:
:param path_marker:
:return:
"""
# small molecule
# new_order = rdmolfiles.CanonicalRankAtoms(m)
# mol =... | 5,322,942 |
def header(columns):
"""Create html for column headers."""
cells = add_bars(columns)
return div(docfilter, div(*cells, cls='noselect'), id='header') | 5,322,943 |
def WithOutListDataInsertFormDataBySerialNo(SerialNo, rawData, UserID, processID):
"""
根据任务流水号和原始数据插入数据库
:param SerialNo:任务流水号
:param rawData:插入之前的原始数据字典列表
:param UserID:插入数据的检验员工号
:param processID:表格ID
:return:
"""
selectedStep = rawData.pop('selectedStep') if 'selectedStep' in rawData else "" #... | 5,322,944 |
def train(mmdict, df, params, ndisp, saveto=None, tloss=.001):
"""Train the autoencoder neural network and save the results
Arguments:
mmdict -- dictionary of memory map files
params -- dictionay of parameters
"""
tf.reset_default_graph()
width = params['width']
height = p... | 5,322,945 |
def set_playbook_config(ctx, **kwargs):
"""
Set all playbook node instance configuration as runtime properties
:param _ctx: Cloudify node instance which is instance of CloudifyContext
:param config: Playbook node configurations
"""
def _get_secure_values(data, sensitive_keys, parent_hide=False):... | 5,322,946 |
def get_services_accounting_flow(device, field, output=None):
""" Get value of field from show services accounting flow
Args:
device (`obj`): Device object
field (`str`): field name in show output
output (`str`): output of show services accounting flow
Returns:
... | 5,322,947 |
def moving_window_stride(array, window, step):
"""
Returns view of strided array for moving window calculation with given window size and step
:param array: numpy.ndarray - input array
:param window: int - window size
:param step: int - step lenght
:return: strided: numpy.ndarray - view of strid... | 5,322,948 |
def leave_p_out_indices(p, inputs, targets=None, max_num_folds=None, shuffle=True,
random_state=None, print_indices=True, **kwargs):
"""
Leave p out cross validation.
Args:
p: An integer representing the number of samples to leave out for test.
inputs: A numpy ndarray... | 5,322,949 |
def rollback(options, config):
"""Rollback the current production AWS Lambda version by 1
Notes:
Ignores if the production version is $LATEST
Only rollsback if published version is greater than 1
"""
clusters = config.clusters()
if 'all' in options.processor:
lambda_functio... | 5,322,950 |
def _run_purple(paired, het_file, depth_file, vrn_files, work_dir):
"""Run PURPLE with pre-calculated AMBER and COBALT compatible inputs.
"""
purple_dir = utils.safe_makedir(os.path.join(work_dir, "purple"))
out_file = os.path.join(purple_dir, "%s.purple.cnv" % dd.get_sample_name(paired.tumor_data))
... | 5,322,951 |
def ecef2geodetic(ecef, radians=False):
"""
Convert ECEF coordinates to geodetic using ferrari's method
"""
# Save shape and export column
ecef = np.atleast_1d(ecef)
input_shape = ecef.shape
ecef = np.atleast_2d(ecef)
x, y, z = ecef[:, 0], ecef[:, 1], ecef[:, 2]
ratio = 1.0 if radians else (180.0 / n... | 5,322,952 |
def merge(sorted1, sorted2):
"""Merge two sorted lists into a single sorted list."""
if sorted1 == ():
return sorted2
elif sorted2 == ():
return sorted1
else:
h1, t1 = sorted1
h2, t2 = sorted2
if h1 <= h2:
return (h1, merge(t1, sorted2))
else:
... | 5,322,953 |
def reloadImage():
"""
http://help.autodesk.com/cloudhelp/2019/ENU/Maya-Tech-Docs/CommandsPython/reloadImage.html
-----------------------------------------
reloadImage is undoable, NOT queryable, and NOT editable.
This command reloads an xpm image from disk. This can be used when the file
has changed on disk a... | 5,322,954 |
def write_gpt_fieldmesh(fm,
outfile,
asci2gdf_bin=None,
verbose=False):
"""
Writes a GPT fieldmap file from a FieldMesh object.
Requires cylindrical geometry for now.
"""
assert fm.geometry == 'cylindrical', f'Geometry: {fm.geometry}... | 5,322,955 |
def docker_registry_secure(
docker_client: DockerClient,
docker_compose_secure: Path,
docker_registry_auth_header: Dict[str, str],
docker_registry_cacerts: Path,
docker_registry_certs: DockerRegistryCerts,
docker_registry_htpasswd: Path,
docker_registry_password: str,
docker_registry_ssl... | 5,322,956 |
def _execute_and_commit(statement, view_name=None):
"""Execute an SQL statement; used to parallelize view refereshes"""
with _sqlalchemy_connection() as conn:
with conn.begin() as trans:
trans.execute(statement)
if view_name:
cur.execute('ANALYZE {};'.format(view_na... | 5,322,957 |
def executable_task_instance_post_save_handler(instance, created, **_):
"""Adds additional behavior after saving a task instance.
Right now this just queues up the task instance upon creation.
Args:
instance: The task instance just saved.
created: A boolean telling us if the task instance ... | 5,322,958 |
def setup_clang():
"""
Make sure clang is set up correctly for the sphinx_c_autodoc extension.
The Python clang package requires a matching libclang*.so. Our
``doc/requirements.txt`` file specifies ``clang==10.0.1``, so we need
``libclang-10``.
On Ubuntu 20.04 (and possibly later), this can be... | 5,322,959 |
def _build_bundleitems_update_request(player_id, bundle_name, bundle_item_key, bundle_item_value):
"""
Build the Bundle Items update request.
"""
player_id_bundle = f'{player_id}_{bundle_name}'
timestamp = datetime.utcnow().replace(tzinfo=timezone.utc).isoformat()
return {
'Key': {
... | 5,322,960 |
def dask_read_avro(urlpath, blocksize=100000000, storage_options=None):
"""Read set of avro files into dask dataframes
Use this only with avro schema that make sense as tabular data, i.e.,
not deeply nested with arrays and maps.
Parameters
----------
urlpath: string or list
Absolute or... | 5,322,961 |
def msgs_csv(messages, header):
"""Return messages in .csv format."""
queue = cStringIO.StringIO()
writer = csv.writer(queue, dialect=csv.excel, quoting=csv.QUOTE_ALL)
if header:
writer.writerow(['Date', 'From', 'To', 'Text'])
for m in messages:
writer.writerow([m['date'].encode('utf... | 5,322,962 |
def alpha_s_plot_parameters(
alpha_curve: "list[float]",
loading: "list[float]",
section: "list[float]",
alpha_s_point: float,
reference_area: float,
molar_mass: float,
liquid_density: float,
):
"""Get the parameters for the linear region of the alpha-s plot."""
slope, intercept, co... | 5,322,963 |
def _MutualInformationTransformAccumulate(pcol): # pylint: disable=invalid-name
"""Accumulates information needed for mutual information computation."""
return (pcol | 'VocabCountPerLabelPerTokenAccumulate' >> beam.CombinePerKey(
_CountAndWeightsMeansCombineFn())) | 5,322,964 |
def process_other_logs(other_logs):
"""
Takes a dictionary of Display Name, filename pairs for logs in the IDS_LOG_DIRECTORY and poulates
the JOB_OTHER_LOGS with a dictonary containing the Display Name and file contents.
"""
global JOB_OTHER_LOGS, IDS_LOG_DIRECTORY, SENSOR_TECHNOLOGY
print_debu... | 5,322,965 |
def test_flatten_context():
"""Ensures that `join` works with Context."""
assert flatten(
Context.unit(Context.unit(1)),
)(Context.Empty) == 1 | 5,322,966 |
def GTLRU(input_a, input_b, n_channels: int):
"""Gated[?] Tanh Leaky ReLU Unit (GTLRU)"""
in_act = input_a+input_b
t_act = torch.tanh(in_act[:, :n_channels, :])
r_act = torch.nn.functional.leaky_relu(in_act[:, n_channels:, :], negative_slope=0.01, inplace=True)
acts = t_act * r_act
return acts | 5,322,967 |
def get_items_by_category(category_id, limit, offset=None):
"""
Return items from catalog by category with limit and offset
:param category_id:
:param limit:
:param offset:
:return object:
"""
return session.query(Catalog).filter_by(
category=category_id).offset(offset).limit(li... | 5,322,968 |
def cosine(u, v, w=None):
"""
Compute the Cosine distance between 1-D arrays.
The Cosine distance between `u` and `v`, is defined as
.. math::
1 - \\frac{u \\cdot v}
{||u||_2 ||v||_2}.
where :math:`u \\cdot v` is the dot product of :math:`u` and
:math:`v`.
Para... | 5,322,969 |
def adjust_site_parameters(site):
"""Updates extra parameters with applicable datastreams from
`arm_reference_sites.json`
Parameters
----------
site: dict
Returns
-------
dict
Copy of input with updated extra parameters.
"""
with open(DEFAULT_SITEFILE) as fp:
si... | 5,322,970 |
def slice_repr(slice_obj):
"""
Get the best guess of a minimal representation of
a slice, as it would be created by indexing.
"""
slice_items = [slice_obj.start, slice_obj.stop, slice_obj.step]
if slice_items[-1] is None:
slice_items.pop()
if slice_items[-1] is None:
if slice... | 5,322,971 |
def test_trailing_eos(dataset):
"""
Test if sentences in id representation always have an trailing EOS token.
Arguments:
dataset (LJSpeechDatasetHelper):
Dataset loading helper instance.
"""
# Load all samples from the dataset.
n_samples = None
id_sentences, sentence_le... | 5,322,972 |
async def isAtLeastInstructor(context: commands.Context) -> bool:
"""
Returns true if context.author is either an admin or an instructor and False otherwise
:param context:
:return:
"""
return await isInstructor(context) or await isAdmin(context) | 5,322,973 |
def _prob_to_dets(probs, diameter=None, offset=None, class_probs=None,
keypoints=None, min_score=0.01, num_min=10,
max_dims=None, min_dims=None):
"""
Directly convert a one-channel probability map into a Detections object.
Helper for Heatmap.detect
It does this by c... | 5,322,974 |
async def test_async_send_calls_have_async_call(
event_loop: asyncio.AbstractEventLoop,
) -> None:
"""Verify async_send_* methods have an async_* pair."""
for name, value in inspect.getmembers(client.HyperionClient):
if name.startswith("async_send_") and callable(value):
new_name = "asyn... | 5,322,975 |
def pad_sequences(sequences, pad_symbol, max_length=None,
mask_present_symbol=None, padding_mode='both'):
"""
Pads a collection of sequences. Will work only for two dimensional data.
:param sequences: list or np array, which has sequences (lists or np arrays)
that ... | 5,322,976 |
def cli(env, storage_type, size, iops, tier, os_type,
location, snapshot_size):
"""Order a block storage volume."""
block_manager = SoftLayer.BlockStorageManager(env.client)
storage_type = storage_type.lower()
if storage_type == 'performance':
if iops is None:
raise exceptio... | 5,322,977 |
def post_has_mime_parts(request, parts):
"""Validate that a MMP POST contains all required sections.
:param request: Django Request
:param parts: [(part_type, part_name), ...]
:return: None or raises exception.
Where information is stored in the request:
part_type header: request.META['HTTP_<U... | 5,322,978 |
def cast_cal_range(cal_range: Sequence[raw_mz_type]) -> Tuple[float, float]:
"""
:param cal_range:
"""
min_val, max_val = cal_range
return float(min_val), float(max_val) | 5,322,979 |
def get_warc_identifiers(sip):
"""Parses the SIP in HDFS and retrieves WARC/ARK tuples."""
w = webhdfs.API(prefix=WEBHDFS)
identifiers = []
tar = "%s/%s.tar.gz" % (SIP_ROOT, sip)
if w.exists(tar):
logger.debug("Found %s" % tar)
t = w.open(tar)
tar = tarfile.open(mode="r:gz", fileobj=StringIO(t))
for i in t... | 5,322,980 |
def rebarxl():
"""
rebarxl()
Outputs a simple rebar table delimited with spaces. Used for
pasting a rebar table into excel for use with VLOOKUP etc.
"""
print("size dia area wt")
for bar in [3,4,5,6,7,8,9,10,11,14,18]:
b = Bar(bar)
print("{0} {1} {2} {3}".format(b.... | 5,322,981 |
def add_card(handler_input, response):
"""Add a card by translating ssml text to card content."""
# type: (HandlerInput, Response) -> None
response.card = SimpleCard(
title=skill_name,
content=convert_speech_to_text(response.output_speech.ssml)) | 5,322,982 |
def refresh_cache() -> None:
"""Refresh caches which is older than 40sec.
If Failed to download information, it tries to download up to 4 times.
"""
for distributor in Distributor:
if not distributor.is_valid():
continue
if _load(distributor=distributor, expire_second=40) i... | 5,322,983 |
def request_get(url):
"""
Realisa una solicitud 'GET' en la url proporcinada, si se realiza con exito retorna el contenido
y se ocurre algun error retorna 'None'
Parametro 'url' direccion del sitio web
return: 'requests.get.content'
"""
try:
with closing(get(url, stream=True)) as ... | 5,322,984 |
def in_virtualenv_currently():
"""Check whether currently running inside of a virtualenv or not"""
return get_base_prefix_compat() != sys.prefix | 5,322,985 |
def make_tensor(tensor):
""" 转换numpy数组到potobuf格式 """
shape = projector_pb2.Tensor.TensorShape(dim=[projector_pb2.Tensor.TensorShape.Dim(size=d)
for d in tensor.shape])
return projector_pb2.Tensor(dtype=str(tensor.dtype),
tens... | 5,322,986 |
def pad(sequences, max_length, pad_value=0):
"""Pads a list of sequences.
Args:
sequences: A list of sequences to be padded.
max_length: The length to pad to.
pad_value: The value used for padding.
Returns:
A list of padded sequences.
"""
out = []
for sequence in ... | 5,322,987 |
def dict_blocks_decoder(nB, v, step, lookup: dict, dec_fmt: str):
"""
Decodes a single block from a NORB pooling design
"""
ds = Design()
dm = ds.matrix
decoder = DictBlockDecoder(dm, lookup, format=dec_fmt)
res = []
for b in range(nB):
p = v.squeeze()[step*b:step*b + step]
... | 5,322,988 |
def _build_circuit_layers_and_connectivity_nearest_neighbors(n_qubits):
"""Function to generate circuit layers for processors with nearest-neighbor
connectivity
Args:
n_qubits (int): number of qubits in the qubit array
Returns:
(zquantum.core.circuit.CircuitConnectivity, zquantum.core.ci... | 5,322,989 |
def band_colormap( cmap, nband=10 ):
""" -> a colormap with e.g. 10 bands """
cmap = get_cmap( cmap )
h = .5 / nband
A = cmap( np.linspace( h, 1 - h, nband ))
name = "%s-band-%d" % (cmap.name, nband)
return array_cmap( A, name, n=nband ) | 5,322,990 |
def rolling_optimal_combo_stats(ret1, ret2, window_len, window_step, nsteps=20, period='monthly', rebal_period=3,
downside_vol=True):
"""Find the optimal (volatility-minimizing) combination of two return series over a rolling window.
Args:
- ret1: a sequence of period return... | 5,322,991 |
def forward_backward_prop(data, labels, params, dimensions):
"""
Forward and backward propagation for a two-layer sigmoidal network
Compute the forward propagation and for the cross entropy cost,
and backward propagation for the gradients for all parameters.
Arguments:
data -- M x Dx matrix, w... | 5,322,992 |
def generate_output_descriptors(filename_out_base,
max_block_size_voxels,
overlap_size_voxels,
dim_order,
header,
output_type,
n... | 5,322,993 |
def clean_data(df):
"""
The function is to clean the data.
Parameters:
df (pandas dataframe): loaded data from load_data function.
Returns:
df (pandas dataframe): cleaned version of the data.
"""
# Create a dataframe of the 36 individual category columns
cate_df = df['categor... | 5,322,994 |
def DocumentVariables(filename):
"""!
TODO_DOC
- if True will replace any existing variable documentation with new auto-generated lines.
- check for global variables and see if they have comments
- it's a root level line. Could it be a variable?
@param filename: TODO_DOC
@return TODO_DOC
## Profile
* line co... | 5,322,995 |
def squeezenet1_0_fpn_feature_shape_fn(img_shape):
""" Takes an image_shape as an input to calculate the FPN output sizes
Ensure that img_shape is of the format (..., H, W)
Args
img_shape : image shape as torch.Tensor not torch.Size should have
H, W as last 2 axis
Returns
P3... | 5,322,996 |
def validate_url(url):
"""Validates the url.
Args:
url(str): The URL to validate
Raises:
ValidationError: If the validation has failed
"""
# We don't allow downloading from other sites except for youtube
if not _is_url_from_youtube(url):
raise ValidationError('Invalid U... | 5,322,997 |
def temp_paths_2(tmp_path_factory):
"""
Makes temporary directories, for testing bak_to_git_2, and populates them
with test files. Returns pathlib.Path objects for each.
"""
temp_path: Path = tmp_path_factory.mktemp("baktogit2")
bak_path = temp_path / "_0_bak"
bak_path.mkdir()
t1 = "202... | 5,322,998 |
def clip_alpha(aj, H, L):
"""
cLips alpha vaLues tHat are greater
tHan H or Less tHan L
"""
if aj > H:
aj = H
if L > aj:
aj = L
return aj | 5,322,999 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.