content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def make_tweet(quantity, ticker, asset_description, price, tx_date, tx_time, instrument, trade_type):
"""Create and return a new instance of a Tweet object."""
tweet = Tweet(quantity, ticker, asset_description, price, tx_date, tx_time, instrument, trade_type)
return tweet | f35f25bcbd9235d9c13864106952554a5cc4a163 | 34,900 |
import warnings
def rescale_laplacian(laplacian):
"""
Scale graph Laplacian by the largest eigenvalue of normalized graph Laplacian,
so that the eigenvalues of the scaled Laplacian are <= 1.
Args:
laplacian: Laplacian matrix of the graph
Returns:
Return a scaled Laplacian matrix.... | cf43000542c9c8b23001b0df0d157077a8a84d98 | 34,901 |
import os
def download_source(src_version):
"""
Загрузка архива с исходным кодом требуемой версии nginx
Возвращает имя скаченного файла
:param src_version:
:return file_name:
"""
logger.info("Downloading nginx src...")
file_name = "nginx-{}.tar.gz".format(src_version)
url = "{}/{}"... | c5d6f766b5d6f589b402d32856375ca7ce8001f1 | 34,902 |
def get_function_signature(uplevels=0):
"""
RETURNS the calling function signature, at runtime.
"""
uplevels += 1
funcname = get_function_name(uplevels)
params = get_function_parameters_and_values(uplevels)
params = ", ".join(["{}={}".format(*i) for i in params])
sig = "{}({})".format(... | 62b23ca9f644b46ebbe4ba122ccd7c11291efbcd | 34,903 |
import os
def get_logfile_fullpath(fingerprint_result_dir, procmon_csv:str, fingerprint_file_csv:str, fingerprint_reg_csv:str)->str:
"""
>>> fingerprint_result_dir = 'c:/fingerprint'
>>> procmon_csv = 'procmon-logfile'
>>> fingerprint_file_csv = 'test_c_files'
>>> fingerprint_reg_csv = 'test_regis... | 1631bdedfda110f2f684496ce381b0db40b5c608 | 34,904 |
def multivariate_multiply(m1, c1, m2, c2):
""" Multiplies the two multivariate Gaussians together and returns the
results as the tuple (mean, covariance).
Examples
--------
.. code-block:: Python
m, c = multivariate_multiply([7.0, 2], [[1.0, 2.0], [2.0, 1.0]],
... | 59cba92949533e4ec001ffa758bc125fd74960d5 | 34,905 |
def make_initial_state():
"""
Create an initial state dictionary.
"""
return { 'geogrid' : 'waiting',
'ingest' : 'waiting',
'ungrib' : 'waiting',
'metgrid' : 'waiting',
'real' : 'waiting',
'wrf' : 'waiting',
'output': 'waiting... | 7a9e2bccb52c1a75ce2ef1d313177fd573433461 | 34,906 |
def xliff_import_confirm(request, xliff_dir):
"""
Confirm the XLIFF import and write changes to database
:param request: The current request (used for error messages)
:type request: ~django.http.HttpRequest
:param xliff_dir: The directory containing the xliff files
:type xliff_dir: str
:r... | aa022adc6c4a471c3fd1f7b9896f9b3aa5c1ddcf | 34,907 |
def generate_gaps_time_series(nt, nx, ny, pct, gaps_type):
""" Generate gaps on time series of modeled fields.
Input:
- pct: percentage of gaps to be generated
- gaps_type: type of gaps, can be:
- 'random': randomly distributed gaps across time series
- 'corr'... | 20267e0043efbf40f1779592961012f8999ac249 | 34,908 |
from datetime import datetime
def leave_feedback():
"""Оставить отзыв"""
json = request.get_json()
if "text" in json:
Feedback.create(text=json["text"], user=get_user_from_request())
Telegram(current_app.config).notify_admin_channel(
"Пользователь %s оставил отзыв: %s"
... | cdc1c5898c1f68ebcb1d4b34dd05ff2fab6c450f | 34,909 |
from typing import Optional
def get_control_panel(control_panel_arn: Optional[str] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetControlPanelResult:
"""
AWS Route53 Recovery Control Control Panel resource schema .
:param str control_panel_arn: The Amazon Resou... | d8dd1280505b70ee25166941f9822827f10850c4 | 34,910 |
from typing import Sequence
from typing import Optional
from typing import Type
from typing import Union
def zeros(shape: Sequence[int],
dtype: Optional[Type[np.number]] = None,
backend: Optional[Union[Text, AbstractBackend]] = None) -> Tensor:
"""Return a Tensor of shape `shape` of all zeros.
... | e913c5fa24095842492cec670fde2ea61afc24c6 | 34,911 |
def staff_required(
function=None, redirect_field_name=REDIRECT_FIELD_NAME, login_url="login"
):
"""Decorator for views that checks that the logged in user is a staff/admin,
redirects to the log-in page if necessary."""
actual_decorator = user_passes_test(
lambda user: user.is_active and user.is... | 804ba1021993507796fd7009ffea880fcebc2edc | 34,912 |
def from_Peppercorn_restingset_reaction(reaction, restingsets):
""" Converts a condensed Peppercorn PepperReaction object to an equivalent
DNAObjects RestingSetReaction object. This function requires as an argument a
dict mapping Peppercorn RestingSet objects to equivalent DNAObject RestingSets.
"""
if rea... | 12f368f7c2a2e5f20456c37131f28a76573cebe3 | 34,913 |
from unittest.mock import Mock
def mock_stripe_checkout(monkeypatch):
"""Fixture to monkeypatch stripe.checkout.* methods"""
mock = Mock()
mock.Session.create.return_value.url = "https://example.net/stripe_checkout/"
monkeypatch.setattr(stripe, "checkout", mock)
return mock | 78c8bf08bb41c831f2e0a602a889b937ea1534c5 | 34,914 |
import time
def milliseconds():
"""
Current time in milliseconds (UTC).
"""
return int(time.time() * 1000) | cc829688be8742423a8306b0ffae14f318541687 | 34,915 |
def test_dispatch_responses():
"""
MessageSenderMixin._dispatch_responses() Test plan:
-Ensure False returned if pre_dispatch_responses hook returns false
-Ensure False returned if post_dispatch_responses hook returns false
-Catch invalid response from hpit on [message][id]
-Catc... | c2d25ccde706246f89eb74ff11dbf673ca07f792 | 34,916 |
def fit_wave_interval(wave, old_sampling, new_sampling, new_size = None):
"""
Produces an array of wavelengths between two values and with a given number
of elements.
Parameters
----------
wave : np.ndarray, list
List or ndarray with initial wavelength and final wavelength e.g.:
... | 0e2473fa707f704f60ecf5a4dcf0966ab5f041be | 34,917 |
def make_network_from_structural_and_functional(structural_edges, functional_edges):
"""
Combine structural and functional dataframes to get a deduplicated dataframe of edges
:param structural_edges: pandas DataFrame including columns ['source_content_id', 'destination_content_id']
:param functional_edg... | fdea72dab9da4cab05d7a998e543476b761dd74a | 34,918 |
import argparse
def parse_arguments(args):
"""
Parse the arguments from the user
"""
parser = argparse.ArgumentParser(
description= "HAllA's Clustering using hierarchical clustering and Silhouette score.\n",
formatter_class=argparse.RawTextHelpFormatter)
parser.add_argument(
... | e5478e250b8ef3a818f1fa794b0cc686304e24f6 | 34,919 |
import math
def num_k_of_n(n: int, k: int) -> int:
"""Return number of combinations of k elements out of n."""
if k > n:
return 0
if k == n:
return 1
return math.factorial(n) // (math.factorial(k) * math.factorial((n - k))) | de99dd88fc6e747421e36c698a525b7e58b1e4de | 34,920 |
def new_graph():
"""Make graph to play with."""
return Graph() | eac2a6a9e65db733cc744e391fbbb6f2906cf744 | 34,921 |
def subtract_mean_batch_reward(population):
"""Returns new Population where each batch has mean-zero rewards."""
df = population.to_frame()
mean_dict = df.groupby('batch_index').reward.mean().to_dict()
def reward_for_sample(sample):
return sample.reward - mean_dict[sample.batch_index]
shifted_samples = ... | 73813c3f165dc933983b0abe48392505cc202e6e | 34,922 |
def norm(x):
"""Calculate the Euclidean norm of a vector x."""
return np.sqrt(np.dot(x, x)) | c09ff946ed6248e4bf57b87f96ec4ad54ce4cdc8 | 34,923 |
def codegen_reload_data():
"""Parameters to codegen used to generate the fn_palo_alto_wildfire package"""
reload_params = {"package": u"fn_palo_alto_wildfire",
"incident_fields": [],
"action_fields": [],
"function_params": [u"artifact_id", u"artifact... | 554f93deb50664db00ef59a67f76a979779cb9c9 | 34,924 |
def min_number_in_rotated_array(r_nums):
"""
:param r_nums:rotated arrat
:return: min number
"""
if not r_nums:
return None
left = 0
right = len(r_nums)-1
while left < right:
mid = (left + right) // 2
if r_nums[mid] == r_nums[right] == r_nums[left]:
ri... | 97cd37fb040a38b6c52cf816d29b97aa36c3c338 | 34,925 |
def create_cond_node(return_name_ids, pred, true_func, false_func):
"""
Create `fluid.layers.cond(pred, true_fn, false_fn)` to replace
original `python if/else` statement.
"""
# TODO(Aurelius84): should replace the api hard code.
cond_api = gast.parse('fluid.layers.cond').body[0].value
true_... | 3cc3073d092d3bbe95cf23175fd11f56f84198cf | 34,926 |
def scatter_columns(A):
"""
Performs the reverse operation as gather_columns. Thus, each prow receives
the prow'th row-slice of A.
If A had local shape(grid[0] * m_l, n_l), thre result has local shape
(m_l, n_l). If the number of local rows in A is not an even multiple
of grid[0] an error is thrown.
"""
... | 7619491aa08ee172aa77c15b44caa889b690cc54 | 34,927 |
def digitos(valor):
"""Resulta em uma string contendo apenas os dígitos da string original."""
return ''.join([d for d in valor if d.isdigit()]) | dc742d871efefa8067f33c95cc277963e3cfa201 | 34,928 |
def from_Point(ros_pt):
"""From ROS Point to Klamp't point"""
return [ros_pt.x,ros_pt.y,ros_pt.z] | 34d83ea0266883679c7e2f51c4eb555e189940d4 | 34,929 |
def greedy():
"""A greedy distribution."""
def sample_fn(key: ArrayLike, preferences: ArrayLike):
probs = _argmax_with_random_tie_breaking(preferences)
return _categorical_sample(key, probs)
def probs_fn(preferences: ArrayLike):
return _argmax_with_random_tie_breaking(preferences)
def log_prob_fn... | b99c4c2d410be42be33c38633b4b998e5db37be7 | 34,930 |
def GibbsSampler(dna_list, k, t, N, mode = 'v1', repeat=20):
"""Input a list of Dna sequence, out put the best set of motifs.
The motifs are generated by Gibbs sampling and optimized by comparing
hamming or entropy scores. Mode 'v1' returns kmer by weighted probability;
mode v2 returns the most probabl... | 767597df8b23baf09666009a90452d9d51a814fb | 34,931 |
def read_input_h5(h5):
"""
Reads astra inpu5 from h5
See: write_input_h5
"""
d = {}
for g in h5:
d[g] = dict(h5[g].attrs)
# Convert to native types
for k, v in d[g].items():
d[g][k] = native_type(v)
return d | 1bcf29418df9fcd4d49bb86e32c47febf2bb2403 | 34,932 |
import math
def to_half_life(days):
"""
Return the constant [1/s] from the half life length [day]
"""
s= 24 * 3600 * days
return -math.log(1/2)/s | 7224be1e3e460336493d49c3f2b3d8932341f575 | 34,933 |
def fit_on_batch(model, x, y, loss_fn, optimizer, metrics=["loss", "acc"]):
"""Trains the model on a single batch of examples.
This is a training function for a basic classifier. For more complex models,
you should write your own training function.
NOTE: Before you call this, make sure to do `model.tr... | 87fa7342bdf84a382fdcce5edde9458bec7bb4c8 | 34,934 |
def get_longest_common_substring(text_a, text_b):
"""Find longest common subtring."""
# isjunk=None, a='', b='', autojunk=True
seqMatch = SequenceMatcher(None, text_a, text_b, autojunk=False)
#Also:
# autojunk = True (default)
# isjunk = None (deafult), same as: lambda x: False;
# or return... | 9b4c75525aa071892aba11919aa59dae2e4a43de | 34,935 |
from typing import OrderedDict
def from_group(group, time_index=False, absolute_time=False, scaled_data=True):
"""
Converts a TDMS group object to a DataFrame. DataFrame columns are named using the channel names.
:param group: Group object to convert.
:param time_index: Whether to include a time inde... | ba2d049a8c3076e02c7a9bbb8019ef901957aa7a | 34,936 |
def get_model(source, data_only=False, curdir=None):
"""FIXME: Documentation missing.
Mention TestSuite.from_model when docs are written.
"""
tokens = get_tokens(source, data_only)
statements = _tokens_to_statements(tokens, curdir)
return _statements_to_model(statements, source) | 7aac93872d2f7c2753c1fd9fb753b502d9492069 | 34,937 |
import time
def _bq_harness_with_result(sql, do_batch):
"""
Handles all the boilerplate for running a BQ job
"""
client = bigquery.Client()
job_config = bigquery.QueryJobConfig()
if do_batch:
job_config.priority = bigquery.QueryPriority.BATCH
location = 'US'
# API request - s... | 8546498d7e4553e5c0c74f7515db5c75ef4338ad | 34,938 |
def create_workflow(name=None, namespace=None, bucket=None, **kwargs):
"""
Args:
name: Name to give to the workflow. This can also be used to name
things associated with the workflow.
"""
builder = Builder(name=name, namespace=namespace, bucket=bucket, **kwargs)
return builder... | 58980a10d3ebe858547c71efc65c369a78373016 | 34,939 |
def validadeInequalityFilter(inequality_filters, entity):
"""Check if a entity attends all the inequality filters inputed"""
check = True
# Iterated on every the inequality filter informed
for f in inequality_filters:
if hasattr(entity, f["field"]): # Check if the entity has the attribute
... | 374174dc4b9aac720c74fdf83b55321ed6525a7b | 34,940 |
import time
import os
def _make_reader(event_buffer_len=65536, delay=0.1):
"""Read a large amount of events into the given queue. event_buffer_len
determines how much to attempt to read at once
"""
logger.debug("Create reader buffer={} delay={}"
.format(event_buffer_len, delay))
... | b4a5dbac7a6bda44b8b05ad0c146de77f000b5d6 | 34,941 |
def flops_metric_map(end_points, mean_metric, total_name='Total Flops'):
"""Assembles flops-count metrics into a map for use in tf.contrib.metrics."""
metric_map = {}
total_flops = tf.to_float(end_points['flops'])
flops_map = moments_metric_map(total_flops, total_name, mean_metric,
delimiter='/', do_shift... | fd18df2d4f442e8afc9902760a864a479eefe7c5 | 34,942 |
def _is_false2(x):
"""Non-vectorized helper function"""
return (x in ("False", "false", "0") or not bool(x)) and not _is_na2(x) | 972983f25474017065128023de1011f40c319866 | 34,943 |
import re
def process_document(document, context_size, dictionary, fixed_dictionary=False):
"""
Given a dictionary, extract the tuples of words of length equal to
context_size. Each word is represented by a unique integer number.
If fixed_dictionary is True, only take consecutive tuples of words
... | 3f3531faa8c9aad63ac798e9c3e3a06230d5ecf7 | 34,944 |
def list_buckets():
"""
Lists available buckets.
:return: list of available buckets
Amazon (2019) s3-python-example-list-buckets.py
Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
"""
# create s3 client
s3 = boto3.client('s3')
# call client and get lis... | e669d1137d43ffc62d474a36be6e64c5b02eca2a | 34,945 |
def site_time_zone(request, registry, settings):
"""Expose website URL from ``tm.site_time_zone`` config variable to templates.
By best practices, all dates and times should be stored in the database using :term:`UTC` time. This setting
allows quickly convert dates and times to your local time.
Exampl... | 40d3314d35fde3d77a4e2f5fe441eee499f8de03 | 34,946 |
def qubic_spline_coeff(x_nodes, y_nodes):
"""Here underscored variables are related to the matrix equation,
whereas normal ones stand for the spline coefficients
"""
polynomials_num = len(x_nodes) - 1
coeffs = np.zeros((polynomials_num, 3))
hs = (x_nodes - np.roll(x_nodes, 1))[1:]
ys = (y_no... | 95d1f50d638919355acbe21d2564ab7a37a4b920 | 34,947 |
from bs4 import BeautifulSoup
import itertools
def load_C2O(xml_file):
"""Load a C2O decision model.
See http://www.jku.at/isse/content/e139529/e126342/e126343 for
information about the C2O (Configurator 2.0) tool.
Arguments:
xml_file: Path to a C2O XML file.
Returns:
A tuple wi... | b708e94d6a29829d0df775f784ad7070aa663edc | 34,948 |
def contact_infectivity_asymptomatic_40x50():
"""
Real Name: b'contact infectivity asymptomatic 40x50'
Original Eqn: b'contacts per person normal 40x50*infectivity per contact'
Units: b'1/Day'
Limits: (None, None)
Type: component
b''
"""
return contacts_per_person_normal_40x50() * i... | 63d1d87a35bc2eafa64b3b22993f388ce617c3b4 | 34,949 |
def freezeclass(cls):
""" Decorator to freeze a class."""
cls.__frozen = False
def frozensetattr(self, key, value):
if self.__frozen and not hasattr(self, key):
print("Class {} is frozen. Cannot set {} = {}"
.format(cls.__name__, key, value))
else:
... | 58fd3754c93dfcfa3aeb8b7ed722cd7d4bfd307e | 34,950 |
def gsc_url_keyword(prop, start, end, query, url):
"""Return position, clicks & impressions from GSC for keyword for URL."""
#API Not adapted to Pipulate yet
request = {
"startDate": start,
"endDate": end,
"dimensions": [
"query",
"page"
],
"dimensionFilterGrou... | 3fa1993e73cf8672eef232a7de12c6db1914ca51 | 34,951 |
def zerofill_net(input_size=(640, None, 1), **dummy_kwargs):
"""A net that performs a simple zero-filled reconstruction
Parameters:
input_size (tuple): the size of your input kspace
Returns:
keras.models.Model: the zerofill net model, compiled
"""
# shapes
mask_shape = input_size[:-1]
... | bde693f37097c797c8a2344ef8f196241e619147 | 34,952 |
def __useless_contour(shape, detected, last_cont,center,angle):
"""
Erase the useless contours, center, and angle.
Contours, center, and angle are erased if the shape type is ALL, PARTIAL or UNKNOWN.
Parameters
----------
shape : Shape
The shape we want to detect
detected : Shape
... | 6daa7add5ae79222853600d3e7e7f406a2d4c37e | 34,953 |
def add_b(_rb):
""" Add for Baselines
"""
def add(e):
for i in range(e["obs"].shape[0]):
_rb.add(obs_t=e["obs"][i],
action=e["act"][i],
reward=e["rew"][i],
obs_tp1=e["next_obs"][i],
done=e["done"][i])
ret... | 1b2d6bb94958a00a5c43e0b601f4999b0271f932 | 34,954 |
def get_ncfile(fname='cmip5.CSIRO-Mk3-6-0.nc'):
""" Return one netCDF file
"""
return join(get_datadir(),fname) | 1638eaa0519ac4415ea114dc6abdb760f951f3d5 | 34,955 |
def generate_complete_path(filename:str, main_folder="./temp/", subfolders='', file_extension = ".png", save_files=True):
"""
Function to create the full path of a plot based on `name`. It creates all the subfolders required to save the final file.
If `save_files=False` returns `None`, useful to control fro... | b97e7531088688d72ef3a248abedcfef3a054394 | 34,956 |
def realm_from_principal(principal):
"""
Attempt to retrieve a realm name from a principal, if the principal is fully qualified.
:param principal: A principal name: user@DOMAIN.COM
:type: principal: str
:return: realm if present, else None
:rtype: str
"""
if '@' not in principal:
... | 1880fef7b4383edc6f2ccd94958200686d500e0c | 34,957 |
from typing import List
import torch
def patch_batchnorm(module: nn.Module) -> List:
"""Patch all batchnorm instances (1d, 2d, 3d, sync_bn, etc.) of a module
so that they don't track running stats when torch.no_grad() is enabled.
This is important in activation checkpointing to ensure stats are tra... | d1456d48db5f2016716aaaa4f87f2eb77e4dcd43 | 34,958 |
def decode_uids(uids, *, return_sids_iids:bool=False, return_sids_pids:bool=False,
experimental_noinfo_id:int=-1, experimental_dataset_spec:DatasetSpec=None,
experimental_correct_range:bool=False):
"""
Given the universal ids `uids` according to the hierarchical format described
in... | fc56ff3f53b2cd44d1c60f2ce90c79145d98364f | 34,959 |
import six
def _joined_names_column(df):
"""
Join data from all name columns into a single column.
"""
return df.apply(
lambda row: ','.join(set([
six.text_type(n)
for n in [row['main_name'], row['asciiname'], row['alternatenames']]
if n and n is not np.nan
... | d563971403758035bf9c57442a3d99c246f2fb92 | 34,960 |
def skip(
num_input_channels=2, num_output_channels=3, num_channels_down=[16, 32, 64, 128, 128],
num_channels_up=[16, 32, 64, 128, 128],
num_channels_skip=[4, 4, 4, 4, 4], filter_size_down=3,
filter_size_up=3, filter_skip_size=1, need_sigmoid=True, need_bias=True,
pad='zero', ups... | 4c26a931d701f1cfb439a835c1fe628569bbc24f | 34,961 |
def validate_kml(possible_files):
"""Validate uploaded KML file and a possible image companion file
KML files that specify vectorial data typers are uploaded standalone.
However, if the KML specifies a GroundOverlay type (raster) they are
uploaded together with a raster file.
"""
kml_file = [
... | e5389c7b3b9972757fb44a5c2e29af4aaede1618 | 34,962 |
import base64
def mailform():
"""Sample form for sending email via Microsoft Graph."""
# read user profile data
user_profile = MSGRAPH.get('me/', headers=request_headers()).data
user_name = user_profile['displayName']
# get profile photo
photo_data, _, profile_pic = profile_photo(client=MSGR... | e9180515b84e7f012aef576e123ea08fba3aefda | 34,963 |
def _global_query_(included_interviews=None, included_globals=None, client_as_numeric=True, exclude_reliability=True):
"""
Constructs the globals query for session-level datasets
:param included_interviews: iterable of str specifying names of interviews to include
:param included_globals:
:param cli... | dca8599fc7625f4f8a2db5321c32666b6b384c02 | 34,964 |
def basic_detokenizer(tokens):
"""Reverse the process of the basic tokenizer below."""
result = []
previous_nospace = True
for t in tokens:
if is_char(t):
result.append(t[_CHAR_MARKER_LEN:])
previous_nospace = True
elif t == _SPACE:
result.append(" ")
previous_nospace = True
... | 073a388a3a7f2133457e9c7a61a499b830d59760 | 34,965 |
def page_not_found(error):
"""Generic 404 error page.
:param error: An exception from the error.
:returns: The rendered 404 error template.
"""
app.logger.debug('Rendering 404 page')
return render_template('404.html'), 404 | 533ba80d8aa9c1c819380501f7fdddb8af0e002d | 34,966 |
def get_task_state(exit_code):
"""Interprets the exit_code and return the corresponding task status string
Parameters
----------
exit_code: int
An integer that represents the return code of the task.
Returns
-------
A task status string corresponding to the exit code.
"""
i... | 99837d42586ffacc2d2b1e8dc938add185bc0e04 | 34,967 |
def filtertime(timestamp, interval):
"""Check if timestamp is between timestamp_range - (time1,time2)
Args:
timestamp --> UNIX timestamp value.
interval --> `Tuple` of 2 UNIX timestamp values.
Returns:
`bool` --> True/False
"""
T0, T1 = interval
if (timestamp <= T1) an... | 72fe1aa9ed01e59ad7bbe5299b4c21272fab7354 | 34,968 |
def is_dataframe(value):
"""
Check if an object is a Spark DataFrame
:param value:
:return:
"""
return isinstance(value, DataFrame) | 954276a168586d7cd19846575d239a82083d3f9f | 34,969 |
from typing import Type
from typing import Dict
def reverse_enum(enum_to_reverse: Type[SMOOTHIE_GCODE]) -> Dict:
"""
Returns dictionary with keys and values switched from passed Enum
:param enum_to_reverse: The Enum that you want to reverse
:return: Reversed dictionary
"""
# I don't know what ... | 4dbb65905d2441089eb989b28733b6f4c4e0b529 | 34,970 |
def install_npm(path=None, build_dir=None, source_dir=None, build_cmd='build', force=False):
"""Return a Command for managing an npm installation.
Note: The command is skipped if the `--skip-npm` flag is used.
Parameters
----------
path: str, optional
The base path of the node package. De... | dd99c1a80f3fe3228d08c4ffad0efaf450c35aed | 34,971 |
from typing import Iterable
from typing import List
from typing import Tuple
from typing import Counter
def group_Counter(trip: Iterable[Leg]) -> List[Tuple[int, int]]:
"""Group legs into bins with distances 5 nm or less.
>>> trip = [ ('s1', 'e1', 1), ('s4', 'e4', 4.9), ('s5', 'e5', 5), ('s6', 'e6', 6)]
... | 51cf9dac6e25a4c5c3666a5ad60169304759d7c7 | 34,972 |
import time
def run_deduper(deduper, data_frame, settings_file, training_file, recall_weight = 1):
"""
Given a deduper object and a dataset, this function trains the model and
predicts which records are duplicates.
depends:
dedupe as dd
pandas as pd
time
params:
d... | 918969cf37dc948ab88e19e7239873da384bafa2 | 34,973 |
def _get_file_preferred_suffix() -> tuple:
"""Based on ontologia/core.lkg.yml + env variable LANGUAGE, build preferred
user language
Returns:
tuple: the result of file sufisex
"""
userpref_suffix = []
core_suffix = CORE_LKG['fs']['hdp']['base']
userlangs_upper = get_language_user_... | 2bb2c3a7d2543d284203467d93ea4d3c0cfedbd3 | 34,974 |
def fatorial(n, show=False):
"""
-> Call
:param n:
:param show:
:return:
"""
f = 1
for c in range (n, 0, -1):
if show:
print(c, end='')
if c>1:
print(' x ', end='')
else:
#print(f'{c} X ')
print(' = '... | edc42b1269799716d90896cdada721c33d156503 | 34,975 |
import uuid
def integrate_whole(payload, org, out_uuid, group):
"""integrates payload into whole of profile, returns dict"""
if group:
in_uuid = str(uuid.uuid4())
nested = {"PayloadContent": payload,
"PayloadEnabled": True,
"PayloadIdentifier": 'SparkleDisab... | b08cab03f0a1e3a2b74110a7829f6fc6d736d0f4 | 34,976 |
from typing import List
def search_hospitals(request_input: RequestInput, db_session) -> List[dict]:
"""
Search hospitals based on requested items. Sort them by nearest location
:param request_input: RequestInput
:param db_session: DB session
:return: List of Hospital dictionaries
"""
# Se... | 22dde6acb46fcc03e2cf6f2ef56fca05a2b4090b | 34,977 |
def get_inverse_metric():
"""Computes and returns the inverse metric
Sets the inverse metric variable, so that DendroSym knows how to compute
various derived variables. This should be done early on in the
generating script. It requires the metric to already be defined.
Returns
-------
symp... | da6399366b0b4096065dcb8ea8e2dd5f95555432 | 34,978 |
def add_towers_4G_km2_sheet(ws, cols, lnth):
"""
"""
for col in cols:
cell = "{}1".format(col)
ws[cell] = "=Towers!{}".format(cell)
for col in cols[:2]:
for i in range(1, lnth):
cell = "{}{}".format(col, i)
ws[cell] = "=Towers!{}".format(cell)
for c... | 1fe86a6ddd210c13d3e92f68a1deb9b41375d14b | 34,979 |
from typing import List
from typing import Dict
def get_all_netting_channel_events(
chain: BlockChainService,
token_network_address: Address,
netting_channel_identifier: ChannelID,
contract_manager: ContractManager,
from_block: BlockSpecification = GENESIS_BLOCK_NUMBER,
... | bcaf2a96db7a95c3660abcc7daac4a448baad50d | 34,980 |
from typing import List
def custom_extractors(
eval_shared_model: tfma.MaybeMultipleEvalSharedModels,
eval_config: tfma.EvalConfig,
tensor_adapter_config: tensor_adapter.TensorAdapterConfig,
) -> List[tfma.extractors.Extractor]:
"""Returns default extractors plus a custom prediction extractor."""
pred... | a6efc2c15bbb6b437710d79a3b22174c19eb1083 | 34,981 |
def custom_detrending(flc):
"""Wrapper"""
f = flc.flux[np.isfinite(flc.flux)]
if np.abs(f[0]-f[-1])/np.median(f) > .2:
print("Do a coarse spline interpolation to remove trends.")
flc = fit_spline(flc, spline_coarseness=12)
flc.flux[:] = flc.detrended_flux[:]
# Iterativel... | 534e0881ccab91811128f1e7f109460321f98937 | 34,982 |
import random
def summon_blocks(board):
"""Place 1-8 circles in random places on the speed board"""
for _ in range(random.randint(1, 8)):
x = random.randint(0, 4)
y = random.randint(0, 4)
while board[x][y] != 'g':
x = random.randint(0, 4)
y = random.randint(0, 4)
board[x][y] = 'b'
return board | 0cfa703b6451e44ea8688561bc857ac70f560c90 | 34,983 |
from typing import List
from typing import Tuple
def three_sum_brute_force(array: List[int], target: int) -> Tuple[int, int, int]:
"""
args:
array:
target:
returns:
idxs
>>> s = [-1, 0, 1, 2, -1, -4]
>>> three_sum_brute_force(s, 0)
(0, 1, 2)
O(N^3)
"""
for i, ... | 4a47fae2c4f81ef654bcf21c73462cc4965b6b78 | 34,984 |
import os
def duplicates(work, golden=None, purge=False):
""" Finds duplicates and purges them based on the flags
@param work: work path where duplicates will be searched and purged if purge flag is set
@param golden: path where duplicates will be searched, however never deleted
@param purge: delete d... | 34583b495e794de3ac48bebcd18874c5ee7a9da4 | 34,985 |
def on_cooldown(user):
"""Shortcut: Get remaining cooldown of a user."""
return Parent.GetUserCooldownDuration(ScriptName, settings["command"], user) | afadc17c45f09303d1fdcddc997c6b5d98c5e903 | 34,986 |
def get_ieconstraints(unknowns, segment):
""" Runs the mission if the inequality constraint values are needed, these are specific to a climb
Assumptions:
Time only goes forward
CL is less than a specified limit
CL is greater than zero
All altitudes are greater than zero
... | 6cdc5ce218ecdc40b792f0bf2fce8789e8577aa9 | 34,987 |
def check_file_name(file_name, file_type="", extension=""):
"""
check_file_name(file_name, file_type="", extension="")
Checks file_name for file_type or extension
"""
file_name = check_string(file_name, -1, '.', extension)
file_name = check_string(file_name, -1, '_', file_type)
return file_name | 250937094bc90e67ccf5a3d2615105b4e448dfff | 34,988 |
def render_experiments(
driver: Driver = None,
collab_id: str = "",
project_id: str = "",
form_type: str = "display",
show_details: bool = True
):
""" Renders out retrieved experiment metadata in a custom form
Args:
driver (Driver): A connected Synergos driver to communicate with... | 8f210251052081184b0e3792ed7381263a9961b2 | 34,989 |
import json
def tag_lookup(request):
"""JSON endpoint that returns a list of potential tags.
Used for upload template autocomplete.
"""
tag = request.GET['tag']
tagSlug = slugify(tag.strip())
tagCandidates = Tag.objects.values('word').filter(slug__startswith=tagSlug)
tags = json.dumps([c... | c6cca931538a30bfa2e6f356f87eaa17158f5145 | 34,990 |
def scope_to_list(scope):
"""Convert a space separated string to a list of scopes."""
if isinstance(scope, list) or scope is None:
return scope
else:
return scope.split(" ") | c806f91192f86dbc42719787d9ddfe0d79690f0c | 34,991 |
from pathlib import Path
import importlib
def import_migration_script(filepath: Path) -> ModuleType:
"""
Import migration script as if it were a module.
"""
spec = importlib.util.spec_from_file_location(filepath.stem, filepath)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_mo... | 15c8a5532d0a38d0741c3a82c299ad13e6885792 | 34,992 |
from typing import Callable
import inspect
def numargs(func: Callable) -> int:
"""Get number of arguments."""
return len(inspect.signature(func).parameters) | 2b4e068798add68323db6bd43253fbca34ea71ba | 34,993 |
def _embed(x, order=3, delay=1):
"""Time-delay embedding.
Parameters
----------
x : 1d-array, shape (n_times)
Time series
order : int
Embedding dimension (order)
delay : int
Delay.
Returns
-------
embedded : ndarray, shape (n_times - (order - 1) * delay, order... | e2834c835521e57132f67a19f4a405af752e497f | 34,994 |
def counts_normalization(counts, max_t):
"""This functions acts over the counts matrices and vectors in order to
normalize their elements into a probabilities.
Parameters
----------
counts: array_like, shape(n,n,nlags)
the counts of the coincident spikes considering lag times.
Returns
... | a4e92df1dd53ae31dceb40341f90a1797bd4c753 | 34,995 |
def form_baseline_intro(current_law):
"""
Form final sentance of introduction paragraph
"""
if not current_law:
return f"{date()}"
else:
return (
f"{date()}, along with some modifications. A summary of these "
"modifications can be found in the \"Summary of Ba... | 8e93002290188605eb5df6992f5f41ae2352634d | 34,996 |
from typing import Any
def serialise(entry: Directive) -> Any:
"""Serialise an entry."""
if not entry:
return None
ret = entry._asdict()
ret["type"] = entry.__class__.__name__
if isinstance(entry, Transaction):
ret["payee"] = entry.payee or ""
if entry.tags:
ret... | 9ec9e1ea77011a79f8d1aac7ce4c804ef288f9f6 | 34,997 |
def MeanValueCoordinateMapping(dpoint, uv, physical_points):
"""MVC mapping from parametric uv to physical 3D
inputs:
dpoint: [list, tuple or 1D array of floats] desired uv point
uv: [2D array] of parametric uv points of polygon vertices
physic... | e5212fc953a67bc3e9827aa0d3bb4c088a6c848d | 34,998 |
import re
def _handle_discogs(url):
"""https://*discogs.com/*"""
apiurl = 'https://api.discogs.com/'
headers = {'user-agent': 'pyfibot-urltitle'}
title_formats = {
'release': '{0[artists][0][name]} - {0[title]} - ({0[year]}) - {0[labels][0][catno]}',
'artist': '{0[name]}',
'l... | 37be95755e77782ad4b6beee000a6b096a681aa9 | 34,999 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.