content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def summary_of_datasets_by_user(username):
"""Return summary information of datasets the user has access to.
Return dictionary of summary information.
Raises AuthenticationError if user is invalid.
"""
# Get all the datasets the user has access to.
datasets = search_datasets_by_user(username, ... | 9e69e5bef72e37659b0fb45476f4004bdb4e7c30 | 72,800 |
def get_urls(metainfo):
"""
Return a mapping of Package URLs and a mapping of other URLs collected from
metainfo.
"""
# Misc URLs to possibly track
# Project-URL: Release notes
# Project-URL: Release Notes
# Project-URL: Changelog
# Project-URL: Changes
#
# Project-URL: Furth... | 61135497fd62e1b9610ed3957611c38bb497cfc5 | 72,801 |
def simplevolume(flist, distances, voxel, g):
"""estimate the volume by the fraction of interior points"""
res = options.ics_partial_volume_resolution
distance_threshold = options.ics_distance_threshold
sx, sy, sz = g["dx"] / res, g["dy"] / res, g["dz"] / res
res1 = res + 1
# count up... | 8623754e3d5bad7a4bff9c7a4e814b2b34648b07 | 72,802 |
import collections
def expand_realms(db, project_id, realms_cfg):
"""Expands realms_config_pb2.RealmsCfg into a flat realms_pb2.Realms.
The returned realms_pb2.Realms contains realms and permissions of a single
project only. Permissions not mentioned in the project's realms are omitted.
All realms_pb2.Permis... | 68ee2027d1c848386162ca68bd39a5e623b80041 | 72,803 |
import base64
from datetime import datetime
import os
def send_message_in_group_chat(request, chat_name_slug):
"""Iserts message into db(ONLY FOR GROUPCHATS)"""
current_user = TLAccount.objects.get(id=request.user.id)
message = request.POST.get("message_body", "")
group_chat = GroupChat.objects.get(s... | 0861bfb42d89a633618489365b2840e4b8d78522 | 72,804 |
def _vm_replica_cb_detail(repname, action, jsons, key_json_idx=None):
"""Create tasklog detail"""
res = {'repname': repname}
if not jsons:
return res
for out in jsons:
if 'msg' in out:
res['msg'] = out['msg']
res['rc'] = out['rc']
if key_json_idx is None:
... | 083a2c96563d173a1cca2f2ad26e0e44875afb1e | 72,805 |
def create_test_bot(config_settings: dict,
chatbot_engine_name: str = "") -> ChatbotEngine:
"""Create a bot for testing."""
if not config_settings:
config_settings = load_configuration(get_configuration_path(),
"BBOT_ENV", "testing")
r... | 257b1cb51d23e4f5cc60be146270b21053417c2b | 72,806 |
def coref_cleaning(t, new_coref_np, current_coref):
"""Assign the correct coreference tag according to
Args: t (token), new_coref_np (Boolean), current_coref (int)
Return: new_coref_np (Boolean), current_coref (int)
"""
if t.coref.startswith('(') and t.coref.endswith(')')... | 9e2d1db3316c6ddd2c09050b64838cc92d5dd651 | 72,807 |
def topsort(order):
"""Given a binary array defining a partial order (o[i,j]==True means i<j),
compute a topological sort. This is a quick and dirty implementation
that works for up to a few thousand elements."""
n = len(order)
visited = np.zeros(n)
L = []
def visit(k):
if visited[k... | 2b09b5589655e7e3391c9802d993cd565061a4b8 | 72,808 |
def bipartite_modularity(B,m,R,T,CO):
"""Computation of the bipartite modularity as described in ""Modularity and community detection in bipartite networks" by Michael J. Barber." """
RtBT = R.transpose().dot(B.dot(T))
Qcoms = (1/m)*(np.diagonal(RtBT))
Q = sum(Qcoms)
Qcoms = Qcoms[Qcoms>0]
CO[... | cc5aac25c51136511af693bd54978f83ee9a9707 | 72,809 |
def calculate_interval(s):
"""
Expand intervals expressed as nI, where I is one of:
s: seconds
m: minutes
h: hours
d: days (24 hours)
w: weeks (7 days)
"""
m = INTERVAL_RE.search(s)
if not m:
raise InvalidInterval("No match: %s" % s)
n = int(m.... | 10c4ccac0e09e1d23de7486b8dc30b459ff9a1f6 | 72,810 |
def get_default_tokenizer():
"""Only support split tokenizer
"""
def _split_tokenizer(x, delimiter=None):
if delimiter == "":
return list(x)
return x.split(delimiter)
return _split_tokenizer | 91cc23378d230d9cb47fbe0c47cf7a33cbce5265 | 72,811 |
def admin_guard(f):
"""
Middleware (guard): checks if the current authorized user is election
officer or not.
"""
@wraps(f)
def decorated_function(*args, **kwargs):
if 'eid' not in kwargs.keys() or F.g.user.username \
not in meta.Election(kwargs['eid']).get()['election_of... | e5d5fce9c5b2a0d2197c78f50d54f5d75e4cf7cc | 72,812 |
import sys
def compute_min_distance(c1s, relation, c2s):
""" """
# Cover first a couple of base cases to enhance performance
if c1s & c2s:
return 0
if not c1s or not c2s or not relation:
return sys.maxsize
# index the adjacency relation
adjacencies = defaultdict(list)
for... | b8a4eb1be0f4dd62f2eaafffd33202d6b4f90473 | 72,813 |
def prt_or_rsl(damage_type: str, prt: int, rsl: int) -> int:
"""
Depending on the given damage type, returns Prt or Rsl respectively,
whichever is more appropriate
:param damage_type: The DamageType being dealt
:param prt: a unit's Prt
:param rsl: a unit's Rsl
:return: whichever of Prt and R... | ee74909d887a58b7f5c7817992663b46737a3d82 | 72,814 |
from typing import Optional
def paginate(
items_query: Select,
count_query: Select,
page: int,
per_page: int,
*,
scalar_result: bool = False,
unique_result: bool = False,
item_mapper: Optional[Mapper] = None,
) -> Pagination:
"""Return `per_page` items from page `page`."""
if p... | 8a3c1ad51c5ab7be5f790662330bf64098593a83 | 72,815 |
from ubinascii import hexlify
def get_upp_payload(upp: bytes) -> bytes:
"""
Get the payload of a Ubirch Protocol Message
:param upp: received UPP
:return: payload of the UPP
"""
if upp[0] == 0x95 and upp[1] == 0x22: # signed UPP
payload_start_idx = 23
elif upp[0] == 0x96 and upp[1... | d645f584c4650c055202760cbb9f1d3795f9e5cc | 72,816 |
def _lineage_ngs_define(seq, proto):
""" Given local sequence and protospacer sequence, define a local region of indel/SNV analysis.
Determines 20bp flanking sequences to the left and right of cut site.
Helper function of lineage_ngs_dict2csv().
:param seq: local genomic sequence
:param prot... | 314c4909bba78b78848db9f6c2d710b960bcbeaf | 72,817 |
def servers_element(settingsXml):
"""Get or create the <servers> element from the passed "settings.xml"."""
try:
serversElement = firstElement(settingsXml, '/{%(ns)s}servers')
except IndexError:
serversElement = etree.Element('servers')
settingsXml.getroot().append(serversElement)
... | 5151dff14b50bc58353c1e97a9a08c4b1f70ceb0 | 72,818 |
def index(request):
"""
View function for home page.
"""
return render(
request,
'index.html',
context={},
) | 67bd739eb23b0930f25b2956c006dcbfd2e0d3bd | 72,819 |
def grant_user(cursor, **userArgs):
"""
Grant the "user" role to a user
Parameters:
-----------
cursor: Psycopg2 cursor
Cursor of type RealDict in the postgres database
userArgs: Dict
dictionary with the different element:
username: Str
name of the user
... | 6b37258ab78d239c7f54425c3967303ba61f48bb | 72,820 |
def ReadSAMnoMem(ref, art, output, compareList, readdic, rankdic,phredoffset):
"""
Main function for comparing to mappings. This functions takes the complete alignments for artificial and reference genome and goes through them in parallel.
Since the mappings are sorted the function alternates the parsing of... | 6aba18586a54d4a514b8fd515ec2a5b629fea708 | 72,821 |
def crext_ExtendedMasterSecret():
"""Create an Extended Master Secret extension"""
return ExtensionType.extended_master_secret.value + lenprefix(b"") | 0ac971c78328637043df54cd8660f79ae5840bd0 | 72,822 |
import uuid
import random
def set_facility_code(facility_id):
"""
Generate and set a unique facility code
Args:
facility_id: the facility ID
Returns:
the facility code
"""
db = current.db
s3db = current.s3db
table = s3db.org_facility
query = ... | ec432fb0620ed92557c3f2a1f06ea15dce9f9820 | 72,823 |
import json
def load_dict_from_json(filename: str) -> dict:
"""
Load the given file as a python `dict`
Parameters
----------
filename: `str` an absolute path to the json file to be loaded.
Returns
-------
`dict` The loaded json file as a python dictionary.
"""
with open(filen... | 1d55e5dbcf33e7f1d21063be7b722a5ed5bc6bb3 | 72,824 |
import random
import string
def metadata(time, shape_type=None, coords=None, attributes=None):
"""
Create single VIA metadata record.
:param time: time in seconds
:param shape_type: see VIA_RSHAPE
:param coords: RECTANGLE: [x,y,w,h], LINE: [x1,y1,x2,y2], ...
:param attributes: {attribute id: ... | 85bf0bcec544baf7fff6ced20c46a62806d5f601 | 72,825 |
def create_test_function(
test_file_loc,
tested_function,
test_name,
regen=REGEN_TEST_FIXTURES,
):
"""
Return a test function closed on test arguments to run
`tested_function(test_file_loc)`.
"""
def test_proper(self):
test_loc = self.get_test_loc(test_file_loc, must_exist=T... | b4cb7eb723daa4451315e9770a2470b8ccd8902b | 72,826 |
def _Run(args, version):
"""Deploy a model to an existing Vertex AI endpoint."""
validation.ValidateDisplayName(args.display_name)
if version != constants.GA_VERSION:
validation.ValidateAutoscalingMetricSpecs(args.autoscaling_metric_specs)
endpoint_ref = args.CONCEPTS.endpoint.Parse()
args.region = endpo... | b655027d1020b01600c6160f73c76ba85dedb470 | 72,827 |
def user_group_required(*required_groups):
"""
Decorate a view function to check if user belongs to one of the groups passed as an arguments.
Can decorate a simple view function as well as dispatch method of generic view class.
"""
def wrapper(func):
def wrapped_function(*args, **kwargs):
... | fe0f0bbf75279233f4b96a3ae156b2fa666e9803 | 72,828 |
import json
def edit_notes_simple(*args):
"""
Render a list of Notes as simply as possible
Still tries to exercise the same codepaths as a normal endpoint, though.
"""
def render_n2_desc(n: Note):
return n.desc
def render_n2_json(n: Note) -> str:
return escape(json.dumps(n.as... | 45b3d51d52208929672ba1b52b7d15b5e0562a9f | 72,829 |
import shutil
def prepare_empty_dirs(dirs: list):
"""
建立空目录。若已经存在,则删除后创建。
parents=True
Args:
dirs: Path list
Returns:
dirs 中各个目录的句柄
"""
result = []
for d in dirs:
if d.exists():
shutil.rmtree(d.as_posix())
d.mkdir(parents=True, exist_ok=Fal... | a672542576ea7eeff8b99aa43d223cfe48069ecc | 72,830 |
import os
import configparser
def check_config(configfile):
"""check if config is ok"""
if os.path.isfile(configfile):
config = configparser.ConfigParser()
config.read(configfile)
listeSeries = update_liste(config)
else:
print ("n... | 7d55447a70d2d5e0ae463f25e46d405ae64be4ad | 72,831 |
def collect_not_null_kwargs(**kwargs) -> dict:
"""
Collect not null key value pair from keyword arguments.
.. versionadded:: 1.0.1
"""
return {
k: v
for k, v in kwargs.items()
if v is not None
} | 84e3438b5a4f0a48a4b558cc50b65a21e5883af9 | 72,832 |
def get_axislabels(fluor="dff", area=False, scale=False, datatype="roi",
x_ax=None, y_ax=None):
"""
get_axislabels()
Returns appropriate labels for x and y axes.
If y_ax is None, y axis is assumed to be fluorescence, and label is
inferred from fluor and dff parameters. If... | 5d95cae0846235451adb125a7773bc83652c64e1 | 72,833 |
def remove_duplicate_candidate_view(request):
"""
We use this view to semi-automate the process of finding candidate duplicates. Exact
copies can be deleted automatically, and similar entries can be manually reviewed and deleted.
:param request:
:return:
"""
authority_required = {'admin'} #... | f567f31213fd025a48783f2ee6a86676e2ecbcdf | 72,834 |
def multiple_data_analysis(model_location, data_locations,
**kwargs):
"""Run model analysis for a single model on multiple data sets.
Args:
model_location: The location of the exported eval saved model.
data_locations: A list of data set locations.
**kwargs: The args used for... | a6c1004c9073549102f30b47cbb31207c3387f53 | 72,835 |
def terminate_instance():
"""
Terminate an instance.
@return: Response.
"""
helpers.require_parameters(['InstanceId.1'])
instance_id = helpers.get('InstanceId.1')
previous_state = describe_instance_by_id(instance_id)
new_state = _terminate_instance_request(instance_id)
return _modif... | 1e28248c2efb7c21f9bc0b3abb32d4405958b780 | 72,836 |
def get_n_neighborhood_start_stop_indices_3D(volume_shape, point, n):
"""
Compute the start and stop indices along the 3 dimensions for the n-neighborhood of the point within the 3D volume.
Note that this returns an index range where the end is *non-inclusive*! So for a point at x,y,z with 0-neighborhood (... | 6eb1c6f0b4ff537b3d0eb1b647b019a2d61480b7 | 72,837 |
def find_declaration(
declarations,
decl_type=None,
name=None,
parent=None,
recursive=True,
fullname=None):
"""
Returns single declaration that match criteria, defined by developer.
If more the one declaration was found None will be returned.
For more inf... | a3e534029a38e3547756790ab7703507a835f90a | 72,838 |
from typing import Dict
from typing import Any
def add_to_dict_with_swapped_keys(old_dict: Dict[Any, Dict],
new_dict: Dict[Any, Dict]) -> Dict[Any, Dict]:
"""
Swap the keys of two nested dictionaries in a new dictionary.
{'Key1': {'Key2': 42}} -> {'Key2': {'Key1': 42}}
... | 2b4d0a0d8bd2734d8c0bc7abde1fa659454f1464 | 72,839 |
def wet_bulb_globe_temperature_BoM(base):
"""Calculate Wet Bulb Globe Temperature approximations.
Parameters
----------
base : dict of array_like
dict containing CMIP-style variables, which should contain the following
keys:
tas : near-surface air temperature... | 7c384dd4bbab659b7a2bda6a3ffea98957212590 | 72,840 |
import os
def splitpath(full_path):
"""
Splits a path into all possible pieces (vs. just head/tail).
"""
head, tail = os.path.split(full_path)
result = [tail]
while len(head) > 0:
[head, tail] = os.path.split(head)
result.append(tail)
result = [x for x in result if len(x)]
return result[::-... | 427a9de5772459504026d235e5e9ff59259a5c80 | 72,841 |
import typing
import functools
def build_simple_validator(func: typing.Callable, *args, **kwargs) -> typing.Callable[[typing.Any], typing.Any]:
"""Build a ready-to-use simple validator out of a function.
Args:
- func: callable, the function to be called to validate an input
- args: list, args... | cc8227cce228579e51aa05ceb25d9020d51eb199 | 72,842 |
import os
def _ResolvePath(included_from, included_path, basepath):
"""Gets the absolute path of the file to be included.
Resolves in the following order:
- absolute path or relative to working directory
(path as specified resolves to a file)
- relative to basepath
(basepath + path resolves to a file... | b9482c32ff5364ec562ff278e72f8c1018285865 | 72,843 |
from typing import Optional
def assign(new_value: NodeInput, variable_id: str, name: Optional[str] = None) -> Node:
"""Return a node which produces the Assign operation.
@param new_value: Node producing a value to be assigned to a variable.
@param variable_id: Id of a variable to be updated.
@par... | 9b641c32a8d0ed88eb8666e088f6a7b37b39e083 | 72,844 |
def is_scipy_stats_cont(arg, scipy_stats_cont=SCIPY_STATS_CONT):
""" Returns if arg belongs to scipy.stats.continuous """
return isinstance(arg, tuple(scipy_stats_cont)) | cc3001ce242f87072e6ec9014b64c7fa02a75dbd | 72,845 |
from datetime import datetime
import os
import csv
def prepData(inputFileName, category, comment):
"""
Description: prepates data to submit
Input: inputFileName - input file containing IPs, one per line (string)
category - IP submission category (string)
... | cebe0be1449ea14320cf995f1aaf813c9f6231ec | 72,846 |
def oph_to_gal():
""" Compute the transformation from heliocentric Ophiuchus coordinates to
spherical Galactic.
"""
return matrix_transpose(gal_to_oph()) | 387b1f27c1e0ebdfc4cff5573e58f246a68f25aa | 72,847 |
import torch
def NMTCriterion(vocabSize, opt):
"""
Construct the standard NMT Criterion
"""
weight = torch.ones(vocabSize)
weight[constants.PAD] = 0
crit = nn.NLLLoss(weight, size_average=False)
#crit = nn.NLLLoss(size_average=False, ignore_index=onmt.Constants.PAD)
if opt.gpus:
... | 2550cc0579800e02c3bdcf27bd0599dca3d7576d | 72,848 |
import torch
def quat_conjugate(a: torch.Tensor) -> torch.Tensor:
"""Computes the conjugate of a quaternion.
Args:
a: quaternion to compute conjugate of, shape (N, 4)
Returns:
Conjugated `a`, shape (N, 4)
"""
shape = a.shape
a = a.reshape(-1, 4)
return torch.cat((-a[:, :3... | 530eb2a8d8b9b87de2bfcaeb48729704908131cc | 72,849 |
def insert_audio_clip(background, audio_clip, previous_segments):
"""
Insert a new audio segment over the background noise at a random time step, making sure that the
audio segment does not overlap with existing segments.
Arguments:
background -- a 10 second background audio recording.
a... | 42253d611f32418085f1ac13299d9ba0c59e3f4b | 72,850 |
def image_example(img_string, mask_string):
"""Returns tf.Example containing image and mask as byteslist
Args:
img_string: bytes string of image
mask_string: bytes string of mask
Returns:
tf.train.Example which will be serialized and written to tfrecord
"""
feature = {... | 8c23bf03591598695314edd4d0def5a4e59e5efb | 72,851 |
import re
def feed_db(path_file):
""" Read file and put all category in mongo db """
cat_list = open_category_file(path_file)
if not cat_list:
return False
category = None
words = []
for line in cat_list:
if "category" in line:
result = re.match("<category: (.+)>"... | 7f6ac355a3254d523b5525df3908520927b0c54e | 72,852 |
import re
import uuid
def add_new_mol(rdmol, target):
"""Function to add a new bound Molecule object
Takes an RDKit molecule and a Target
Returns None"""
new_mol = Molecule()
rdProps = rdmol.GetProp("_Name").split("_")
comp_ref = add_new_comp(rdmol)
if comp_ref is None:
return None... | 750e78ba56a2cc967b205f72a6cb315a9c5df71d | 72,853 |
def compute_dominant_color(image, n_clusters=3, max_iter=10, threshold_error=1.0, attempts=10):
"""
Compute the dominant color of an input image using the kmeans clustering. The centers of the
clusters are the dominant colors of the input image
:param image: input image. Either a multi-channel color im... | 85c386487115398e2bebb3b57f19486ab39f3ee7 | 72,854 |
def createUnits(version):
"""Create a dictionary with units."""
try:
units = Units(codata[version])
except KeyError:
raise NotImplementedError("Codata {0} not found".format(version))
# Define all units
# permittivity of vacuum
units["_eps0"] = 1 / units["_mu0"] / units["_c"] **... | 56583dd1470b523d3655c041ef93dc5f960c91ab | 72,855 |
def low_cut_filter(x, fs, cutoff=70):
""" Low-cut filter
Args:
x (ndarray): Waveform sequence
fs (int): Sampling frequency
cutoff (float): Cutoff frequency of low cut filter
Return:
(ndarray): Low cut filtered waveform sequence
"""
nyquist = fs // 2
norm_cutoff = ... | 0ece15d02adaa39a0c85b2efe854b83afd67194a | 72,856 |
def interpret_model(
X,
model,
interpreter=RIPPER(),
model_predict_function=None,
score_function=score_accuracy,
):
"""Interpret another model.
Parameters
----------
model :
trained classifier, e.g. sklearn, keras, pytorch, etc.
X : DataFrame, numpy a... | 93a78e6ff8c8e446e1f567a7b5a0dcc78b8ac02f | 72,857 |
def week_from_start(in_path, col, identifier):
"""
Description:\n
Calculate the number of weeks for each logging since the first day of the logging for each participant(identifier). The returned values for loggings from the first week are 1.
Input:\n
- in_path (str, panda... | 983b2bd618306eb466df0dc952530ec4b7a4a8f4 | 72,858 |
def get_job_instance_states(username, m_wf_id, wf_id, job_id, job_instance_id):
"""
Returns a collection of Job States.
:query int start-index: Return results starting from record <start-index> (0 indexed)
:query int max-results: Return a maximum of <max-results> records
:query string query: Search... | 80ad0b9d835ef863aba7d6b4391d5bebea576bc8 | 72,859 |
import statistics
def extract_chords_for_melodies(quantized_sequence, melodies):
"""Extracts a chord progression from the quantized NoteSequence for melodies.
This function will extract the underlying chord progression (encoded as text
annotations) from `quantized_sequence` for each monophonic melody in
`mel... | 40beafe48c224651d18ba8700b1bae526400f5d6 | 72,860 |
import subprocess
import re
def lookup_manpage_section(name: str) -> int:
"""
uses `man -w <name>` to look up the path of the man page,
then from that parses the path to get the section
number.
If not found, defaults to 1.
>>> lookup_manpage_section("ping")
8
>>> lookup_manpage_sectio... | 2c56da60479c1f2cfc01d692ac4747443d152fd5 | 72,861 |
def readSSHORT(stream):
"""
Read short signed integer
:type stream: FileIO or ByteIO
:param stream: Where to read from
:return: result
:rtype: int
"""
return _read_struct(stream, S_SSHORT)[0] | 94bce8ee3cbd8d488b8d3e994959894559c4f6e8 | 72,862 |
def send_to_left_side(targets, values):
"""Send the given target values to the left of all other values.
Example:
targets = ["b", "x","c"]
values = ["a", "b", "c", "x", "y", "z"]
send_to_left_side(targets, values) # -> ["b", "x", "c", "a", "y", "z"]
Args:
targets: Values to send t... | c19f5476e1c0294595aafb7647c418b0e63f8f0e | 72,863 |
def padding(sound_stft):
"""Apply reflection padding to ensure that number of time frames of
`sound`'s STFT representation is multiple of 64.
Args:
sound_stft (torch.Tensor): Spectrogram to be padded.
Returns:
Tuple[torch.Tensor, Tuple[int, int]]: Reflection padded spectrogram and
... | ff7134764ded3b83f7ecd93c0077fe243b4e171b | 72,864 |
import random
def generate_id():
"""Generates a new unique id for new user"""
id_s = connect_to_sql("select unique_id from user_data")
while True:
new_id = random.randint(100000, 999999)
if new_id not in id_s:
return new_id | 10adcbf2f16ed58baf2de493d4e040f6fb8e06eb | 72,865 |
import subprocess
import sys
import os
import tqdm
import re
def build_index(use_bag=False, careful=False, expt_dir_list=None):
"""
An experiment is a collection of outputNNN directories. Each directory
represents the output of a single job submission script. These directories
are created by the *pay... | 6fc2b24c9c2d9271e6859500a635e0d7c43f48d4 | 72,866 |
import os
def get_params_path():
"""Get path to Jinja templates."""
# THIS IS HACK... need a better method
path = "params"
base_path = os.path.dirname(os.path.abspath(__file__))
return os.path.join(base_path, path) | 2e3090f9fb456e0df5402f2bf3a171a277c79b6f | 72,867 |
import struct
def discard_blanks(data):
"""Remove blank spaces from the data file"""
pos = 0
for i_char in data:
char = struct.unpack('s', data[pos:pos + 1])[0].decode()
if char not in ["*", " "]:
break
else:
pos += 1
return data[pos:] | aff090ab188bffd6bca86eb3b861d25a0440dbcc | 72,868 |
def matches(text):
"""
Return the list of keyword matches in text
"""
matches = []
for rgx in compiledRegexes:
found = rgx.findall(text)
matches.append((rgx.pattern, len(found)))
return matches | 334f5739f946f3c9f545a2bc4ffb9c05940f0ea6 | 72,869 |
def set_amplifier_mode(
con_handle: ConnectionHandler,
slot_id: str,
channel_index: int,
amplifier_mode: str | int,
) -> str:
"""Set the amplifier mode for an analog channel.
The system needs to be idle before calling this function.
If the specified amplifier mode is not supported by the... | c234814b3c96664e90414bf023fe4f450cab630f | 72,870 |
def get_saliency_maps_for_class_activation(
model_object, target_class, list_of_input_matrices):
"""For each input example, creates saliency map for prob of target class.
:param model_object: Instance of `keras.models.Model`.
:param target_class: Saliency maps will be created for this class. Must ... | cd2a329a3f42e8760e5e0cf0134fa6d3a7798f05 | 72,871 |
def select_one():
"""
Select 1 from database
"""
sql = "SELECT 1"
results = query_db(sql, db = get_db(), pretty_print=True)
return results | 4fd4cc6e4a707f581dba3f284cf288299b209211 | 72,872 |
from typing import Dict
def approve_root(
chain: str, start: int, end: int, current_rewards: Dict, tree_manager: TreeManager
):
"""Approve latest root on a chain
:param chain: chain to approve root
:param start: start block for rewards
:param end: end block for rewards
:param current_rewards:... | 7813171adde29775e724edb3a39b5262122b954c | 72,873 |
def _is_required_serializer_field(field):
# type: (ast.Field) -> bool
"""
Get whether we require this field to have a value set before serialization.
Fields that must be set before serialization are fields without default values, that are not
optional, and are not chained.
"""
return not fi... | dc2a07ec4bccca01844e97daa1b8f3632c7c8e81 | 72,874 |
from typing import Callable
def muzero_expand_node(
n: DeterministicNode,
info: Info,
inference: Callable[[State, Action], MuzeroInferenceOutput],
) -> float:
"""Muzero's way of expanding and evaluating a node
``n`` is assumed to contain "action", and its parent "latent_state".
Will create a... | b010a88853bacf1b1d1964fb31df03ab0542435d | 72,875 |
def quote(s):
"""Quote a string, with either single or double quotes depending on the content"""
sq = single_quote(s)
dq = double_quote(s)
return sq if len(sq) <= len(dq) else dq | 92c0ac7547a976c0f9b2745b87d8150e3cdb3de8 | 72,876 |
def PreToolBar(*args, **kwargs):
"""PreToolBar() -> ToolBar"""
val = _controls_.new_PreToolBar(*args, **kwargs)
return val | 804e74dba6758f12330663ec2af7f42c2a214b8a | 72,877 |
def convert_date(date_column):
"""Converts date from object to datetime format
Args:
date_column (pd.Series): Raw object data
Returns:
pd.Series: Default <pd.datetime> format
"""
return pd.to_datetime(date_column, format='%Y-%m-%dT%H:%M:%S') | 0da414e2ca32aa18efc76297184ba7ea40285df9 | 72,878 |
def blank_lines(logical_line, blank_lines, indent_level, line_number,
previous_logical):
"""
Separate top-level function and class definitions with two blank lines.
Method definitions inside a class are separated by a single blank line.
Extra blank lines may be used (sparingly) to sepa... | 0f2d89ae662ffd39170e83f8788cf2946f7cd045 | 72,879 |
import sys
def main():
"""
Main
Returns
-------
int
0 on success, 1 otherwise.
"""
subcommands = {_create: create_vm,
_destroy: destroy_vm,
_create_pool: _create_pool_vm,
_list_pool: _list_pool_vm,
... | a638445c73ab5a7cb8aaeb5fb84f2180fd12d613 | 72,880 |
import os
def train(args):
"""train"""
logger.info("Start train program")
# parse config
config_info = config.parse_config(args.config)
train_config = config.merge_configs(config_info, 'train', vars(args))
valid_config = config.merge_configs(config_info, 'valid', vars(args))
valid_config['... | ecab754fe890f86e630796804fdddefe667b3a7d | 72,881 |
import glob
import os
import re
def doRename(files=None, wildcard=None, pattern='', replacement='', rename=False):
"""Rename all files in a directory using replacement"""
newfiles = []
if files==None:
files = glob.glob(wildcard)
for pathname in files:
basename= os.path.basename(pathna... | 3287f2cdb4a895fdae2cc2baf00da96dd1bf2c4b | 72,882 |
import math
def gen_circarrow(axis=np.array([1, 0, 0]),
starting_vector=None,
portion=0.3,
center=np.array([0, 0, 0]),
radius=0.005,
thickness=0.0015,
sections=8,
discretization=24):
"""
... | 1523994cfa6923ce3219a59bfbfcb7f16144441c | 72,883 |
def confirmation_option(*param_decls, **attrs):
"""Shortcut for confirmation prompts that can be ignored by passing
``--yes`` as parameter.
This is equivalent to decorating a function with :func:`option` with
the following parameters::
def callback(ctx, param, value):
if not value:... | a587cacf29e76c2da95187c1906f311ed0c45338 | 72,884 |
def huffmandict(alphabet, freqs, n, verbose=False):
"""Function that creates the dictionnary for the huffman coder
:param alphabet: List of elements that can be encoded
:type alphabet: list
:param freqs: List of appearence frequencies for each element in the alphabet
:type freqs: list
:param n:... | 9c740c535fcb65f016657aed4db59d13f00f35de | 72,885 |
def dual_quaternions_from_transforms(A2Bs):
"""Get dual quaternions from transformations.
Parameters
----------
A2Bs : array-like, shape (..., 4, 4)
Poses represented by homogeneous matrices
Returns
-------
dqs : array, shape (..., 8)
Dual quaternions to represent transform... | e310547021a1a5939a2ce26d5d81903fedabda28 | 72,886 |
from typing import Union
from typing import List
from typing import Tuple
from typing import OrderedDict
def split_features(
features: Union[List[DenseFeature], List[SparseFeature], List[SparseSeqFeature]]
) -> Tuple[
OrderedDict[str, DenseFeature],
OrderedDict[str, SparseFeature],
OrderedDict[str, Sp... | 0a999cb99c4042dbe55028d8ea948c6f0af7e309 | 72,887 |
def expand_packed(n,packed):
"""
Unpacks the entries of a lower triangular matrix from one dimension
to two dimensions.Identical to PyMC3 expand_packed except it operates on
numpy arrays rather than theano tensors.
Parameters
----------
n : int
The dimension of the matrix to be unpa... | 706bd34160b62d71df4196197986526d0a9f84f5 | 72,888 |
def states_to_piece_positions(next_states):
"""Given a list of next states, produce a list of two coordinates for each
possible next state. The first coordinate will be the location of the
piece that was moved, and the second coordinate will be the location that
the piece moved to.
"""
moves... | b65d4d0d7d9e6e7bd874a51f73c632017de36b99 | 72,889 |
import time
import os
from datetime import datetime
def get_ocdata(exdate = '25FEB2016', start = 540*60, stop = 930*60, waitflag= True, nosleep= True):
"""
start: Market open time/when the data scraping starts, in seconds elapsed from 12:00 AM
stop: Market closing time/when the data scraping stops, in se... | 1e549f75813f55741be70f573ad1965e9485a40d | 72,890 |
import json
def TriggerSwarmingTask(host, request, http_client):
"""Triggers a new Swarming task for the given request.
Args:
request (SwarmingTaskRequest): A Swarming task request.
http_client (FinditHttpClient): An http client with automatic retry.
"""
response_data, error = http_client_util.SendR... | c90b965a3931240f7151ab0d050254d6f180d68d | 72,891 |
def gem_cov(frags, weight_flag):
"""
GEM coverage.
Args:
frags (list of list): [chrom,start,end] for each fragment in a GEM
weight_flag (binary): True if weighted by fragment number; False otherwise
Returns:
gem_all (list of bed entries): bed entries in format [chrom,start,end]
... | cd515d0f358992e07d9bf441c486ce088ce7c7a3 | 72,892 |
import re
def fix_outputs_doc(lines):
"""
Convert a list of lines from the Matlab OUTPUTS section
into a list suitable for the numpydoc Returns section,
handling multiple output variables if present.
Exception: we don't support the 'in_ocean' return, so
it is filtered out here.
"""
pa... | 659a9ac494094c2beae6bc052ac842aae6dd9259 | 72,893 |
def load_task_specific_data_in_proportion(datasets, task_labels, classes_appearing_in_tasks, class_seen_already):
"""
Loads task specific data from the datasets proportionate to classes appearing in different tasks
"""
global_class_indices = np.column_stack(np.nonzero(datasets['labels']))
count = 0
... | 1f8e9693908d82e9679175f277f0cfc6a9610452 | 72,894 |
import re
def tokenize(text):
"""
This function tokenizes text by deleting punctuation, converting
to lowercase, deleting stopwords, lemmatizing and stemming
Input:
text - text to be tokenized
Output:
stemmed - the resulting tokens
"""
url_regex = 'http[s]?://(?:[a-zA-Z]|... | c8c82d8eb2fb0dfa966ed7f974358709eb5db573 | 72,895 |
def svn_stream_copy(*args):
"""svn_stream_copy(svn_stream_t _from, svn_stream_t to, apr_pool_t pool) -> svn_error_t"""
return _core.svn_stream_copy(*args) | bcf56d71a44d2b229f8677998484e033de46c92b | 72,896 |
def get_short_name(obj):
"""
Returns short name of given Maya object
:param obj: str
:return: str
"""
try:
obj = obj.meta_node
except Exception:
pass
node_names = maya.cmds.ls(obj, shortNames=True)
if node_names:
if len(node_names) == 1:
return n... | 671c5eab19ee0308a248ac4cf71aff89213eadd2 | 72,897 |
def BPRLoss(vocab_size: int, dim: int):
"""BPR Loss with biases."""
return dpr.layers.Sequential(
dpr.layers.Select(inputs=("userEmbeddings", "targetPositives", "targetNegatives", "targetMask")),
dpr.layers.Embedding(
inputs="targetPositives",
outputs="targetPositiveEmbed... | 7ca500c9f16483f8a0457c41b1029239b7c47ee1 | 72,898 |
from typing import List
import random
def generate_good_endowments(nb_goods: int, nb_agents: int, base_amount: int, uniform_lower_bound_factor: int, uniform_upper_bound_factor: int) -> List[List[int]]:
"""
Compute good endowments per agent. That is, a matrix of shape (nb_agents, nb_goods).
:param nb_good... | 954feb953a760a473ac684c0b2f21eb5fa9fd046 | 72,899 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.