content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def convolve_cbvs(sectors=np.arange(1,14,1)):
"""
Bins the co-trending basis vectors into FFI times;
Calls download_cbvs to get filenames
Input
-----
type(sectors) == list
"""
# Gets the cutout for a target in the CVZ
coord = SkyCoord('04:35:50.330 -64:01:37.33', unit=(u.hourangle, u.d... | 18,100 |
def _format_param(name, optimizer, param):
"""Return correctly formatted lr/momentum for each param group."""
if isinstance(param, (list, tuple)):
if len(param) != len(optimizer.param_groups):
raise ValueError("expected {} values for {}, got {}".format(
len(optimizer.param_gr... | 18,101 |
def run_test(d):
"""
Run the gaussian test with dimension d
"""
######### Problem Specification
# Data generation parameters
prior_mu_z = np.zeros(d, dtype=np.float32) # Prior mean
prior_sigma_z = np.eye(d, dtype=np.float32) # Prior covariance matrix
# True model parameters
... | 18,102 |
def coh_overflow_test():
"""
Test whether very very opaque layers will break the coherent program
"""
n_list = [ 1., 2+.1j, 1+3j, 4., 5.]
d_list = [inf, 50, 1e5, 50, inf]
lam = 200
alpha_d = imag(n_list[2]) * 4 * pi * d_list[2] / lam
print('Very opaque layer: Calculation s... | 18,103 |
def ShowZallocs(cmd_args=None):
""" Prints all allocations in the zallocations table
"""
if unsigned(kern.globals.zallocations) == 0:
print "zallocations array not initialized!"
return
print '{0: <5s} {1: <18s} {2: <5s} {3: <15s}'.format('INDEX','ADDRESS','TRACE','SIZE')
current_inde... | 18,104 |
def test_field_extension_post(app_client, load_test_data):
"""Test POST search with included and excluded fields (fields extension)"""
body = {
"fields": {
"exclude": ["datetime"],
"include": ["properties.pers:phi", "properties.gsd"],
}
}
resp = app_client.post(... | 18,105 |
def write(text, into=None, session_id=None):
"""
:param text: The text to be written.
:type text: one of str, unicode
:param into: The element to write into.
:type into: one of str, unicode, :py:class:`HTMLElement`, \
:py:class:`selenium.webdriver.remote.webelement.WebElement`, :py:class:`Alert`
... | 18,106 |
def as_binary_vector(labels, num_classes):
"""
Construct binary label vector given a list of label indices.
Args:
labels (list): The input label list.
num_classes (int): Number of classes of the label vector.
Returns:
labels (numpy array): the resulting binary vector.
"""
... | 18,107 |
def evaluation_lda(model, data, dictionary, corpus):
""" Compute coherence score and perplexity.
params:
model: lda model
data: list of lists (tokenized)
dictionary
corpus
returns: coherence score, perplexity score
"""
coherence_model_lda = CoherenceModel(model=model, texts=data, di... | 18,108 |
def get_map_with_square(map_info, square):
"""
build string of the map with its top left
bigger square without obstacle full
"""
map_string = ""
x_indices = list(range(square["x"], square["x"] + square["size"]))
y_indices = list(range(square["y"], square["y"] + square["size"]))
M = map_i... | 18,109 |
def bgr_colormap():
"""
In cdict, the first column is interpolated between 0.0 & 1.0 - this indicates the value to be plotted
the second column specifies how interpolation should be done from below
the third column specifies how interpolation should be done from above
if the second column does not equal the t... | 18,110 |
def test_construct_h6_tag(attributes):
"""Test for validating whether the h6 tag is constructed correctly or not.
"""
h6_ = H6(**attributes)
assert h6_.construct() == h6.render(attributes) | 18,111 |
def autovalidation_from_docstring():
"""
Test validation using JsonSchema
The default payload is invalid, try it, then change the age to a
valid integer and try again
---
tags:
- officer
parameters:
- name: body
in: body
required: true
schema:
i... | 18,112 |
def get_vlan_groups(url, headers):
"""
Get dictionary of existing vlan groups
"""
vlan_groups = []
api_url = f"{url}/api/ipam/vlan-groups/"
response = requests.request("GET", api_url, headers=headers)
all_vlan_groups = response.json()["results"]
for vlan_group in all_vlan_groups:
... | 18,113 |
def highest_price():
""" Finding the ten most expensive items per unit price in the northwind DB """
ten_highest_query = """
SELECT ProductName
FROM Product
GROUP BY UnitPrice
ORDER BY UnitPrice DESC
LIMIT 10; """
ten_highest = cursor.execute(ten_highest_query).fetcha... | 18,114 |
def load_viewpoints(viewpoint_file_list):
"""load multiple viewpoints file from given lists
Args:
viewpoint_file_list: a list contains obj path
a wrapper for load_viewpoint function
Returns:
return a generator contains multiple generators
which contains obj pathes
"... | 18,115 |
def getLastReading(session: Session) -> Reading:
"""
Finds the last reading associated with the session
NB: Always returns a Reading, because every Session has at least 1 Reading
Args:
session (Session): A Session object representing the session record in the database
Returns:
date... | 18,116 |
def process_outlier(data, population_set):
"""
Parameters
----------
data
population_set
Returns
-------
"""
content = list()
for date in set(map(lambda x: x['date'], data)):
tmp_item = {
"date": date,
"value": list()
}
for val... | 18,117 |
def valid_http(http_success=HTTPOk, # type: Union[Type[HTTPSuccessful], Type[HTTPRedirection]]
http_kwargs=None, # type: Optional[ParamsType]
detail="", # type: Optional[Str]
content=None, # type: Optional[J... | 18,118 |
async def unregister(lrrbot, conn, event, respond_to, channel):
"""
Command: !live unregister CHANNEL
Unregister CHANNEL as a fanstreamer channel.
"""
try:
await twitch.unfollow_channel(channel)
conn.privmsg(respond_to, "Channel '%s' removed from the fanstreamer list." % channel)
except urllib.error.HTTPErro... | 18,119 |
def button(update, context):
"""
Reply button when displayed options.
:param update: update object of chatbot
:param context: context of conversation
"""
query = update.callback_query
entity = query.data
entity_type = context.chat_data["entity_type"]
local_context = {
"inte... | 18,120 |
def operating_cf(cf_df):
"""Checks if the latest reported OCF (Cashflow) is positive.
Explanation of OCF: https://www.investopedia.com/terms/o/operatingcashflow.asp
cf_df = Cashflow Statement of the specified company
"""
cf = cf_df.iloc[cf_df.index.get_loc("Total Cash From Operating Activities"... | 18,121 |
def generate_performance_scores(query_dataset, target_variable, candidate_datasets, params):
"""Generates all the performance scores.
"""
performance_scores = list()
# params
algorithm = params['regression_algorithm']
cluster_execution = params['cluster']
hdfs_address = params['hdfs_addres... | 18,122 |
def correct_sparameters_twelve_term(sparameters_complex,twelve_term_correction,reciprocal=True):
"""Applies the twelve term correction to sparameters and returns a new sparameter list.
The sparameters should be a list of [frequency, S11, S21, S12, S22] where S terms are complex numbers.
The twelve term corr... | 18,123 |
def api_activity_logs(request):
"""Test utility."""
auth = get_auth(request)
obj = ActivityLogs(auth=auth)
check_apiobj(authobj=auth, apiobj=obj)
return obj | 18,124 |
def RNAshapes_parser(lines=None,order=True):
"""
Returns a list containing tuples of (sequence,pairs object,energy) for
every sequence
[[Seq,Pairs,Ene],[Seq,Pairs,Ene],...]
Structures will be ordered by the structure energy by default, of ordered
isnt desired set order to False
"""
resu... | 18,125 |
def get_case_strategy( # pylint: disable=too-many-locals
draw: Callable,
operation: APIOperation,
hooks: Optional[HookDispatcher] = None,
data_generation_method: DataGenerationMethod = DataGenerationMethod.default(),
path_parameters: Union[NotSet, Dict[str, Any]] = NOT_SET,
headers: Union[NotSe... | 18,126 |
def addi(imm_val, rs1):
"""
Adds the sign extended 12 bit immediate to register rs1.
Arithmetic overflow is ignored and the result is the
low 32 bits.
--ADDI rs, rs1, 0 is used to implement MV rd, rs1
"""
reg[rs1] = imm_val + int(reg[rs1]) | 18,127 |
def type_from_value(value, visitor=None, node=None):
"""Given a Value from resolving an annotation, return the type."""
ctx = _Context(visitor, node)
return _type_from_value(value, ctx) | 18,128 |
def _accesslen(data) -> int:
"""This was inspired by the `default_collate` function.
https://github.com/pytorch/pytorch/blob/master/torch/utils/data/_utils/
"""
if isinstance(data, (tuple, list)):
item = data[0]
if not isinstance(item, (float, int, str)):
return len(item)
... | 18,129 |
def createSkill(request, volunteer_id):
"""
Method to create skills and interests
:param request:
:param volunteer_id:
:return:
"""
if request.method == 'POST':
volunteer = Volunteer_User_Add_Ons.objects.get(pk=volunteer_id)
skills = request.POST.getlist('skills')
in... | 18,130 |
def analyticJacobian(robot : object, dq = 0.001, symbolic = False):
"""Using Homogeneous Transformation Matrices, this function computes Analytic Jacobian Matrix of a serial robot given joints positions in radians. Serial robot's kinematic parameters have to be set before using this function
Args:
robot (Seria... | 18,131 |
def test_sharedmethod_reuse_on_subclasses():
"""
Regression test for an issue where sharedmethod would bind to one class
for all time, causing the same method not to work properly on other
subclasses of that class.
It has the same problem when the same sharedmethod is called on different
instan... | 18,132 |
def get_subtask_spec_factory_classes():
"""Return dictionary with all factory classes defined in files in this directory.
This file is excluded from the search."""
this_file = os.path.split(__file__)[-1]
directory = os.path.dirname(__file__)
exclude = [this_file, "subtask_spec_factory.py"]
fact... | 18,133 |
def test_countMatches():
"""Unit test for countMatches function. Checks output is as
expected for a variety of extreme cases."""
# create test image
ground_truth = np.zeros((20, 20))
ground_truth[4:10, 4:10] = 1
inferred = np.zeros((20, 20))
inferred[4:10, 4:6] = 1
inferred[4:10, 6:10] ... | 18,134 |
def check_keyup_events(event, ship):
"""Respond to key release."""
if event.key == pygame.K_RIGHT:
ship.moving_right = False
elif event.key == pygame.K_LEFT:
ship.moving_left = False
elif event.key == pygame.K_UP:
ship.moving_up = False
elif event.key == pygame.K_DOWN... | 18,135 |
def triu_indices_from(arr, k=0):
"""
Returns the indices for the upper-triangle of `arr`.
Args:
arr (Union[Tensor, list, tuple]): 2-dimensional array.
k (int, optional): Diagonal offset, default is 0.
Returns:
triu_indices_from, tuple of 2 tensor, shape(N)
Indices for t... | 18,136 |
def is_debug():
"""Return true if xylem is set to debug console output."""
global _debug
return _debug | 18,137 |
def import_metrics(jsondoc):
"""Update metrics DB from `dict` data structure.
The input data structure is expected to be the one produced by SNMP
simulator's command responder `fulljson` reporting module.
.. code-block:: python
{
'format': 'jsondoc',
'version': 1,
'host'... | 18,138 |
def func(var):
"""Function"""
return var + 1 | 18,139 |
def register_user(username, password):
"""
Hashes the given password and registers a new user in the database.
"""
hashed_password = bcrypt.hash(password)
app_user = AppUser(username=username.lower(), password=hashed_password)
db.session.add(app_user)
db.session.commit() | 18,140 |
def flanking_regions_fasta_deletion(genome, dataframe, flanking_region_size):
"""
Makes batch processing possible, pulls down small region
of genome for which to design primers around.
This is based on the chromosome and position of input file.
Each Fasta record will contain:
>Sample_Gene_chr:... | 18,141 |
def numpy_episodes(
train_dir, test_dir, shape, loader, preprocess_fn=None, scan_every=10,
num_chunks=None, **kwargs):
"""Read sequences stored as compressed Numpy files as a TensorFlow dataset.
Args:
train_dir: Directory containing NPZ files of the training dataset.
test_dir: Directory con... | 18,142 |
def fft_convolve(ts, query):
"""
Computes the sliding dot product for query over the time series using
the quicker FFT convolution approach.
Parameters
----------
ts : array_like
The time series.
query : array_like
The query.
Returns
-------
array_like - The sli... | 18,143 |
def _add_merge_gvcfs_job(
b: hb.Batch,
gvcfs: List[hb.ResourceGroup],
output_gvcf_path: Optional[str],
sample_name: str,
) -> Job:
"""
Combine by-interval GVCFs into a single sample GVCF file
"""
job_name = f'Merge {len(gvcfs)} GVCFs, {sample_name}'
j = b.new_job(job_name)
j.ima... | 18,144 |
def register_permission(name, codename, ctypes=None):
"""Registers a permission to the framework. Returns the permission if the
registration was successfully, otherwise False.
**Parameters:**
name
The unique name of the permission. This is displayed to the customer.
codename
The u... | 18,145 |
def calculate_outliers(tile_urls, num_outliers, cache, nprocs):
"""
Fetch tiles and calculate the outlier tiles per layer.
The number of outliers is per layer - the largest N.
Cache, if true, uses a local disk cache for the tiles. This can be very
useful if re-running percentile calculations.
... | 18,146 |
def load_trigger_dataset(
fname,
templatizer,
limit=None,
train=False,
preprocessor_key=None,
priming_dataset=None,
max_priming_examples=64,
):
"""
Loads a MLM classification dataset.
Parameters
==========
fname : str
The filename.
templatizer : Templatizer
... | 18,147 |
def pmu2bids(physio_files, verbose=False):
"""
Function to read a list of Siemens PMU physio files and
save them as a BIDS physiological recording.
Parameters
----------
physio_files : list of str
list of paths to files with a Siemens PMU recording
verbose : bool
verbose fla... | 18,148 |
def add_chain(length):
"""Adds a chain to the network so that"""
chained_works = []
chain = utils.generate_chain(length)
for i in range(len(chain)-1):
agent_id = get_random_agent().properties(ns.KEY_AGENT_ID).value().next()
work_id = g.create_work().properties(ns.KEY_WORK_ID).value().nex... | 18,149 |
async def ping(ctx):
""" Pong """
await ctx.send("pong") | 18,150 |
def re_fit(file_name, top_c, bot_c):
""" re-fits a prepared oocyte file (-t and -b flags for top and bot constraints)"""
from vartools.result import re_fit_data
if top_c == "True":
top_c = True
elif top_c == "False":
top_c = False
else:
sys.exit("Invalid option: " + top_c)
... | 18,151 |
def convert_graph_to_db_format(input_graph: nx.Graph, with_weights=False, cast_to_directed=False):
"""Converts a given graph into a DB format, which consists of two or three lists
1. **Index list:** a list where the i-th position contains the index of the beginning of the list of adjacent nodes (in th... | 18,152 |
def read_pnts(pnt_bytes, object_layers):
"""Read the layer's points."""
print("\tReading Layer ("+object_layers[-1].name+") Points")
offset= 0
chunk_len= len(pnt_bytes)
while offset < chunk_len:
pnts= struct.unpack(">fff", pnt_bytes[offset:offset+12])
offset+= 12
# Re-order ... | 18,153 |
def auxiliary_subfields():
"""Factory associated with AuxSubfieldsPoroelasticity.
"""
return AuxSubfieldsPoroelasticity() | 18,154 |
def cassandra_get_unit_data():
"""
Basing function to obtain units from db and return as dict
:return: dictionary of units
"""
kpi_dict = {}
cassandra_cluster = Cluster()
session = cassandra_cluster.connect('pb2')
query = session.prepare('SELECT * FROM kpi_units')
query_data = sessio... | 18,155 |
def read_cfg_float(cfgp, section, key, default):
"""
Read float from a config file
Args:
cfgp: Config parser
section: [section] of the config file
key: Key to be read
default: Value if couldn't be read
Returns: Resulting float
"""
if cfgp.has_option(section, key... | 18,156 |
def get_repository_output(repository_name: Optional[pulumi.Input[str]] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> pulumi.Output[GetRepositoryResult]:
"""
The AWS::ECR::Repository resource specifies an Amazon Elastic Container Registry (Amazon ECR) repository, where users c... | 18,157 |
def random(website):
"""
随机获取cookies
:param website:查询网站给 如:weibo
:return:随机获取的cookies
"""
g = get_conn()
cookies = getattr(g, website + '_cookies').random()
return cookies | 18,158 |
def get_pid(referral_data):
""" Example getting PID using the same token used to query AD
NOTE! to get PID the referral information must exist in the BETA(UAT) instance of TOMS
"""
referral_uid = referral_data['referral_uid']
url = "https://api.beta.genomics.nhs.uk/reidentification/referral-pid... | 18,159 |
def test_create_search_space():
"""Generate a random neural network from the search_space definition.
"""
import random
random.seed(10)
from random import random
from tensorflow.keras.utils import plot_model
import tensorflow as tf
tf.random.set_seed(10)
search_space = create_searc... | 18,160 |
def open_events(
fname: Union[Path, str], leap_sec: float, get_frame_rate: bool = False
) -> Tuple[
List[float], List[float], List[float], List[datetime], Union[List[float], None]
]:
"""
Parameters
----------
fname : Path or str
filename of *_events.pos file
leap_sec : float
... | 18,161 |
def intdags_permutations(draw, min_size:int=1, max_size:int=10):
""" Produce instances of a same DAG. Instances are not nesessarily
topologically sorted """
return draw(lists(permutations(draw(intdags())),
min_size=min_size,
max_size=max_size)) | 18,162 |
def rich_echo_via_pager(
text_or_generator: t.Union[t.Iterable[str], t.Callable[[], t.Iterable[str]], str],
theme: t.Optional[Theme] = None,
highlight=False,
markdown: bool = False,
**kwargs,
) -> None:
"""This function takes a text and shows it via an environment specific
pager on stdout.
... | 18,163 |
def getConfiguredGraphClass(doer):
"""
In this class method, we must return a configured graph class
"""
# if options.bReified:
# DU_GRAPH = Graph_MultiSinglePageXml_Segmenter_Separator_DOM
if options.bSeparator:
DU_GRAPH = ConjugateSegmenterGraph_MultiSinglePageXml_Separator
els... | 18,164 |
def find_amped_polys_for_syntheticidle(qubit_filter, idleStr, model, singleQfiducials=None,
prepLbl=None, effectLbls=None, initJ=None, initJrank=None,
wrtParams=None, algorithm="greedy", require_all_amped=True,
... | 18,165 |
def _seed(x, deg=5, seeds=None):
"""Seed the greedy algorithm with (deg+1) evenly spaced indices"""
if seeds is None:
f = lambda m, n: [ii*n//m + n//(2*m) for ii in range(m)]
indices = np.sort(np.hstack([[0, len(x)-1], f(deg-1, len(x))]))
else:
indices = seeds
errors = []
return indices, errors | 18,166 |
def check_radius_against_distance(cube, radius):
"""Check required distance isn't greater than the size of the domain.
Args:
cube (iris.cube.Cube):
The cube to check.
radius (float):
The radius, which cannot be more than half of the
size of the domain.
"... | 18,167 |
def get_ref(cube):
"""Gets the 8 reflection symmetries of a nd numpy array"""
L = []
L.append(cube[:,:,:])
L.append(cube[:,:,::-1])
L.append(cube[:,::-1,:])
L.append(cube[::-1,:,:])
L.append(cube[:,::-1,::-1])
L.append(cube[::-1,:,::-1])
L.append(cube[::-1,::-1,:])
L.append(cube[... | 18,168 |
def get_relation_functionality(
mapped_triples: Collection[Tuple[int, int, int]],
add_labels: bool = True,
label_to_id: Optional[Mapping[str, int]] = None,
) -> pd.DataFrame:
"""Calculate relation functionalities.
:param mapped_triples:
The ID-based triples.
:return:
A datafram... | 18,169 |
def df_to_vega_lite(df, path=None):
"""
Export a pandas.DataFrame to a vega-lite data JSON.
Params
------
df : pandas.DataFrame
dataframe to convert to JSON
path : None or str
if None, return the JSON str. Else write JSON to the file specified by
path.
"""
chart ... | 18,170 |
def _is_json_mimetype(mimetype):
"""Returns 'True' if a given mimetype implies JSON data."""
return any(
[
mimetype == "application/json",
mimetype.startswith("application/") and mimetype.endswith("+json"),
]
) | 18,171 |
def show_fields(*fields):
"""Output the {field label -> field value} dictionary. Does the alignment
and formats certain specific types of values."""
fields = filter( lambda x: x, fields )
target_len = max( len(name) for name, value in fields ) + 2
for name, value in fields:
line = name + ':... | 18,172 |
def make_request(action, data, token):
"""Make request based on passed arguments and timestamp."""
return {
'action': action,
'time': datetime.now().timestamp(),
'data': data,
'token': token
} | 18,173 |
def get_stats_historical_prices(timestamp, horizon):
"""
We assume here that the price is a random variable following a normal
distribution. We compute the mean and covariance of the price distribution.
"""
hist_prices_df = pd.read_csv(HISTORICAL_PRICES_CSV)
hist_prices_df["timestamp"] = pd.to_d... | 18,174 |
def _unflattify(values, shape):
"""
Unflattifies parameter values.
:param values: The flattened array of values that are to be unflattified
:type values: torch.Tensor
:param shape: The shape of the parameter prior
:type shape: torch.Size
:rtype: torch.Tensor
"""
if len(shape) < 1 or... | 18,175 |
def sc_iter_fasta_brute(file_name, inmem=False):
""" Iter over fasta file."""
header = None
seq = []
with open(file_name) as fh:
if inmem:
data = fh.readlines()
else:
data = fh
for line in data:
if line.startswith(">"):
if ... | 18,176 |
def theme_cmd(data, buffer, args):
"""Callback for /theme command."""
if args == '':
weechat.command('', '/help ' + SCRIPT_COMMAND)
return weechat.WEECHAT_RC_OK
argv = args.strip().split(' ', 1)
if len(argv) == 0:
return weechat.WEECHAT_RC_OK
if argv[0] in ('install',):
... | 18,177 |
def get_unique_chemical_names(reagents):
"""Get the unique chemical species names in a list of reagents.
The concentrations of these species define the vector space in which we sample possible experiments
:param reagents: a list of perovskitereagent objects
:return: a list of the unique chemical names... | 18,178 |
def get_sorted_keys(dict_to_sort):
"""Gets the keys from a dict and sorts them in ascending order.
Assumes keys are of the form Ni, where N is a letter and i is an integer.
Args:
dict_to_sort (dict): dict whose keys need sorting
Returns:
list: list of sorted keys from dict_to_sort
... | 18,179 |
def model_3d(psrs, psd='powerlaw', noisedict=None, components=30,
gamma_common=None, upper_limit=False, bayesephem=False,
wideband=False):
"""
Reads in list of enterprise Pulsar instance and returns a PTA
instantiated with model 3D from the analysis paper:
per pulsar:
... | 18,180 |
def max_votes(x):
"""
Return the maximum occurrence of predicted class.
Notes
-----
If number of class 0 prediction is equal to number of class 1 predictions, NO_VOTE will be returned.
E.g.
Num_preds_0 = 25,
Num_preds_1 = 25,
Num_preds_NO_VOTE = 0,
... | 18,181 |
def misclassification_error(y_true: np.ndarray, y_pred: np.ndarray, normalize: bool = True) -> float:
"""
Calculate misclassification loss
Parameters
----------
y_true: ndarray of shape (n_samples, )
True response values
y_pred: ndarray of shape (n_samples, )
Predicted response ... | 18,182 |
def dunif(x, minimum=0,maximum=1):
"""
Calculates the point estimate of the uniform distribution
"""
from scipy.stats import uniform
result=uniform.pdf(x=x,loc=minimum,scale=maximum-minimum)
return result | 18,183 |
def fatal(msg):
""" Print an error message and die """
global globalErrorHandler
globalErrorHandler._fatal(msg) | 18,184 |
def _generate_upsert_sql(mon_loc):
"""
Generate SQL to insert/update.
"""
mon_loc_db = [(k, _manipulate_values(v, k in TIME_COLUMNS)) for k, v in mon_loc.items()]
all_columns = ','.join(col for (col, _) in mon_loc_db)
all_values = ','.join(value for (_, value) in mon_loc_db)
update_query = '... | 18,185 |
def filtered_qs(func):
"""
#TODO: zrobić, obsługę funkcji z argumentami
:param func:
:return:
"""
@functools.wraps(func)
def wrapped(self, *args, **kwargs):
ret_qs = func(self)
return ret_qs.filter(*args, **kwargs)
return wrapped | 18,186 |
def dict2obj(d):
"""Given a dictionary, return an object with the keys mapped to attributes
and the values mapped to attribute values. This is recursive, so nested
dictionaries are nested objects."""
top = type('dict2obj', (object,), d)
seqs = tuple, list, set, frozenset
for k, v in d.items():
... | 18,187 |
async def paste(pstl):
""" For .paste command, allows using
dogbin functionality with the command. """
dogbin_final_url = ""
match = pstl.pattern_match.group(1).strip()
reply_id = pstl.reply_to_msg_id
if not match and not reply_id:
await pstl.edit("There's nothing to paste.")
... | 18,188 |
def customized_algorithm_plot(experiment_name='finite_simple_sanity', data_path=_DEFAULT_DATA_PATH):
"""Simple plot of average instantaneous regret by agent, per timestep.
Args:
experiment_name: string = name of experiment config.
data_path: string = where to look for the files.
Returns:
p: ggplot p... | 18,189 |
def main(target_dir=None):
"""
Read gyp files and create Android.mk for the Android framework's
external/skia.
@param target_dir Directory in which to place 'Android.mk'. If None, the file
will be placed in skia's root directory.
"""
# Create a temporary folder to hold gyp and gypd files... | 18,190 |
def write_var(db, blob_id, body):
"""
"""
size = len(body)
with open(make_path(blob_id), "wb") as f:
f.write(body)
cur = db.cursor()
cur.execute("UPDATE objs SET size=?, status=? WHERE id=?", (size, STATUS_COMPLETE, blob_id))
db.commit() | 18,191 |
def _get_log_time_scale(units):
"""Retrieves the ``log10()`` of the scale factor for a given time unit.
Args:
units (str): String specifying the units
(one of ``'fs'``, ``'ps'``, ``'ns'``, ``'us'``, ``'ms'``, ``'sec'``).
Returns:
The ``log10()`` of the scale factor for the time... | 18,192 |
def match_info_multithreading():
"""
多线程匹配信息
:return:
"""
start = 0
num = 100
total = vj['user'].count()
thread_pool = []
while start < total:
th = threading.Thread(target=match_info, args=(start, num))
thread_pool.append(th)
start += num
for th in thread... | 18,193 |
def print_status(status):
""" Helper function printing your status """
print("This is your status:")
print("\n---\n")
print("\n".join(l.strip() for l in status)) | 18,194 |
def resolvermatch(request):
"""Add the name of the currently resolved pattern to the RequestContext"""
match = resolve(request.path)
if match:
return {'resolved': match}
else:
return {} | 18,195 |
def create_vlan(host, port, user, password, interface, int_id, vlan, ip, mask, template, config):
"""Function to create a subinterface on CSR1000V."""
intfc = re.compile(r'^(\D+)(\d+)$')
m = intfc.match(interface + int_id)
if m is None:
print("Invalid interface name. Valid example: ", BASE)
... | 18,196 |
def selection_sort(arr: list) -> list:
"""
Main sorting function. Using "find_smallest" function as part
of the algorythm.
:param arr: list to sort
:return: sorted list
"""
new_arr = []
for index in range(len(arr)):
smallest = find_smallest(arr)
new_arr.append(arr.pop(sma... | 18,197 |
def get_primary_monitor():
"""
Returns the primary monitor.
Wrapper for:
GLFWmonitor* glfwGetPrimaryMonitor(void);
"""
return _glfw.glfwGetPrimaryMonitor() | 18,198 |
def query_people_and_institutions(rc, names):
"""Get the people and institutions names."""
people, institutions = [], []
for person_name in names:
person_found = fuzzy_retrieval(all_docs_from_collection(
rc.client, "people"),
["name", "aka", "_id"],
person_name, c... | 18,199 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.