content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
from math import log10
import io
import sys
def get_weights(mutation_table, weights):
"""
get_weights
=================
Method to calculate different weights to add to calculate the O/E score with using a mutation frequency table. This weight can
be used as the O/E scaling factor.
1) The PH... | f08ac8383eb07b04e23aa2f60d6693507527c525 | 3,610,000 |
def trainNetwork(data, labels, backend):
"""
Train a quantum neural network on inputs data and
labels, using backend backend. Returns the parameters
learned, a list containing the cost over every
iteration and the validation accuracy.
"""
numQubits = np.log2(len(data[0]))
data = np.array... | b25d3b7f7b8e8193e471293c117a8419ece00ca1 | 3,610,001 |
def normalise(symbol):
"""
Takes a c++ symbol or funtion and splits it into symbol and a normalised argument list.
:Parameters:
symbol : string
A C++ symbol or function definition like ``PolyVox::Volume``, ``Volume::printAll() const``
:return:
a tuple consisting of two strings: ``(qualified function name... | d0f47bfb92bb828199d52b1cac16127222bbfacf | 3,610,002 |
def create_plot(df, title, tech_colors={}):
"""
:param df:
:param title: string, plot title
:param tech_colors: optional dict that maps technologies to colors.
Technologies without a specified color will use a default palette
:return:
"""
# TODO: handle empty dataframe (will give bo... | 390e6b2ad3b8477a7e798ad6e92122a7fb254104 | 3,610,003 |
def predict(x, theta):
"""
Predict the outcome of the data set
"""
hypo_line = theta[0]
for i in range(1, len(theta)):
hypo_line = hypo_line + theta[i] * column(x, i - 1)
y_pred = sigmoid_function(hypo_line)
for j in range(len(y_pred)):
# print(j, y_pred[j])
if y... | 983774fad82f3245c175f1908b1bb54cffbc1efa | 3,610,004 |
def good_corners(img, numFeatures = 25):
"""
Finds corners via Shi-Tomasi Good Features To Track.
Returns corners.
"""
gray = ImageIO.grayscale(img)
corners = cv2.goodFeautresToTrack(gray, numFeatures, 0.01, 10)
corners = np.int0(corners)
return corners | 276f684148d10c8d4271fe44427aff34f3c7411b | 3,610,005 |
import array
def remove_glyf_instructions(tt) -> int:
"""Removes instruction set bytecode from glyph definitions in the glyf table."""
glyph_number: int = 0
for glyph in tt["glyf"].glyphs.values():
glyph.expand(tt["glyf"])
if hasattr(glyph, "program") and glyph.program.bytecode != array.ar... | 1b73d9b2fd53a2568f953faab65d5bfae5351189 | 3,610,006 |
def get_entities_coords(borehole):
"""Get entity and coordinate information of a named borehole
from the A.ENTITIES database in GA's Oracle environment
Parameters:
borehole (string): The name of the borehole to query, eg RN018612
Returns:
A Pandas dataframe with columns:
ENO, ENTIT... | 79925814697ccd6b888594141aed75c4812eb115 | 3,610,007 |
def auth_required_same_user(*args, **kwargs):
"""Decorator for requiring an authenticated user to be the same as the
user in the URL parameters. By default the user url parameter name to
lookup is 'id', but this can be customized by passing an argument:
@auth_require_same_user('user_id')
@bp.route('... | 465c5cf1396998cae6ed339eae77909a0bb52c54 | 3,610,008 |
import sys
def tweet_with_image(twtr, filename, msg, force=False):
""" tweet する """
if "ipy" in sys.argv[0] and not force:
return
#print(msg)
with open(filename, "rb") as imagefile:
imagedata = imagefile.read()
params = {"media[]": imagedata, "status": msg + " #COVID19"}
... | 094983d5469a740a63e2f4c74929cce316b1abf0 | 3,610,009 |
import random
def log_random_msg(node, container, logfile):
"""Print random message to the container log file
:param node: Node the container is running on
:type node: class: tobiko.openstack.topology.OpenStackTopologyNode
:param container: Name of the container
:type container: string
:param... | 3f4b4cdde6090e78530b4fad5fb6cf412f0c32c2 | 3,610,010 |
def admin_timekeeper_state():
"""
timekeeperのstate値を取得する(GET)、state値を変更する(PUT)。
"""
log_request(username())
if request.method == 'GET':
dat = {'state': cds.timekeeper_state()}
return adc_response_json(dat)
# PUTの場合
if not priv_admin():
return adc_response('access forb... | c85744e2edabce247faabae91624b95665534a2e | 3,610,011 |
from typing import Dict
from typing import Any
def _make_version_config(version,
scaling: str,
instance_tag: str,
instances: int = 10) -> Dict[str, Any]:
"""Creates one version config as part of an API response."""
return {scaling: {in... | 1d4f613f35ace2f540629e6c79b3f571b3c2a255 | 3,610,012 |
import os
def calculate_destination(prefix, cuda, lib, lib_ver):
"""Calculates the installation directory."""
return os.path.join(prefix, ".data") | c7b471fb191daa345ddb44ef033d18d96198455c | 3,610,013 |
def get_latest_guild_info():
"""
获取最新的游戏指南
"""
# noinspection PyBroadException
try:
# guild = GuildInfo.query.order_by(GuildInfo.date.desc()).options(GuildInfo.cache.from_cache()).first()
guild = GuildInfo.query.order_by(GuildInfo.date.desc()).first()
except Exception as e:
... | 9a33011cee25e40db3190c04673b345f20165647 | 3,610,014 |
import json
def run(args):
"""Download a chunk of data from a file"""
uid = str(args["uid"])
drive_uid = str(args["drive_uid"])
file_uid = str(args["file_uid"])
chunk_idx = int(args["chunk_index"])
secret = str(args["secret"])
drive = DriveInfo(drive_uid=drive_uid)
try:
(dat... | 12ead08d7d29c738b5a0f1c8f568feac12f8b38b | 3,610,015 |
def fmt_channel_ranges(channels, shorten_seq=5, rs="tm", c_sep="_", zp=2):
"""String of channel numbers separated with delimiters with consecutive channels
are shortened when sequence length above threshold.
Args:
channels: list of channels
shorten_seq: number of consecutive channels to be ... | 438765ff29401ce18fb50246fd00b236a5ea74cd | 3,610,016 |
def expected_wp_fg(situation, probs, data):
"""Expected WP from kicking, factoring in p(FG made)."""
if 'fg_make_prob' in situation and isinstance(situation['fg_make_prob'], float):
pos = situation['fg_make_prob']
else:
fgs = data['fgs']
# Set the probability of success of implausib... | 90c327e50d1b80a3da6b8a366e426cc0dbddcbba | 3,610,017 |
import os
def clone_files(pair):
"""pair = (name, parent). Clone the named student's PE repository
into parent and return (name, path), where path is name/files or
None if the repository does not exist.
parent/name should not already exist."""
name, parent = pair
try:
git_path = f"git:... | 97c364d9a27a865c6171794fc1abe8c7671cff03 | 3,610,018 |
def ppis_fracspassing_counts(ppis, obs, exclude_ppis=None, cutoff=0.5):
"""
For a limited set of ppis (say top 15k), return a list that also includes
as the final column the number of fractionations in which that ppi passes
the threshold.
exclude_ppis is chiefly for excluding cxppis.
ppis should... | 650aa552f3487423d600c06558e2e6657e7c0ddd | 3,610,019 |
def Digits(name = None, attrs = None):
"""match one or more decimal digits
This is the same as (?P<name?attrs>\d+).
If 'name' is not None, the matching text will be put inside a
group of the given name. You can optionally include group
attributes.
"""
return _group(name, Re(r"\d+"... | 8ac09f58cd1043678e15397e9f38d97e6d45a98e | 3,610,020 |
def sec_from_hms(start, *times):
""" Returns a list of times based on adding each offset tuple in times
to the start time (which should be in seconds). Offset tuples can be
in any of the forms: (hours), (hours,minutes), or (hours,minutes,seconds).
"""
ret = []
for t in times:
cur = 0
... | 4c279736f173cbec4170880cfdf279e801847b5a | 3,610,021 |
def delete_task(request, pk):
"""
タスクの削除
アクセス制御 :
指定された pk でタスクが存在しないとき 404
タスクがアクティブでないとき 404
認証されていないときログイン要求
タスクへアクセスする権限がないときエラー
タスクが変更不可(完了済)のときエラー
"""
task = get_object_or_404(Task, pk=pk)
redirect_to = 'public_tasks' if task.is_public() else 'my_tasks'
... | a995d042e29408609acef3a7b02a6384ca15cee2 | 3,610,022 |
import pickle
def load_dataset(logger, args):
"""
加载训练集
"""
logger.info("loading training dataset")
train_path = args.train_path
with open(train_path, "rb") as f:
train_list = pickle.load(f)
# test
# train_list = train_list[:24]
train_dataset = CPMDataset(train_list, arg... | 8bfeb90bee6a3cbe1cbc4777fa692c9658d34555 | 3,610,023 |
def path_exists(node1, node2, G):
"""
This function checks whether a path exists between two nodes (node1,
node2) in graph G.
"""
visited_nodes = set()
queue = [node1]
while len(queue) > 0:
node = queue.pop()
neighbors = list(G.neighbors(node))
if node2 in neighbors... | 6d1560121db7ca58f262ae32c6514c972e0fc96e | 3,610,024 |
def remove_missing_targets(this_data,target_var):
"""
Gets raw data and removes rows with missing targets
Parameters
----------
this_data : dataframe
The raw data which has been compiled from Yahoo!Finance
target_var : string
Column name of target variable
Returns
-----... | 82d9d5f77821c7ee1b6eec53d3b9bb474922beac | 3,610,025 |
import torch
def time_one(funcs, launch_wait=True, timer=None, name='', func_names=None):
""" Run and time a single iteration of funcs.
funcs is a list functions that do GPU work.
:param launch_wait: if True, launches a wait kernel before measuring to hide kernel launch latency.
:param ti... | 7f6febe7101246990c45d72744e44a244462bbcc | 3,610,026 |
def spike_threshold(sample_bin, bin_thres, covariates, cov_bins, spiketimes, direct=False):
"""
Only include spikes that correspond to bins with sufficient occupancy time. This is useful
when using histogram models to avoid counting undersampled bins, which suffer from huge
variance when computing the... | 1aff1772274720ae7468af94aa3542e9e0c5c84a | 3,610,027 |
def tee(iterable, n=2):
"""Return n independent iterators from a single iterable.
:param iterable: the iterator from which to make iterators.
:param n: the number of iterators to make (default is 2)
"""
return [iter(iterable) for _ in range(n)] | cb35d518b90ddf66627e171b00e977823d4d3d17 | 3,610,028 |
import pandas as pd
def pandas_extract_rows(data_frame, ugridtype_str, index_names):
"""removes the t2-t6 for S and E points"""
letter_dims = [
('G', 6),
('E', 1),
('S', 1),
('H', 6),
('L', 6),
]
cat_keys = []
for (letter, dim) in letter_dims:
if let... | 2b297aa5e6944d9eaa6b18031045d3b03e7c6d9f | 3,610,029 |
def all_users():
"""
View that returns all users of the database
"""
r = request
users = db.session.query(User).all()
data = {
"data": [user.as_dict() for user in users],
}
return jsonify(data) | 8b171c838983927b9f5c76beb5c8ea1ed77c53e0 | 3,610,030 |
import logging
import sys
def do_story_eyes(scraper, eyes_tree, mtop=None):
"""
Process the starting page, "story_eyes.php"
Payload allows us to redirect to an older month page,
which we will sometimes need for catching up on the
month transition.
"""
mcap = scraper.get_month_caption(eyes_... | 05645a64d1b07fa67014eb563d68e3b6f8a3e011 | 3,610,031 |
def test_eml_type(mocker):
"""
Given:
- A eml file
When:
- run the ParseEmailFilesV2 script
Then:
- Ensure its was parsed successfully
"""
def executeCommand(name, args=None):
if name == 'getFilePath':
return [
{
'Ty... | 5b5c0b941ab1f163a4642581762f5922ab4a04c2 | 3,610,032 |
def reverse_grammar(pgrammar):
"""reverses the order of the keys appearing in the parsed grammar."""
pgrammar = dict(reversed(list(pgrammar.items())))
return pgrammar | f4f1b6a5e9f8ad062dde6f6322cec771e792bc6d | 3,610,033 |
import itertools
def build_output_table():
"""Build an output table (find output given state and input bit)"""
output = {}
states = [''.join(x) for x in itertools.product('01', repeat=K-1)]
for s in states:
output[s] = []
stream = [int(x) for x in s]
for input in [0, 1]:
# NOTE: inputs arra... | 80f483aa007829ab241bec206414e86aa6a994e2 | 3,610,034 |
def delta_E_to_R_f(delta_E):
"""
Converts from colour-appearance difference to
*CIE 2017 Colour Fidelity Index* (CFI) :math:`R_f` value.
Parameters
----------
delta_E : numeric
Euclidean distance between two colours in *CAM02-UCS* colourspace.
Returns
-------
float
... | 73a5542210e2824f5a6ed4699905368e898a6d51 | 3,610,035 |
import re
import os
def parse_path(path):
"""
Get name and version of the installer
"""
pat = re.compile(r"([\w.]+)-([\w.]+)-Linux-x86_64\.sh$")
fn = os.path.basename(path)
m = pat.match(fn)
name = m.group(1)
version = m.group(2)
return name, version | 23bad22cec9444c0a6f667dd56bd6c7269d6107c | 3,610,036 |
def createRandomParticleList(n, numParticles=10, lower=0, upper=100):
"""
Returns a list of particles with randomly initialized positions.
Parameters:
n (int): Dimesion of the position tuple.
numParticles (int, optional): Number of particles to be initialized in the
list.
lower (float, ... | e7f7b63551aefefa99148722cf85c84b49abb667 | 3,610,037 |
import fileinput
def read_input() -> str:
"""Reads Brainfuck application from file or stdin"""
return "".join(line for line in fileinput.input()) | 7d3b8776cf95a254a414e91ff9e236575ddfc2ea | 3,610,038 |
def A_weighting(frequencies, min_db=-80.0): # pylint: disable=invalid-name
"""Compute the A-weighting of a set of frequencies.
Parameters
----------
frequencies : scalar or np.ndarray [shape=(n,)]
One or more frequencies (in Hz)
min_db : float [scalar] or None
Clip weights below t... | 940d1945a2bee8307d09da69ee8015de0068baf7 | 3,610,039 |
def is_search_in_version(search, version):
"""
Determine if the given version is a valid member of the given version search
text.
"""
search_segments = search.split('.')
seg_count = len(search_segments)
version_segments = version['full'].split('.')
full_version_count = len(version_segmen... | 0a7bc028985d6d18bb4fd1eb745082756be4707f | 3,610,040 |
def parse_live_msg(user, msg, title, game):
"""Turns the bot's <user> <title> etc format into a readable message"""
msg = str(msg)
user = str(user)
word = ""
words = []
r = 0
for i in range(len(msg)):
if msg[i] == "<" or msg[i] == ">":
if r == 1:
if "every... | 07a4269d24df3f69d5ab215c0e9579a3bb691b63 | 3,610,041 |
def accept_mapping(mapping_id):
"""Process a vote.
:param int mapping_id: id of the mapping to be accepted by the admin
"""
mapping, created = current_app.manager.accept_mapping(mapping_id)
if not mapping:
return abort(404, "Missing mapping for ID {}".format(mapping_id))
if created is... | 60cb898ed74e28da1f2c9550a78e5e4b228800b9 | 3,610,042 |
import json
def get_task():
"""
Get a task from the server
A request is a json file with the following fields:
- "annotation_type" which can have the values...
- name
- name_preview
- trim
- trim_preview
- "user_name"
If it is a request from an MTurk iFrame, it ... | 7acc2dcb4a16fae7050a7d52bdf19251879f319b | 3,610,043 |
def xmllint_format(xml):
"""
Pretty-print XML like ``xmllint`` does.
Arguments:
xml (string): Serialized XML
"""
parser = ET.XMLParser(resolve_entities=False, strip_cdata=False, remove_blank_text=True)
document = ET.fromstring(xml, parser)
return ('%s\n%s' % ('<?xml version="1.0" en... | 4a20d18b22c01b04d280085c77bf1362c54cf7a2 | 3,610,044 |
def get_fact_score(extracted_scores,
subj,
obj,
freq_dict,
score_type='FREQ_SCORE'):
"""Return score for a subj, obj pair of entities.
Args:
extracted_scores: A score vector of size E
subj: subj entity id
obj: obj entity id
... | f127b65a6aa18891ddafcd7053b38dda4f831420 | 3,610,045 |
def XCAFDoc_DocumentTool_DGTsLabel(*args):
"""
* Returns sub-label of DocLabel() with tag 4.
:param acces:
:type acces: TDF_Label &
:rtype: TDF_Label
"""
return _XCAFDoc.XCAFDoc_DocumentTool_DGTsLabel(*args) | d5f0860e27ce1afa448330bd514dfbad47a15a0e | 3,610,046 |
def FilterLabels(labels):
"""Filter label strings in label list.
Filter labels (list of strings) with the following conditions,
1. If 'label' has 'key' and 'value' OR 'key' only, then add the label to
filtered label list. (e.g. 'label_key=label_value', 'label_key')
2. If 'label' has an equal sign but no 'val... | 1d9584fdfefa65ae94562a5a225d7727e6df4664 | 3,610,047 |
def get_or_create_account(organization_name, account):
"""
Check if account already exists. If not, create it.
Return a tax account or None.
"""
default_root_type = 'Liability'
root_type = account.get('root_type', default_root_type)
existing_accounts = frappe.get_list('Account',
filters={
'organization': o... | 4fa650b9577b6bf942dfebf8d1a982ceadfcd02a | 3,610,048 |
def cs_by_search_unnamed(filename, alpha_values):
"""Reads in a file for cluster sizes."""
alpha_to_cs = {}
index = 0
with open(filename, mode="r") as file:
for row in file:
if "Cluster sizes:" in row:
if row[-1] == "\n":
row = row[:-1]
... | b898f44a72c4451b5ec100cccbda3b0addfc0ec6 | 3,610,049 |
import os
import django_pdr
def make_query(query_name, *args):
"""
A function used to generate SQL code from SQL templates
saved in the SQL folder.
For more information see django_pdr/sql/README.MD
"""
file_path = os.path.join(
os.path.dirname(django_pdr.__file__),
"sql",
... | ea11275ddc87505aba9e6cec5fbb878ee92bc37f | 3,610,050 |
def get_host_set_arg(kernel_name, arg_index, arg_size, arg_value):
"""Get host code snippet: set a single argument"""
src = get_snippet("snippet/clSetKernelArg.txt")
src = src.replace("KERNEL_NAME", kernel_name)
src = src.replace("ARG_INDEX", str(arg_index))
src = src.replace("ARG_SIZE", arg_size)
... | 1e67651d85cc9433f6d0e5959854127f41eb4abb | 3,610,051 |
def get_multus_cni_value(config):
"""
This function is used to get multus cni value
"""
logger.info("\n Argument List:" + "\n config:" + str(config))
ret = False
sriov_cni = False
flannel_cni = False
weave_cni = False
macvlan_cni = False
num_nets = config.get(consts.KUBERNETES).g... | 3b3ec36f9a11943b440742d6a9f5a9244695e420 | 3,610,052 |
def build_location(request):
"""Build WebSocket location for request."""
location_parts = []
if request.is_https():
location_parts.append(WEB_SOCKET_SECURE_SCHEME)
else:
location_parts.append(WEB_SOCKET_SCHEME)
location_parts.append('://')
host, port = parse_host_header(request)
... | cdff7291577d363ef6c1f36e34fe3a2b22147f5f | 3,610,053 |
def sample_patch(im: np.ndarray,
pos: np.ndarray,
sample_sz: np.ndarray,
output_sz: np.ndarray=None):
"""Sample an image patch.
args:
im: Image
pos: center position of crop
sample_sz: size to crop
output_sz: size to resize to
... | dd85b44239466767cda137f6991880290794df45 | 3,610,054 |
def remove_child_items(item_list):
"""
For a list of filesystem items, remove those items that are duplicates or children of other items
Eg, for remove_child_items['/path/to/some/item/child', '/path/to/another/item', '/path/to/some/item']
returns ['/path/to/another/item', '/path/to/some/item']
I... | 02f92094cb697be40a4c16d90e8ee6b33f965438 | 3,610,055 |
def getNumFiles(dir):
"""
retrieves the number of files in a given directory
"""
return len(getFiles(dir)) | 59180683db915bd02542c7059e59ffec515aec35 | 3,610,056 |
import json
def vapix_session_request(session, url, **kwargs):
"""Return data based on url."""
if API_DISCOVERY_URL in url:
return json.dumps(API_DISCOVERY_RESPONSE)
if BASIC_DEVICE_INFO_URL in url:
return json.dumps(BASIC_DEVICE_INFO_RESPONSE)
if LIGHT_CONTROL_URL in url:
retu... | 53d49713a8c710ba6d486f628e3699249bef9872 | 3,610,057 |
def create_dataset_early_allocated(group, name, size, dtype):
"""
Create an HdF5 dataset, allocating the full space for it at the start of the process.
This can make it faster to write data incrementally from multiple processes.
The dataset is also not pre-filled, saving more time.
Parameters
... | b570bfefa861b07b25ee65753455bcb04e922606 | 3,610,058 |
from typing import Optional
def verify_stack_size(
func: Fn,
stack: Stack,
signature: Optional[Signature] = None,
) -> int:
"""Verifies that the stack contains required number of arguments for function call.
Args:
func: a function.
stack: arguments available for the call.
... | 99f999fec3522cce20979e5e3bc32c4c529a5c33 | 3,610,059 |
import collections
def list_or_starargs(func):
"""This is a decorator to specify that a function either takes iterable input in the form of an iterable or a list of passed arguments.
If other arguments are needed, the function will need to use kwargs.
This passes the list as the first argument."""
def... | 850901ebc6ec463bd31d94927a0afbd6f52e8518 | 3,610,060 |
def isen_nozzle_mass_flow(A_t, p_t, T_t, gamma_var, R, M):
"""
Calculates mass flow through a nozzle which is isentropically expanding
a given flow
Input variables:
A_t : nozzle throat area
gamma_var : ratio of specific heats
p_t : pressure at throat
T_t : temperature at throat
M : Mach num... | d2cb14d099167c4dbca4ce51a67d248bd15a4a88 | 3,610,061 |
def GenerateConfig(context):
"""Generate configuration."""
base_name = context.env['name']
# Properties for the container-based instance.
instance = {
'zone': context.properties['zone'],
'machineType': ZonalComputeUrl(context.env['project'],
context.properties['... | 0be26f630655ca851ff10f81e37c9533ae117a5f | 3,610,062 |
def calc_overturning_stf(ds,grid,doFlip=True):
"""
Only for simple domains, compute meridional overturning streamfunction
Parameters
----------
ds : xarray Dataset from MITgcm output, via
e.g. xmitgcm.open_mdsdataset
must contain 'V' or 'VVELMASS'... | d7d25368268dc16c4603a88a3a11607772f04da4 | 3,610,063 |
from gatenlp.annotation import Annotation
import numbers
def support_annotation_or_set(method):
"""
Decorator to allow a method that normally takes a start and end
offset to take an annotation or annotation set, or any other object that has
"start" and "end" attributes, or a pair of offsets instead.
... | c3719ecd4909dc0da9165a51946649a51f0bbfd4 | 3,610,064 |
def address_dict(obj, prefix='address'):
"""
Creates a dictionary for the address fields with the given prefix
to be used as nested object.
"""
if obj is None:
return None
mapping = {
'line_1': _attrgetter_with_default(f'{prefix}_1', ''),
'line_2': _attrgetter_with_defau... | de39502b2bb4aab66113c848f457785e35082fed | 3,610,065 |
def Message_MsgFile_Msg(*args):
"""
:param key:
:type key: char *
:rtype: TCollection_ExtendedString
* Gives the text for the message identified by the keyword <key> If there are no messages with such keyword defined, the error message is returned. In that case reference to static string is returned,... | da117a1e86ef036c0769bc73c5a27a3a433dab9f | 3,610,066 |
def register_user(email, name, password, password2, balance):
"""
Register the user to the database
:param email: the email of the user
:param name: the name of the user
:param password: the password of user
:param password2: another password input to make sure the input is correct
:return: ... | 0b3476ce1583d31417ff4728283d7eb662277005 | 3,610,067 |
def VerifyManagementEngineLocked(options):
"""Verify Management Engine is locked."""
return GetGooftool(options).VerifyManagementEngineLocked() | 5491f721f8c86012ec5c42f0be71b8121f8b4c21 | 3,610,068 |
def compile(msg):
"""Compile an OpenFlow message template."""
controller = Controller.singleton()
if isinstance(msg, str):
return CompiledString(controller, msg)
if 'type' in msg:
return CompiledObject(controller, msg)
return CompiledObjectRPC(controller, msg) | 89c6c4696ff68b23c2db54c1c203294d8bd39819 | 3,610,069 |
import dateutil
import os
def datetime_from_filename(filename):
"""Create Python datetime object from bag file name.
:param: base name of bag file.
:type: str
:returns: corresponding Python datetime.datetime object.
:note: This implementation assumes the base file name has a
four-ch... | b0fb61b7f90280ea116b4f8f4d58eb9b4d2c3133 | 3,610,070 |
import datasets
def load_data(train=True, batch_size=50, shuffle=False):
"""
加载数据集
:param train: 训练集 or 测试集
:param batch_size: batch的大小
:return: 返回加载好的Dataloader
"""
if train:
# 针对训练数据随机打乱
shuffle = True
# 加载CIFAR10数据集,若不存在则下载
dataset = datasets.CIFAR10('./data',
... | d39c9c5e69ef5c444b268d0dfc4b7d0625abb182 | 3,610,071 |
def route_filter_create_or_update(name, resource_group, **kwargs):
"""
.. versionadded:: 2019.2.0
Create or update a route filter within a specified resource group.
:param name: The name of the route filter to create.
:param resource_group: The resource group name assigned to the
route fi... | 2856d9f82ba03864b071adb265651dd5b7f44492 | 3,610,072 |
def get_featured_dashboard(slug):
"""
Grab a dashboard of featured things.
{% get_featured_dashboard 'homepage' as featured_stuff %}
"""
try:
return Dashboard.objects.get(slug=slug)
except Dashboard.DoesNotExist:
msg = "Dashboard `{}` probably doesn't exist.".format(slug)
... | 36f453ec8b6da8eda477b7d3a1861b293eea6987 | 3,610,073 |
from typing import Any
from typing import Type
def value_to_member(value: Any, cls: Type[Any]) -> str:
"""
Get a member of a class that matches the value given
"""
members = get_class_members(cls)
for member in members:
if getattr(cls, member) == value:
return member
retu... | 48cee85d502bc67ed27f215b89e13581dc9da670 | 3,610,074 |
from typing import Tuple
def adaptive_rejection_sampling(logpdf: callable,
a: float, b: float,
domain: Tuple[float, float],
n_samples: int,
seed=None):
"""
Adaptive rejection samplin... | 1c8ddf223894700a31612687572a65a9bf06f90a | 3,610,075 |
from re import X
def player(board):
"""
Returns player who has the next turn on a board.
"""
flattened = [inner for outer in board for inner in outer]
return O if flattened.count(X) > flattened.count(O) else X | ed406a2ac6dcdf2f544c5b83e9b7d1ddf00a6344 | 3,610,076 |
def viterbi(nodes,trans_p, initial_state = None, return_max = True, start_p = None):
"""
nodes: array, [{"<TAG>": <float>}]
trans_p: dict, {"<TAG_A>": {"TAG_B": <float>}}, TAG_A -> TAG-B
return_max=True: bool, set to False if your want to avoid ill endding tag and find your own.
initial_state=None: ... | 4688b6029a6a68a8680017ae87d4cc0593e58814 | 3,610,077 |
import astropy.time
import pyia
def get_gaia_radec_at_time(gaia_tbl, date=2015.5, format='decimalyear'):
"""
Use `~astropy.coordinates.SkyCoord.apply_space_motion` to compute GAIA positions at a specific observation date
Parameters
----------
gaia_tbl : `~astropy.table.Table`
GAIA tab... | fb9b46f37d8ee0232c9a6180e554fa91d38c7bfc | 3,610,078 |
def dissociate(op, args):
"""Given an associative op, return a flattened list result such
that Expr(op, *result) means the same as Expr(op, *args)."""
result = []
def collect(subargs):
for arg in subargs:
if arg.op == op: collect(arg.args)
else: result.append(arg)
col... | e86d833d31a272078188734932be8d598c821f8d | 3,610,079 |
from typing import List
def ways_to_fill(amount: int, containers: List[int]) -> int:
"""The number of ways to pour amount of liquid into containers.
All containers used must be filled up entirely."""
if amount == 0:
# Reached an acceptable configuration.
return 1
if amount < 0 or not ... | 098a4b22d29f9527dfcf04d48e2f58784903101d | 3,610,080 |
def AggregateData(data,period):
"""Create a clean dataset
Arguments:
- data -- np.array of np.float64, size (N,6)
data[:,0] is unix times (seconds), start of the interval
data[:,1] is close price, dollars
data[:,2] is high price, dollars
data[:,3] is low price, dollars
data[:,... | 7f4fade2de87fbf110716a12c1174881b275b7f3 | 3,610,081 |
def get_tolerance(camera=None,
legacyzpts_product=None):
"""Returns dict giving maximum 'plus/minus' difference for each numeric column
Note, dont fill in if differnce should be zero, that's default
Args:
camera: CAMERAS
legacyzpts_product: legacypipe,zpt,star-photom,star... | 7d087bc4733abc0a114f77e28160999670c68320 | 3,610,082 |
def kspace_setup(box_lengths, angle_averaging, max_k_harmonics, max_aa_harmonics):
"""
Calculate all allowed :math:`k` vectors.
Parameters
----------
max_k_harmonics : numpy.ndarray
Number of harmonics in each direction.
box_lengths : numpy.ndarray
Length of each box's side.
... | eb327b2c3ac8fa5b4d631c9b1053b06b1298ced0 | 3,610,083 |
def predict_transport_mode(triplegs, method="simple-coarse", **kwargs):
"""
Predict the transport mode of triplegs.
Predict/impute the transport mode that was likely chosen to cover the given
tripleg, e.g., car, bicycle, or walk.
Parameters
----------
triplegs: GeoDataFrame (as trackintel ... | 385bdac5b5e2dbbd6219670c084d4df7e45e153f | 3,610,084 |
def get_site_name():
""" Retuns site's name """
domain = getattr(settings, 'SITE_NAME')
return domain | 6bf1ae1a997dbfbb6707f1c49c6c957988faf014 | 3,610,085 |
from typing import List
def execute_adaptive_model(model: AdaptiveModel, dataset: Dataset, series: DataSeries) -> ModelResults:
"""
Executes the neural network on the given data series. We do this in a separate step
to avoid recomputing for multiple budgets. Executing the neural network is relatively expe... | e9e4adb2f6998af6442cef28a68ea90328f53793 | 3,610,086 |
def split_tensor_lastdim(ten):
"""Split last dimension into two tensors."""
# TODO(vrama): Generalize this to other splits than 2.
assert ten.get_shape().as_list()[-1] % 2 == 0, ('Last dimension'
'must be divisible by 2.')
ten1, ten2 = tf.split(ten, 2, axis=len(... | 33651509089a7fbf167163e1d0f135f50e57cbd7 | 3,610,087 |
def finite_diff_hessian(x, grad, epsilon=FINITE_DIFF_EPSILON):
""" Approximate the Hessian of a function using finite difference in the partial gradient.
:param np.ndarray x: point at which to evaluate derivative
:param function grad: function that returns the gradient
"""
fwd_x = np.copy(x)
bwd... | d3b2c4e7cb064733d623def8f762751e7ecf3b07 | 3,610,088 |
def value_at_diviner_channels(xarr):
"""Return value of xarr at each diviner channel."""
dwls = [
3,
7.8,
8.25,
8.55,
(13 + 23) / 2,
(25 + 41) / 2,
(50 + 100) / 2,
(100 + 400) / 2,
] # [microns]
return xarr.interp({"wavelength": dwls}) | 4897ed8250e2f02409205c02a26d63cfafb50a52 | 3,610,089 |
def to_str(obj):
""" Convert something to a string, if it isn't one. """
# NOTE: unicode counts as a string just fine. We just want objects to call
# their __str__ methods.
if not isinstance(obj, basestring):
obj = str(obj)
return obj | 576ad8bf6c8b165d7b43fec39f8b6fbb6a03fb9a | 3,610,090 |
def get_field(addr: gdb.Value, n: int) -> gdb.Value:
"""
This assumes addr is a pointer to a struct that consists entirely
of pointers. Returns the n-th pointer in the struct.
"""
return gdb.parse_and_eval(f"((uintptr_t*){addr})[{n}]") | 88824800bb4a58b3d9072ce7176828157c6d77c8 | 3,610,091 |
def validate_rdkit(mol):
"""
Validates RDKit molecules (single or in a list).
:param mol: an RDKit molecule or list/np.array thereof
:return: boolean array, True if the molecules are chemically valid, False
otherwise
"""
if rdc is None:
raise ImportError('`validate_rdkit` requires ... | b1396c42e7fc753d5ef77b05513a984909f0715b | 3,610,092 |
import ephem
def setup(hass, config):
""" Tracks the state of the sun. """
logger = logging.getLogger(__name__)
if not validate_config(config,
{ha.DOMAIN: [CONF_LATITUDE, CONF_LONGITUDE]},
logger):
return False
try:
except ImportError... | 1d1f1419aa350f41bdd10093df8d8e34b6f3d28c | 3,610,093 |
def generate_graph_for_path_search(edges, transactions, amount_sat):
"""Generate pseudo edges and generate graph for path search."""
targets = list(transactions["target"].unique())
#sources = list(transactions["source"].unique())
#participants = set(sources).union(set(targets))
# drop edges with low... | 852205c11d023f271887d9218d4b461f6bebf7c6 | 3,610,094 |
def point_nonmatch_count(dist_array: np.ndarray, thresh: float = 5) -> int:
"""Given an array of distances, returns number which are not <= threshold."""
return dist_array.shape[0] - point_match_count(dist_array, thresh) | 5eba611bda3e6611dc997afd39b2d103c3163580 | 3,610,095 |
from typing import Optional
from typing import Callable
from typing import Literal
def prune_source_literals(
plan: Plan, *, inplace: bool, predicate: Optional[Callable[[Literal], bool]] = None
) -> Plan:
"""
Prunes source literals. When predicate is present, the literal will only be pruned if it returns ... | 65a9a52503d12c82bf563d042d16c6872d811d40 | 3,610,096 |
def isodatesec(text):
"""Date. Returns the date in ISO 8601 format, including
seconds: "2009-08-18 13:00:13 +0200". See also the rfc3339date
filter.
"""
return util.datestr(text, '%Y-%m-%d %H:%M:%S %1%2') | 7a840f8c558b227a4d9f8e3ded52d83dab41c2e5 | 3,610,097 |
def pull_docker_image(docker_client, url):
""" Pull Docker image
Args:
docker_client (:obj:`docker.client.DockerClient`): Docker client
url (:obj:`str`): URL for Docker image
Returns:
:obj:`docker.models.images.Image`: Docker image
"""
try:
return docker_client.imag... | ea70b6ec2ce97cf0f3806dc2364a001fa8187c55 | 3,610,098 |
def NTPasswordHash(password):
""" Return NTPasswordHash """
phash = MD4.new()
phash.update(unicode(password).encode("utf-16le"))
return phash.digest() | 025c31775fe90893506282e46de771c71555c4de | 3,610,099 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.