content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import pickle
def get_ctf_by_name(database, name):
"""
Fetch a CTF object in the database with a given name.
Return the matching CTF object if found, or None otherwise.
"""
ctfs = pickle.load(open(database, "rb"))
for ctf in ctfs:
if ctf.name == name:
return ctf
return... | 32bf2489da5a01810813715060bdcdd15126b8f7 | 3,601,200 |
def system_storage(required_resource_keys, name=None, is_persistent=True, config_schema=None):
"""Creates a system storage definition.
The decorated function will be passed as the ``system_storage_creation_fn`` to a
:py:class:`SystemStorageDefinition`.
Args:
name (str): The name of the system ... | 7eccc29c3616ef534a2b489cd551bc473488ffed | 3,601,201 |
def run(gens, env, version):
"""
Run the pole balancing task using the Gym environment
Returns the winning genome and the statistics of the run.
"""
winner, stats = run_es(gens, env, 500, CONFIG, params(version), SUBSTRATE)
print(f"es_hyperneat_polebalancing_{VERSION_TEXT} done")
return winn... | e592f0c28e69b16e7498a7aff450fb19bd9f8126 | 3,601,202 |
def flow_to_color(flow_uv, clip_flow=None, convert_to_bgr=False):
"""
Expects a two dimensional flow image of shape [H,W,2]
According to the C++ source code of Daniel Scharstein
According to the Matlab source code of Deqing Sun
:param convert_to_bgr: convert output to BGR in the process
:param f... | da55f830984d05837d1318752525b643550b9d12 | 3,601,203 |
def find_greater(l,cab,year):
"""
Compraing list objects in their years according to their cab type
Parameters:
l(list): list of car
cab(str): type of car
year(int): year
returns:
str: return a
"""
counter_year = 0
temp_km = 0
for i in l:
... | 33dac27085495a7d2f5145216acdc124c111c7bf | 3,601,204 |
def find_dist_max(ar_coorx,ar_coory):
"""
Compute the maximum distance between several points defined by their coordinates ar_coorx and ar_coory
"""
nb_cell=len(ar_coorx)
max_dist=0.
for i in range(nb_cell):
for j in range(nb_cell):
max_dist=max(max_dist,distance(ar_coorx[i],... | 40cad577460cf853f589da16a0fb1efeee5e41f4 | 3,601,205 |
from typing import Optional
def start(
categories: Optional[str] = None,
options: Optional[str] = None,
bufferUsageReportingInterval: Optional[float] = None,
transferMode: Optional[str] = None,
streamFormat: Optional[StreamFormat] = None,
streamCompression: Optional[StreamCompression] = None,
... | 369e64cb444b119a0fce8a7b2638817f89e237b8 | 3,601,206 |
def parse_tree(lines):
"""Parses input lines into a decision tree."""
current_index = [0] # need mutable container because of closure limitations
def parse(current_depth):
"""Helper recursive function."""
node_feature = None
children = []
while current_index[0] < len(lines):
... | 2e2b9a408f4682b5a5e61b5830ccad0409646573 | 3,601,207 |
import random
def _random_level():
"""Returns a random level for the new skiplist node
The return value of this function is between 1 and ZSKIPLIST_MAXLEVEL
(both inclusive), with a powerlaw-alike distribution where higher
levels are less likely to be returned.
"""
level = 1
while random.... | 3f5f13defae1140836fedf29c257ed6fc9b68384 | 3,601,208 |
def mobilenet_v2_factory(image_size, pretrained=True):
"""
Args:
image_size:
pretrained:
Returns:
"""
model = MobileNetV2(image_size)
if pretrained:
model.load_state_dict(
load_state_dict_from_url(
"https://download.pytorch.org/models/mobilenet_... | b6bd8f3dc20a68a57bc0b4d268d7b9f4429c04a7 | 3,601,209 |
def make_3d_plots(canonical_field, live_field):
"""
Makes a 3D plot of the live sdf, with the SDF value plotted along the (vertical) Z axis
:param canonical_field: canonical (source) SDF field
:param live_field: warped/transformed live (target) SDF field
:return: image (numpy array) of the 3D plot
... | 10ee05a2a4be346dd869699713ccb831dae463db | 3,601,210 |
def run_analysis(GM_dt, GM_npts, TS_List, EDP_specs, model_params):
"""
Run dynamic analysis for a time history and return a dictionary of envelope EDPs.
Assumes that length is measured in inches and acceleration in in/s2
Parameters
----------
GM_dt: float
Time step of time series
... | 7deae3f1ddedba4d32eb31298e4b161e38226ce0 | 3,601,211 |
def num_rep_2d(xvec, yvec, rCut):
"""
Find the number of replications necessary such that the
2D-circle of radius r_cut at the center of the primitive-cell
lies completely inside the super-cell.
Parameters
-----------------
xvec : numpy array
The basis vector in x direction in x-z p... | f26239c39b0209bb23b532128c7c7aa817411b17 | 3,601,212 |
import subprocess
def capture(command):
"""
Run input command as subprocess and caputure the subprocess' exit code, stdout and stderr.
Parameters
----------
command : list of str
Command to be run as subprocess.
Returns
-------
out : str
Standard output message.
e... | b2d668f4ff125f1793b2688c127276fe9c209651 | 3,601,213 |
import json
def get_results(response):
"""This helper method consumes the response of an ElasticSearch Query and
adds the hits to an array then returns a dictionary representing the
results"""
hit_arr = []
agg_dict = response.aggregations.to_dict()
for hit in response:
hit_dic... | 8bd7ae3d88b57b2af75aedd9b64778832da5f1c8 | 3,601,214 |
def logout():
"""Logout process."""
logout_user()
flash('Вы успешно разлогинились')
return redirect(url_for('landing.index')) | f06f8650ce2b06d8c7ae9329edb7446b78d576cd | 3,601,215 |
def get_minifig_sets(minifig_id, page=None, page_size=None, ordering=None, api_key=None):
"""
Gets details about available sets containing specific minifig.
Args:
minifig_id: str or int
Rebrickable minifig ID.
page: int or None
A page number within the p... | de0a853ff7886585194b1f7cad371806b8f7aa15 | 3,601,216 |
async def async_get_config_entry_diagnostics(
hass: HomeAssistant, config_entry: ConfigEntry
) -> dict:
"""Return diagnostics for a config entry."""
trackables = hass.data[DOMAIN][config_entry.entry_id][TRACKABLES]
diagnostics_data = async_redact_data(
{
"config_entry": config_entry... | f7a5a84a6cb93c0aacc377cc66bc122f8f9efc3b | 3,601,217 |
def ucm_retrieval(retrieval_conf, vectors, targets, mode='test'):
"""
Perform retrieval on the smaller datasets. Difficulty thresholds should
be modified is not using the standard (0.6, 0.4, 0.2) values.
:param retrieval_conf: Retrieval configuration.
:param vectors: Matrix of image embeddings.
... | d7749e90563386ff26041bc988af71050f0f2f0a | 3,601,218 |
import os
def movie_edit(id=None):
"""
编辑电影页面
"""
form = MovieForm()
# 因为是编辑,所以非空验证空
form.url.validators = []
form.logo.validators = []
movie = Movie.query.get_or_404(int(id))
if request.method == "GET":
form.info.data = movie.info
form.tag_id.data = movie.tag_id
... | fb068ecf25133d76eefd1fa1ace74968c2f32060 | 3,601,219 |
import difflib
def diff_lists(one, two):
"""Accepts two lists."""
# d = difflib.Differ() #linejunk=ignore_newline)
# oneclean = []
# twoclean = []
# for line in one:
# oneclean.append(line.encode('ascii', 'replace'))
# for line in two:
# twoclean.append(line.encode('ascii', 'replace'))
# #a = d.compare(one... | 7204a8e8a8ddeb470180f580256d7241126ed0bd | 3,601,220 |
import requests
import json
def address(lat, lng, *, raw=False):
"""
DVB Map Address
(GET https://www.dvb.de/apps/map/address)
:param lat: Latitude
:param lng: Longitude
:param raw: Return raw response
:return: Dict of address
"""
try:
lat, lng = wgs_to_gk4(lat, lng)
... | 6b09c12330491fc23cfe3ca7e168f9916614de83 | 3,601,221 |
def twoTauOU_gaussianSpikes(theta, deltaT, binSize, T, numTrials, data_mean, data_var, disp):
"""Generate a two-timescales process with spike counts sampled from a Guassion distribution.
Assuming that disperssion parameter (fano factor) of spike generation function is known.
Parameters
-----------
... | b567ee3a36337ef17fedf6bf370fd2e91c57b14d | 3,601,222 |
import os
def read_data(fname,):
"""
General routine of reading data.
Input file format
-----------------
```
# Comment lines begins with '#' or '!'
#
10 1.0
0.1234 0.2345 0.3456 0.4567 0.5678 0.6789
0.7890 0.8901 0.9012 0.0123
```
- 1st line: num of ... | c905c74188ff5f668a7c5712c3438f88e0bff45a | 3,601,223 |
def get_py_param_value(context):
"""Extract the value of a parameter.
Dedicated to parameters under dynamic reconfigure
Args:
context (dict): context (related to an param description)
Returns:
str: The value of the parameter as a string
Examples:
>>> context = {desc="an in... | ffeb1044674799b8bb92f90eba963281061a55d3 | 3,601,224 |
def makeBleMessage(header, payload):
"""Factory method for identifying incoming BLE messages and creating the
correct message subclass instance.
"""
# All the supported messages are listed here. Keep ABC-sorted for neatness.
lookup = {
AttClientAttributePrepareWriteResponse().header : A... | 2cb10dbb03cd9b6060242ef40f5ebeccac0cd0f2 | 3,601,225 |
def message(username=None):
"""
Get and send messages
"""
if request.method == 'GET':
messages = current_user.get_messages()
message_data = Message.get_message_data(messages)
users = set()
for u in message_data:
users.add(u['from'])
users.add(... | 3ef1e12952eb9393a2d7ed547d10ea67845a22b2 | 3,601,226 |
from string import Template
import os
def css_renditions(selector=None):
"""
Returns a (long) string containing all the CSS styles in order to support
terminal text renditions (different colors, bold, etc) in an HTML terminal
using the dump_html() function. If *selector* is provided, all styles will
... | 0582fce55be4b9e5a5e617dac02d930159857b20 | 3,601,227 |
def add_contig_to_header(line, ref_file):
"""Streaming target to add contigs to a VCF file header.
"""
if line.startswith("##fileformat=VCF"):
out = [line]
for region in ref.file_contigs(ref_file):
out.append("##contig=<ID=%s,length=%s>" % (region.name, region.size))
retu... | 06135e7b87d33479cb04b9e22173249c4ed7567c | 3,601,228 |
import re
def quac_qasm_transpiler(qiskit_qasm: str) -> str:
"""Converts Qiskit-generated QASM instructions into QuaC-supported instructions
:param qiskit_qasm: a string with a QASM program
:return: a string with a modified QuaC-supported QASM program
"""
quac_qasm = ""
for line in qiskit_qas... | 1db5932053e00756e80db49b555ee70d3f4d881c | 3,601,229 |
def calculate_kinetic_energy(mass, velocity):
"""Returns kinetic energy of mass [kg] with velocity level."""
return 0.5 * mass * velocity ** 2 | 3e92aec7f7fd86b06c8c3ac5671e8908d9a175dd | 3,601,230 |
def build_LISTA_act(prob,tao,T,eps=0.01,initial_lambda=.1,untied=False):
"""
Builds a LISTA network to infer x from prob.y_ = matmul(prob.A,x) + AWGN
return a list of layer info (name,xhat_,newvars)
name : description, e.g. 'LISTA T=1'
xhat_ : that which approximates x_ at some point in the algori... | 1093a6b68a2d4f48dd4f0a051d7de1db0f766e25 | 3,601,231 |
def moftype(cimtype, refclass):
"""Converts a CIM type name to MOF syntax."""
if cimtype == 'reference':
_moftype = refclass + " REF"
else:
_moftype = cimtype
return _moftype | c09697b9a1fabea1f1529de8ab7ee7eeed4da846 | 3,601,232 |
def add_cumulative_samples(df: pd.DataFrame) -> pd.DataFrame:
"""
Add cumulative samples to data table
This is useful for multi file recordings and helping to decide which files
to read to get a certain time range
Parameters
----------
df : pd.DataFrame
Data table with an n_samples... | df0c84d8e41ebfb57b7d3660d9400f25c2625655 | 3,601,233 |
def user_model():
"""Returns the User model object as a test fixture."""
return User | 882c2d886d9c2808e1ce44788b2ec4eb826b11cc | 3,601,234 |
def is_resource_sufficient(order_ingredients):
"""
Returns True when order can be made, False if ingredients are insufficient.
"""
for item in order_ingredients:
if order_ingredients[item] > resources[item]:
print(f"Sorry!! there is not enough {item}.😢")
return False
... | 42b6d324e9bd506e3b4d75514fc9ffa001c3c593 | 3,601,235 |
import random
import os
import torch
def set_seed_logger(args):
"""Initialize the seed and environment variable
Args:
args: the hyper-parameters.
Returns:
args: the hyper-parameters modified by the random seed.
"""
global logger
# predefining random initial seeds
rando... | 095d84a8bf3324f51bf37e483f1b18007cf20db5 | 3,601,236 |
from typing import Any
from typing import Type
from typing import Optional
from typing import get_args
from typing import Mapping
from typing import get_origin
def is_instance_of_type(_object: Any, required_type: Type) -> Optional[bool]:
"""
Check if `object` is of type `required_type`.
Works same as `is... | f100ab818b3ee3cbd7ef00487d5156db7b1f2f9c | 3,601,237 |
def es_healthcheck(*args, **kwargs):
"""Elasticsearch healthcheck."""
verbose = kwargs['verbose']
return _run_healthcheck_command([
"curl",
"-f",
"localhost:9200/_cluster/health?wait_for_status=green"
], verbose) | 2979a2b2ff6860d2079864f66bd39a8767237752 | 3,601,238 |
def rleToMask(rleString, height, width):
"""
This function is an rle to mask converter.
You supply the rle string for one mask, along with it's height and width
from the solutions for stage1 and it will return the mask.
Source: https://www.kaggle.com/robertkag/rle-to-mask-converter
"""
row... | 2fa8fa7e9c8a608347509ab0cd910a405ea11526 | 3,601,239 |
def trolls():
"""pull all entries from trolls table"""
trolls_query = Troll.query.all()
troll = [troll.serialize_troll() for troll in trolls_query]
return jsonify(troll) | d7ae72bbf69773e7dcc2312ca85e7fb37261efe0 | 3,601,240 |
from typing import Optional
import types
def _should_dither(in_bits: int,
out_bits: int,
in_range: Optional[types.Range] = None,
out_range: Optional[types.Range] = None,
in_sample_type: Optional[vs.SampleType] = None,
out_s... | 11c9d22800b44ed5a8ab8a1a3ff95e1b88426c24 | 3,601,241 |
def remove_artefacts(data, ch_labels, Fs, data_ref, ch_labels_ref, params=None):
"""
remove_artefacts: simple procedure to remove artefacts
Syntax: data = remove_artefacts(data, ch_labels, Fs, data_ref, ch_refs)
Inputs:
data - EEG data, in bipolar montage; size: N_channels x N (pandas dat... | 0454c5f83ee07d0258400939bb07fcd2d3951e86 | 3,601,242 |
def bd_wgs(lon, lat, check_china=True):
"""Convert BD09 coordinates to WGS84 (fast estimation)."""
result = lib.prcoords_bd_wgs({'lon': lon, 'lat': lat}, check_china)
return (result.lon, result.lat) | 713b6103156a6307ca66c8f347526165f8268476 | 3,601,243 |
import os
import torch
def get_masks(generation_idx, nrows: int, ncols: int, k: int=3, max_dilation: int=1, observed_idx=None, out_dir: str="/tmp", plot_suffix="", plot=True):
"""Get and plot three masks: mask type A for first layer, mask type B for later layers, and mask type B with dilation.
Masks are copie... | c0c6c5ab67a1ef79e4f44d4a5b6fba02f80bc1ce | 3,601,244 |
import uuid
import subprocess
import requests
import os
def create_object(model_name,
studio_url=[],
model_file="",
project_name=[],
release_type='minor',
object_type='model',
model_description=None,
... | 206b7ebf0e5f4b2f2ed15ac10c6eb05752707d52 | 3,601,245 |
def shift(arr: list):
"""
方法从数组中删除第一个元素,并返回该元素的值。此方法更改数组的长度
从数组中删除的元素; 如果数组为空则返回 undefined(None)
"""
if len(arr):
return arr.pop(0)
return None | ff7ea2320c6b9f846b8d047e6a6a76d0cd7ab645 | 3,601,246 |
def rel_diff_cube(cube_0, cube_1, in_threshold=None, out_threshold=None, percentage=False):
"""rel_diff(cube_0, cube_1, in_threshold=None, out_threshold=None, percentage=False) ->
cube of relative difference
| a - b |
_________
|a|
'in_threshold': if passed, this absolute threshold is applied... | 6dd3da914c271f403a58c5d5408d73e98eb2ddb7 | 3,601,247 |
def train(ca, x, target, steps, optimizer, scheduler):
"""Runs cellular automata (nCA), backpropagates and updates the weights
Args:
ca ([type]): cellular automata model
x ([type]): image to update with nCA
target ([type]): target image
steps ([type]): how many times we update w... | 996e13434711fed4132f16cf93534b86dd10b022 | 3,601,248 |
def handle_status_update(loan_id, new_status):
"""Handles a status update for an order."""
# lookup order in your system using loan_id
# set order status to new_status
return '' | d75f6c145346d7fe9c6fd124dc0590fd66b64da6 | 3,601,249 |
import operator
def format_sensors(ant_sensors, band, full_report):
"""Returns a 2D list of antennae sensor values with text-marked anormalies"""
data = []
exclude = []
revised_data = []
# add warning text
for sensor in ant_sensors:
row = []
row.append(sensor["name"])
... | 789c2f0b2b8bb9f82c1988904599185d8385ee52 | 3,601,250 |
def unconfirmed():
"""User is unconfirmed."""
if current_user.is_anonymous or current_user.confirmed:
return redirect(url_for('web.home_page'))
return render_template('auth/unconfirmed.html') | 1c01d770b14056b68dbfe089e41a50d9cacec64a | 3,601,251 |
def extend_line(line, img_width, img_height, horizon):
"""Generates a line that crosses the given point with the given slope,
and that reaches both the bottom of the image and the virtual horizon.
Arguments:
line: A dict with the following keywords:
center: dict of two floats or None
... | 1a371d12be793119d5dfb69c2ccd86abf7dfe52b | 3,601,252 |
def make_sinks_api(client):
"""Create an instance of the Sinks API adapter.
Args:
client (~logging_v2.client.Client): The client
that holds configuration details.
Returns:
_SinksAPI: A metrics API instance with the proper credentials.
"""
generated = ConfigServiceV2Clie... | 7e792fb057b29b277101f189abd4b8ca03972ddf | 3,601,253 |
def pretty_string(dict, indent=0):
""" Returns string containing all keys and values in a dict. Makes it 'Pretty'. """
result = []
for key, value in dict.items():
if isinstance(value, str):
result.append('\t' * indent + ('%s:\t "%s"' % (key, value)).encode('ascii', 'ignore'))
elif isinstance(value, list):
... | a5e5aa17b29bb31bd9122dc878f0a511c2dcafd9 | 3,601,254 |
def search_for_currency():
""" display a currency by currency slug """
users_currencies = get_users_currency()
slug = request.args.get('slug')
currency_data = get_by_slug(slug)
return render_template('single_currency.html', currency=currency_data, user_currencies=users_currencies) | bb8e4d3cc6d3e03d49a26d42009b168e90633965 | 3,601,255 |
import json
def search(request):
"""
JSON-based search api for external calls into the discovery app
"""
query = request.POST.get('q')
type_of = request.POST.get('q_type')
if len(query) > 0:
if type_of == 'kw':
search_results = {
'works': whoosh_helpers.keyw... | 5c661a5b21f084e3a321896ac7b56158eeace0c5 | 3,601,256 |
def std(data: np.ndarray, ddof: int = 1) -> float:
""" 计算修正的样本标准差
:param data: 要求标准差的数据
:param ddof: 修正值,除法分母为n - ddof,默认为1
:return: 标准差
>>> std(np.array([0.2,0.2,0.2,0.2]))
0.0
"""
return data.std(ddof=ddof) | c8dc4ec832a33b0bf194f85b01124d638999123d | 3,601,257 |
def get_unigram_dist(sentences):
"""
Returns a dictionary with unigrams and thier corresponding probability, given a list of sentences as input
"""
# sentences = random.sample(sentences, sample_count)
# sentences = [s[:-1] for s in sentences]
tokens = nltk.tokenize.word_tokenize(' '.join(sentenc... | 2e4034190edfe30c534be47bf4a49192ef5589de | 3,601,258 |
def eval_instance_segmentation_soma(
flag, pred_mask_path, gt_mask_path, img_names, iou_thresh, use_07_metric=False):
"""Calculate average precisions based on evaluation code of PASCAL VOC.
This function evaluates predicted masks obtained from a dataset
which has :math:`N` images by using average pr... | c0758049b121a579ba81f59ecb34c0cc8da5f58c | 3,601,259 |
def _reverse_reaction_rates(ktp_dct, thermo_dct, rxn, temps):
""" use the equilibrium constant to reverse the reaction rates
"""
[rct_idxs, prd_idxs] = rxn
k_equils = _calculate_equilibrium_constant(
thermo_dct, rct_idxs, prd_idxs, temps)
rev_ktp_dct = {}
for pressure, rates in ktp_dct... | 62aa585ce4ac4cd4397a2e1a83f47ed8d4cdd3e0 | 3,601,260 |
def get_entity(endpoint):
"""
Return the entity of a kernel endpoint
Example param: /journals/8767-8766-12-32-2
Return: journals
"""
_entity, _id = parser_endpoint(endpoint)
return _entity | 5682e262ba9bdefc798fc2e3cb3f70e1b7fbc3ec | 3,601,261 |
def x_y_to_zeta_eta(x, y):
"""Same as def x_y_to_zeta_eta, but for ndarrays."""
x = np.abs(x)
y = np.abs(y)
zeta = np.sqrt(x ** 2 + y ** 2) # + offset
eta = np.ones(zeta.shape)
index = np.where(x > y)
zeta[index] = -zeta[index]
eta[index] = (4.0 / np.pi) * np.arctan(y[index] / x[index])... | 11bf993d3b9c0751a04f1a9870d064c1d414e447 | 3,601,262 |
def config_ldap_server_map_override_attribute_value(dut, **kwargs):
"""
Author: Chandra.vedanaparthi@broadcom.com
config_ldap_server_map_override_attribute_value(dut=data.dut1,key_list=[userShell], \
value_list=["/bin/rbash"],config='yes')
config_ldap_server_map_override_attribute_value(dut=data.du... | baac770b00f24a3dc69dfe38dc4640440fa53db2 | 3,601,263 |
import os
import random
import torch
import json
def get_imagenet_ssl_dataset(root, percent, anno_file, transform_labeled,
transform_ulabeled, transform_val):
"""
Args:
root: datapath for your imagenet
precent: the ratio of labeled data to total data
transf... | 7d0b7a5976e0a507475eb07139adac788c7fcbe0 | 3,601,264 |
def bisection_search(f, low:float, high:float):
"""
A root finding method that does not rely on derivatives
:param f: a function f: X -> R
:param low: the lower bracket
:param high: the upper limit bracket
:return: the location of the root, e.g. f(mid) ~ 0
"""
# flip high and low if out... | 297f4fb80f0837d28573199ca05b90821155cd52 | 3,601,265 |
def clustering(edge_list):
"""ノードパスによってクラスタリング"""
clustered_edge_in_list = []
for edge in edge_list:
clustering_edge = ClusteredDirectiveEdgeV15.clustering(edge)
clustered_edge_in_list.append(clustering_edge)
return clustered_edge_in_list | b0998f1d84d6bbc667031a0cfd78771e943686d2 | 3,601,266 |
def name_fun(n):
"""
input: stopping rule
output: finish nodes
"""
output = []
temp = ['']
for i in range(2*n - 1):
temp_cur = []
for j in temp:
candidate_pos = j + '+'
candidate_neg = j + '-'
if str.count(candidate_pos, '+') >= n:
... | 74111c9a31475a764ed98ab5e2cfae6ec894b10c | 3,601,267 |
import torch
from typing import Any
def add_embeddings(df: pd.DataFrame, bert: Any,
overlap: int = 32, non_overlap: int = 64) -> pd.DataFrame:
"""
Add BERT embeddings to a DataFrame of BERT tokens.
:param df: DataFrame containing BERT tokens, as returned by
:func:`make_bert_token... | 3ac1944dc00a407aa1f16201df780f7c1f107461 | 3,601,268 |
def data_from_game(pm: Pymem, module_offset: int):
"""Return x,z,confirmation, sin and cos values read from game memory"""
plahka = pm.read_bool(module_offset+0x54C2F9)
x = pm.read_float(pm.base_address+0x10493C)
z = pm.read_float(pm.base_address+0x104944)
view_sin = pm.read_float(pm.base_address+0x... | ef16df240f937d8edd0b4a4d44edaa3fd7c2d04f | 3,601,269 |
from pathlib import Path
def check_golden_results_for_task(config):
"""
Copies the latest task run's parse_results.txt into the config directory as golden_results.txt
"""
num_qor_failures = 0
run_dir = find_latest_run_dir(config)
if not config.pass_requirements_file:
print(
... | 7c3fcc9babc286e735077442f507d44a42ed6353 | 3,601,270 |
import json
def translate_header(df, dictionary, dictionary_type='inline'):
"""change the headers of a dataframe base on a mapping dictionary.
Parameters
----------
df : `DataFrame`
The dataframe to be translated
dictionary_type : `str`, default to `inline`
The type of dictionary,... | 371443bc112fa2b0892bbcf945e3089aab995122 | 3,601,271 |
from typing import Optional
from typing import Tuple
from typing import List
import yaml
def clean(clean_data_basename: Optional[str] = default_file_name) -> Tuple[pd.DataFrame, List[BookType]]:
"""
data cleaning
"""
class_count: int = 0
label_list: List[BookType] = []
get_from_disk = clean_d... | 787d9a3142dea915e1b7dc7d704ae8b7f9c8719b | 3,601,272 |
import os
import subprocess
import sys
def get_environment_from_batch_command(env_cmd, initial=None):
"""
Take a command (either a single command or list of arguments)
and return the environment created after running that command.
Note that if the command must be a batch file or .cmd file, or the
... | e03c645f28cc2452539247af0b60198d2bbdae30 | 3,601,273 |
def isHit(obbTree, pSource, pTarget):
"""
From https://blog.kitware.com/ray-casting-ray-tracing-with-vtk/
:param obbTree:
:param pSource:
:param pTarget:
:return:
"""
code = obbTree.IntersectWithLine(pSource, pTarget, None, None)
if code == 0:
return False
return True | 6c37fcb3ffc6f33d308e9762b1b0c27b2b374ef7 | 3,601,274 |
def _gen_repo():
"""Return OSTree repo body."""
return {
'id': utils.uuid4(),
'importer_type_id': 'ostree_web_importer',
'importer_config': {},
'distributors': [],
'notes': {'_repo-type': 'OSTREE'},
} | 1359e5f8238cf931aa444b2fa4695397e763d30f | 3,601,275 |
from typing import Tuple
def permute_systems(X: np.ndarray, Y: np.ndarray) -> Tuple[np.ndarray, np.ndarray]:
"""
Samples new matrices by randomly permuting the systems between X and Y. The original matrices
will not be changed.
"""
assert X.shape == Y.shape
# Do not modify the original matrice... | 6568a0e82e2c23f74160a76090dee9c0cd91b331 | 3,601,276 |
import yaml
def load_config_settings(logger, path_to_config_file):
"""
Load config settings from config file
:param logger: the logger
:param path_to_config_file: location of config file
:return: settings dictionary containing values for:
... | dded0ea8a70bb4dee74e2498bf9cdaa2bd1b7676 | 3,601,277 |
import array
def fit_sem_trans_fncs(G: MultiDiGraph, D_obs: dict) -> dict:
"""
Fit transition functions connecting time-slices in causal Bayesian network.
OBS: this function assumes that transition relationships are first-order Markov only. The code needs to modified if longer-range dependencies need to ... | 6766fa0e5f646f52a3206903d2fa0ac70741c040 | 3,601,278 |
def users_status_page(ids, **kwargs):
"""Wrapper for the `GET /api/users/status <https://github.com/ornicar/lila#get-apiusersstatus-fetch-many-users-online-and-playing-flags>`_ endpoint.
Use :data:`~lichesspy.api.users_status` to avoid manual pagination.
"""
kwargs["ids"] = ",".join(ids)
return _api... | b1bc3fbb5d1719297a5dff8614adce350a977ed9 | 3,601,279 |
import struct
def _generate_bmv2_config(ctx):
"""Preprocesses P4 sources and runs p4c on pre-processed P4 file."""
# Preprocess all files and create 'p4_preprocessed_file'.
p4_preprocessed_file = ctx.actions.declare_file(
ctx.genfiles_dir.path + ctx.label.name + ".pp.p4",
)
cpp_toolchain ... | 185ddf0cbd4ae290079e416187b90c0b44f8fb8a | 3,601,280 |
from typing import Optional
import logging
async def build_get_revoc_reg_def_request(submitter_did: Optional[str],
rev_reg_def_id: str) -> str:
"""
Builds a GET_REVOC_REG_DEF request. Request to get a revocation registry definition,
that Issuer creates for a parti... | 4ec248eec72bc02e680025b0157c4e78774cd29a | 3,601,281 |
def county_data_cleaning(county_path):
"""Clean and relabel county data."""
county_df = pd.read_csv(county_path, index_col='county')
return county_df | 89c786f9f84fd3da29c1fd6b3bd32f64696d377d | 3,601,282 |
def rect2pathd(rect):
"""Converts an SVG-rect element to a Path d-string.
The rectangle will start at the (x,y) coordinate specified by the
rectangle object and proceed counter-clockwise."""
x, y = float(rect.get('x', 0)), float(rect.get('y', 0))
w, h = float(rect.get('width', 0)), float(rect.... | 60827810118abb4de47b12457806199639626aee | 3,601,283 |
from typing import List
def harvest_as_atomic_result(input_model: OptimizationInput, nwout: str) -> List[AtomicResult]:
"""Parse each step in the geometry relaxation as a separate AtomicResult
Args:
input_model: Input specification for the relaxation
nwout: Standard out from the NWChem simula... | adb9e88a0974f882ad90f08ad877a38cf3e33339 | 3,601,284 |
def remote_ip() -> IPAddress:
"""Return request's IP address (i.e. address of the client)."""
addr = request.environ.get('HTTP_X_FORWARDED_FOR') or request.environ.get('REMOTE_ADDR')
# nginx uses ::ffff: as a prefix for IPv4 addresses in ipv6only=off mode.
return ip_address(cut_prefix(addr, '::ffff:')) | 2399da700b487ba10d55d3a456535e4e8b3240f8 | 3,601,285 |
import numpy
def weights(x, y, seeds, influences, decay=2):
"""
Calculate weights for the data based on the distance to the seeds.
Use weights to ignore regions of data outside of the target anomaly.
Parameters:
* x, y : 1d arrays
The x and y coordinates of the observations
* seeds :... | 2841c0740614cda25a157c3ff8a4eb0aa859e16c | 3,601,286 |
def nonzero_item_mean(matrix, nan_symbol):
"""快速计算一个矩阵的列均值
"""
return nonzero_user_mean(matrix.T, nan_symbol) | 7dea1fafe106ecf1aca0c375dc9d3b9f6e910a06 | 3,601,287 |
def judge_same_month(input_month_list):
"""
判断 数据 是否 在同一个月
:param input_month_list:list
:return: str or bool
"""
month_list = []
for item in input_month_list:
month_list.append(item["trade_date"].strftime("%Y-%m"))
month_set = set(month_list)
if len(month_set) != 1:
r... | 69082ac16150082bfe6cd9b384fa010a3849e682 | 3,601,288 |
def _create_trip_from_stack(temp_trip_stack, origin_activity, destination_activity):
"""
Aggregate information of trip elements in a structured dictionary
Parameters
----------
temp_trip_stack : list
list of dictionary like elements (either pandas series or python dictionary). C... | f2ddb6c19650c001c714ddeb8372b81ff40f2abe | 3,601,289 |
import os
import re
import imghdr
def validate_content(content, archive_dirname,
formats_to_validate=[
CombineArchiveContentFormat.SED_ML,
],
validate_models_with_languages=True,
config=None):
""" Validate... | 3f04f0a02c2f6abeb922c393dc6fffa5eb9d4dc6 | 3,601,290 |
def _print_behind_ahead(behind, ahead):
""" Print Behind Ahead """
numcommits = ""
if behind:
numcommits += "-" + str(behind)
if behind and ahead:
numcommits += "/"
if ahead:
numcommits += "+" + str(ahead)
return numcommits | 816e761a7d31d41b13b32db4eb01e7ee8040087b | 3,601,291 |
import socket
def live_server(request, app, monkeypatch, pytestconfig):
"""Run application in a separate process.
When the ``live_server`` fixture is applied, the ``url_for`` function
works as expected::
def test_server_is_up_and_running(live_server):
index_url = url_for('index', _ex... | 45bc0d62c851840a8646b06373221ad1ab20ed79 | 3,601,292 |
from io import StringIO
def writeObject(obj, outstream=None, indentStr=None, level=0):
"""
Writes an object to an output stream
"""
outstream = outstream or StringIO()
return writerFor(obj)(obj, outstream, indentStr, level) | 56b3180d1d205639a7c757e53658be6546b79a07 | 3,601,293 |
from dateutil import tz
def make_lecture(link_page, zoom_location):
"""Create a 1hr lecture on zoom with 1 speaker from 2018."""
lecture_type = EventType.objects.get_or_create(name="Lecture")[0]
start_time = timezone.datetime(2018, 4, 20, 16, 20, tzinfo=EST).astimezone(tz.utc)
end_time = timezone.date... | c6dec160403a2ba81b452ab6eebb2d0d30a90c46 | 3,601,294 |
def precprint(prec_type, prec_cap, p):
"""
String describing the precision mode on a p-adic ring or field.
EXAMPLES::
sage: from sage.rings.padics.misc import precprint
sage: precprint('capped-rel', 12, 2)
'with capped relative precision 12'
sage: precprint('capped-abs', 11... | b3eab5f0fd133ead8c413aded650d839a2c818b9 | 3,601,295 |
from typing import Callable
def whitelisted_autolink() -> Callable[[commands.Command], commands.Command]:
"""Decorator to whitelist a guild for automatic linking."""
async def predicate(ctx: commands.Context) -> bool:
cog: "GithubInfo" = ctx.bot.get_cog("GithubInfo")
user, _ = await cog.fetch... | f0abec105c7b461bfaa88762f971b66cc19e8f3b | 3,601,296 |
def valid(board, pos, num):
"""
Returns is the attempted move is valid
:param board: 2d list of ints
:param pos: (row, col)
:param num: int
:return: bool
"""
# Check Row
for i in range(0, len(board)):
if board[pos[0]][i] == num and pos[1] != i:
return False
#... | 1d7754ac3789fb8ee1d23e0bebd265750e5a72f0 | 3,601,297 |
import math
def random_quaternion(rand: np.ndarray = None) -> np.ndarray:
"""
Return uniform random unit quaternion.
Args:
----
rand: Three independent random variables that are uniformly distributed
between 0 and 1.
"""
if rand is None:
rand = np.random.rand(3)... | 746d8e0732c1052bd8ba6f1d40d6557f7decb4b1 | 3,601,298 |
def remove_leading_zeros(num: str) -> str:
"""
Strips zeros while handling -, M, and empty strings
"""
LOGGER.debug('stripping leading zeroes from: %s', num)
if not num:
LOGGER.debug('nothing to do, returning: %s', num)
return num
if num.startswith('M'):
LOGGER.debug('str... | 6ae85c58966c81818a07553a0d3278fab6d6a617 | 3,601,299 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.