content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def find_sol(c, ws, memo):
"""
Finds an optimal solution for the given instance of the subset sum problem
with weight capacity c and item weights ws, provided maximum total weights
for subproblems are memoized in memo.
"""
sol = []
for n in reversed(range(len(ws))):
if c >= ws[n] and... | 328c6c4d56f9a2f8823c4bd97f4791499cd8ecd3 | 47,900 |
from typing import Optional
from typing import Callable
from typing import cast
def atomic(connection_name: Optional[str] = None) -> Callable[[F], F]:
"""
Transaction decorator.
You can wrap your function with this decorator to run it into one transaction.
If error occurs transaction will rollback.
... | a30522040dd950081ac1cc2c037f2b83ae8a2c7f | 47,901 |
def get_rectangle_information(form):
"""
Функция для формирования json с полигоном для отрисовки аналитики по области
:param form: форма из POST запроса с координатами области (прямоугольника) и 6 основными фильтрами
:return: json с полигоном и необходимой информацией
"""
rectangle_information =... | 443530cbc54769960d1f32b11ae46a1054bd3829 | 47,902 |
import math
def distance(p0, p1):
"""calculate distance between two joint/3D-tuple in the XZ plane (2D)"""
return math.sqrt((p0[0] - p1[0])**2 + (p0[2] - p1[2])**2) | 02e1a1488c32f465f2a1817adb8dfbdb4ea26431 | 47,903 |
def cut_traces(cntfile, annotation):
"""cut the tracedate from a matfile given Annotations
args
----
cntfile: FileName
the cntfile for cutting the data. must correspond in name to the one specified in the annotation
annotation: Annotations
the annotations specifying e.g. onsets as we... | 5aa78ed4d72835458508204c22c5be17d855c2a4 | 47,904 |
import argparse
def get_args():
"""
Method to read the command line arguments and parse them
"""
parser = argparse.ArgumentParser(
description="Split a playlist into multiple playlists"
)
# Required arguments for the program
parser.add_argument("-p", "--playlist_id", required=True... | 3648cd847a760182029d39d858b06a0dd7bc1545 | 47,905 |
import re
import click
def dict_raise_on_duplicates(ordered_pairs):
"""Reject duplicate keys."""
d = {}
schemaOrg = False
for k, v in ordered_pairs:
if re.search(r"\s", k):
# click.secho(k)
click.secho("Please remove the whitespace(s) in property name " + k+
... | 68de1c8f4b6d8d36c90c5b3446f89b67f6fe50d3 | 47,906 |
def plot_radar_chart(data, line_labels, var_labels, **kwargs):
"""Make a radar chart.
Input data is assumed to differ in variables along the columns and differ in
observations/samples along the rows.
Parameters
----------
data: sequence, one- or two-dimensional
Data to plot. Must be so... | 8e542a6e9c49d7751850b7c38c2dec449a12af54 | 47,907 |
def cod_tapcode(mensagem: str, tipo_saida: int) -> str:
# Tabela do tap code
"""Função para codificar em tap code"""
tabela: list = [['A', 'B', 'C', 'D', 'E'],
['F', 'G', 'H', 'I', 'J'],
['L', 'M', 'N', 'O', 'P'],
['Q', 'R', 'S', 'T', 'U'],
... | 4e88755e976bd24e330432d8242cab872e548eff | 47,908 |
import copy
def difference(df, cols, lag=1):
"""
Perform differencing on some columns in a dataframe.
Input:
------
df: pandas dataframe containing the timeseries data.
cols: list of strings indicating which columns to difference
"""
df2 = copy.deepcopy(df)
# Difference based on ... | 00a7edf9fc49f60736a15099b0ab2db178671dc0 | 47,909 |
def regional_indicator(c: str) -> str:
"""Returns a regional indicator emoji given a character."""
return chr(0x1F1E6 - ord("A") + ord(c.upper())) | 9b146ae19e8d41e7c5650c2c08f1c89f1ae7af77 | 47,910 |
import random
import string
def reset_pw(username):
"""Reset a password"""
password_new = ''.join(random.SystemRandom().
choice(string.ascii_uppercase + string.digits)
for _ in range(6))
cursor, conn = db_sql.connect('users.db')
sql = ("UPDATE user... | 817d0df5b1aa460a63e482054db7f2255dada7b1 | 47,911 |
def loadSim(simdir, paramname='snapshot.param'):
"""
Loads a dustydiffusion simulation from a directory. In particular, this
requires the runparameters to be saved in the directory.
Returns
-------
fs : list
list of pynbody snapshots
eps : fcn
Estimate the dust fraction... | 7de1bc65901e9d5984f936386748f148164971b1 | 47,912 |
def update_event_participant(event_id, participant_id):
"""Update an event participant's attendance"""
if flask.request.method != "PUT":
return flask.abort(405)
# Return whether they're True or False based on what's in the request body
return flask.jsonify({"attended": True}) | 9abecfad51a3799c09c0879dc297fbb3fa5b9ec0 | 47,913 |
def send_test_campaign(c: str = None, e: str = None):
"""
Send a test campaign
"""
client = get_client()
if not c:
global campaign_id
c = campaign_id
d = {"test_emails": [e], "send_type": "html", "settings": {"subject_line": "Found test"}}
r = client.campaigns.actions.test(... | 6e2f83a4150bacac608ae054b9e96574be3d5ab8 | 47,914 |
import uuid
def _CreateFeed(client):
"""Creates the feed for DSA page URLs.
Args:
client: an AdWordsClient instance.
Returns:
A _DSAFeedDetails instance containing details about the created feed.
"""
# Get the FeedService.
feed_service = client.GetService('FeedService', version='v201802')
# C... | fc02bc95ac40c192f0aaf60839a01dde234b1448 | 47,915 |
def parse_amount_string(amount: str) -> float:
"""
Parse strings like
- '1.000,00-'
- '1.000,00 S'
- '23,23+'
- '23,23 H'
to the correct amount as float
:param amount: The string of an amount
:return:
"""
# Replace H and S
amount = amount.replace("H", "+").repla... | 1307f753289b53bcd3f895e2582903064c9125ad | 47,916 |
def custom_implicit_transformation(result, local_dict, global_dict):
"""Allows a slightly relaxed syntax.
- Parentheses for single-argument method calls are optional.
- Multiplication is implicit.
- Symbol names can be split (i.e. spaces are not needed between
symbols).
- Functions can be ... | 78d9e21cb5531f994fd218ce930d2a114391049f | 47,917 |
import os
def model_core_from_theseus(models, alignment_file, var_by_res, work_dir=None):
"""
Only residues from the first protein are listed in the theseus output, but then not even all of them
We assume the output is based on the original alignment so that where each residue in the first protein
... | 4e04642afc77df6d6c66a601365759665fdc1e3d | 47,918 |
def fractal_sda(signal, scales=None, show=False):
"""Standardised Dispersion Analysis (SDA)
SDA is part of a family of dispersion techniques used to compute fractal dimension.
The standardised time series is divided in bins of different sizes and their standard deviation (SD)
is calculated. The relatio... | 530bb7bc960f41d20e59bd20f2887a7f3fff088a | 47,919 |
def _randomize_dyads(network, keep, timeout):
"""
This function returns a network with the same nodes and edge number as the input network.
Each edge is swapped rather than moved, so the degree distribution is preserved.
:param network: NetworkX object in tuple, with first item in tuple being network n... | 5c9d2fc2be573267329fa66ec7cb79276a6ed9a4 | 47,920 |
def reproject(geom, from_proj='EPSG:4326', to_proj='EPSG:26942'):
"""Project from ESPG:4326 to ESPG:26942."""
tfm = partial(pyproj.transform, pyproj.Proj(init=from_proj), pyproj.Proj(init=to_proj))
return ops.transform(tfm, geom) | 808c334bb822f37f71316222b0cf323916e070c2 | 47,921 |
def validate_xml(xml_to_check):
"""
validate the xml of the supplied input
:param xml_to_check: bytes object which is the xml to be validated
:return: True or False
"""
try:
etree.parse(BytesIO(xml_to_check))
return True
except etree.XMLSyntaxError:
return False | a12c412f63c77dcab4c6623aae74b7c7805bac2f | 47,922 |
import os
def get_translation_dict_from_file(path, lang, app):
"""load translation dict from given path"""
cleaned = {}
if os.path.exists(path):
csv_content = read_csv_file(path)
for item in csv_content:
if len(item)==3:
# with file and line numbers
cleaned[item[1]] = strip(item[2])
elif len(it... | cc4f4921bbabe3d65a332d12617aedfa1532f184 | 47,923 |
def __scale_width(img, target_width):
"""__scale_width"""
ow, oh = img.size
# the size needs to be a multiple of this number,
# because going through generator network may change img size
# and eventually cause size mismatch error
mult = 4
assert target_width % mult == 0, "the target width ... | aeaca67a9dbd2b71e4d62819fb5f4b3f11787edf | 47,924 |
import re
def validate_orcid_id(ctx, param, orcid_id: str):
"""
Check if valid ORCID iD, should be https://orcid.org/ + 16 digit in form:
https://orcid.org/0000-0000-0000-0000. ctx and param are
necessary `click` callback arguments
"""
if re.match(ORCID_ID_REGEX, orcid_id):
ret... | f63cc8a5e4d753aaae73366ca8414148ade7bf06 | 47,925 |
import os
import shutil
def StageWheelForPackage(system, wheel_dir, wheel):
"""Finds the single wheel in wheel_dir and copies it to the filename indicated
by wheel.filename. Returns the name of the wheel we found.
"""
dst = os.path.join(system.wheel_dir, wheel.filename)
source_path = _FindWheelInDirectory(... | d0aa66cd87a8d0ffda19db489d1172ea4b315255 | 47,926 |
def _get_build_modes_for_base_path(base_path):
""" Returns `get_build_modes_for_cell_and_base_path()` for the specified base_path """
return _get_build_modes_for_cell_and_base_path(
config.get_current_repo_name(),
base_path,
) | 6409c1846f58dfb0e9a0f8df46b2b6e9caa91d7e | 47,927 |
def unique_chunks(lst, n):
""" Returns unique chunks of length n from lst. """
if n < 1:
return set()
return {tuple(lst[i:i + n]) for i in range(0, len(lst), n)} | e06758a4cb13e42394560e3fe2b4889a8e321af9 | 47,928 |
import requests
def query_turtle(sparql_query):
""" Make a SPARQL query with turtle format response"""
data = {'query': sparql_query, 'format': 'text/turtle'}
auth = (settings.SPARQL_AUTH_USR, settings.SPARQL_AUTH_PWD)
headers = {'Accept': 'text/turtle'}
r = requests.post(settings.SPARQL_QUERY_URI... | 9f8e8496c2066dbffd2d6b2a10cb830186d53c25 | 47,929 |
def predict_note_auth():
""" BANK NOTES AUTHENTICATION
This is using DOCSTRING for specifications.
----
parameters:
- name : variance
in: query
type : number
required : true
- name : skewness
in: query
type : number
required : t... | cb2bdab12d8260fd3521a90998d1b15c4c2cae17 | 47,930 |
def mse(predicted, actual):
"""
Mean squared error of predictions.
.. versionadded:: 0.5.0
Parameters
----------
predicted : ndarray
Predictions on which to measure error. May
contain a single or multiple column but must
match `actual` in shape.
actual : ndarray
... | ddcd3e3f3f3d8a7ab865db4818ab1f9b49b1430a | 47,931 |
def handler():
"""
This function puts into memcache and get from it.
Memcache is hosted using elasticache
"""
#r = redis.Redis(
#host='datanode-001.zumykb.0001.use2.cache.amazonaws.com',
#port=6379)
logging.info('created redis client')
queryuserid = sys.argv[1]
querylat = float(sys.argv[2])
querylong = flo... | 4a4975e1299813d1001f567df9a04e5aef2cf2ed | 47,932 |
def a_view(request):
"""Regular unlocked view."""
return HttpResponse('A view.') | 1552ae02cdead810fb60084ecd0977bab79d2818 | 47,933 |
def rotz(ang):
"""
Create a rotation matrix (3 x 3 np.array) in the 3D space with respect to z axis
:param ang: radians. If ang <(>) 0, rotation is (anti-)clockwise with respect to z.
:return: Rz: np.array of shape (3, 3) representing the rotation matrix
"""
Rz = np.array(
[
... | 298ea0e62dbcea711cbe980e1adf0ae167a7124a | 47,934 |
import os
import shutil
import sys
import traceback
def copy(source, destination, quiet=False):
""" Copy a file or folder.
"""
src = os.path.normpath(source)
dst = os.path.normpath(destination)
if not quiet:
pass
#verbose.print_('copy "%s" -> "%s"' %(src, dst))
try:
shutil.copyfile(src, dst)
return Tru... | 7dba1ad311109c9df4ef1cdd245c429ce1627359 | 47,935 |
from pathlib import Path
def fixture_vcf_dir(fixtures_dir: Path) -> Path:
"""Return the path to the vcf fixtures directory"""
return fixtures_dir / "vcfs" | 7a77d40a34fc05b7acb20cc60c0e7343ffd4bfa8 | 47,936 |
def init_params(units, activations):
"""Initialize parameters of the model.
Arguments:
units (list): Each item in the list is the number of units
in the layer. units[0] is the number of input units and
units[len(units) - 1] is the number of output units.
activations (list): Each... | 8d66be5bcc08c2ced30c262da788c5336a13f7e1 | 47,937 |
def pos_features(df):
"""
Gets several part-of-speech features:
1) Percentage of nouns and proper nouns.
2) Percentage of proper nouns
3) Percentage of pronouns
4) Percentage of conjunctions
Needs features:
Tokens
N_words
Adds features
Noun_percent: percentage of no... | efcc4d006a28e71e7f9bfd9d2a1511492ef5ed66 | 47,938 |
import functools
def no_cache(func):
"""Decorator to disable proxy response caching."""
def wrapped_function(*args, **kwargs):
"""Wrapper function to add required headers."""
if flask.request.method == 'OPTIONS':
resp = flask.current_app.make_default_options_response()
else... | f7ec88763de1a47c83aa88410bb927ce18980319 | 47,939 |
def NDArrayEnd(builder):
"""This method is deprecated. Please switch to End."""
return End(builder) | 5dbf92416f8a6b58b8255a54cff88327ed6b00e8 | 47,940 |
def calcularPVoto(tVoto, vJogador):
"""
-> Calcula o percentual de voto de cada jogador que recebeu voto
:param tVoto: Quantidade total de votos computados
:param vJogador: Quantidade de votos do jagador a ser calculado o percentual
Função criada por Jcvendrame
"""
return (vJogador / tVoto) ... | d21dfc72d70d6a9bdea7d5420cea3a63a57204cf | 47,941 |
def construct_SA1_wavefront(nx, ny, ekev, q, xoff = 0, yoff = 0, mx = 0, my = 0,
tiltX = 0, tiltY = 0,
xMin = -400e-06, xMax = 400e-06,
yMin = -400e-06, yMax = 400e-06):
"""
Construct a fully-coherent Gaussian source with proper... | 2ff67665dfb6b474afc5ded73dcbc804fe7b8b4a | 47,942 |
def check_sudoku_block(board, row, col):
"""
Check if the Sudoku board is valid.
"""
board_size = board.shape[0]
block_size = int(np.sqrt(board_size))
row_start = row - row % block_size
col_start = col - col % block_size
gt = set(range(1, board_size + 1))
r = set(board[row_start:(ro... | ca33d815a7743f400ee900efe73c8dbb4a9333b1 | 47,943 |
def equalRankin(ranking, other):
"""Compare two rankings
Args:
ranking (List<CurrencyUsers>)
other (List<CurrencyUsers>)
Return:
Boolean. True if both ranking are equals.
"""
if not other or not ranking:
return False
if len(ranking) != len(other):
return ... | 351fc60ad18450179d7395f7f88698acfdb2c8d4 | 47,944 |
def get_game_range_row_names(game_begin, game_end):
"""Get the row range containing the given games.
Sample row name:
g_0000000001_m001
To capture the range of all moves in the two given games,
the end row will need to go up to g_00..(N+1).
Args:
game_begin: an integer of the beginni... | 700740131dbd497af8b80832a7ad11960ccc710f | 47,945 |
def calc_QIF(P, T):
"""
Quartz-Iron-Fayalite (QIF)
==========================
Define QIF buffer value at P
Parameters
----------
P: float
Pressure in GPa
T: float or numpy array
Temperature in degrees K
Returns
-------
float or numpy array
log_fO2
References
----------
B. R. Frost in Mineralogic... | 550d86fb98f21f728b013f503564f5b1237ef9bb | 47,946 |
import math
def score_word_count(count: int) -> float:
"""Score word frequency as log of count with min of 1.0"""
return max(1.0, math.log(count)) | e49febcac36653a3a188c0ec3edd9cca0c18b81a | 47,947 |
import jinja2
def render(filename, variables):
"""
Grabs the jinja2 file and renders it
:param filename: the jinja2 file to render
:param variables:
:return:
"""
with open(filename, 'rt') as f:
filename = jinja2.Template(f.read())
return filename.render(**variables) | 09fcf7a6966276e2a362f64bfac84dfb5fb1dd0c | 47,948 |
def load_genomes(UTRfilestring, firstStopsCSV, twobitfile):
"""
make this a separate function so that these only need to be loaded a single time
"""
UTRdict= rph.readindict(open(UTRfilestring, "rU"))
utr3adj = pd.read_csv(firstStopsCSV, index_col=0)
genome= twobitreader.TwoBitFile(twobitfile) # do we actually nee... | 0a291c0b55e1f868a87a882fe95167ba829ed759 | 47,949 |
def calcTheta(wavelength, z1):
"""
Calculates the d spacing and the theta angle for a scattering
vector z1
@param wavelength
@param z1 A 3 component numpy array representing the scattering
vector
@param A tuple consisting of the d-value and the theta angle in
radians
... | 9ce846acd4e4b6f211d6b76558d18a54d16f0b75 | 47,950 |
def octahedron():
"""Return the best integral embedding of the octahedral graph."""
v1 = (13 * root(1, 6, 1) - 2) / 3
v2 = -v1.conjugate()
omega = root(1, 3, 1)
v3 = v1 * omega
v4 = v2 * omega
v5 = v1 / omega
v6 = v2 / omega
vertices = (v1, v2, v3, v4, v5, v6)
edges = ((0, 1), (0... | d402fd23e8844bdaad612b17f0930f89b2da248f | 47,951 |
def symbols_for_inclusion(file: CheckFile, match) -> list:
""" Return a list of symbols for a match. """
line_number, column = file.line_number_at(match.end())
line = file.line_at(line_number)
include_suffix = line[column:]
if not is_symbol_list(include_suffix):
return []
listing = ... | 75455942cc7b6abc46ff793522b1297a7157b63e | 47,952 |
def sample_user(email="student@test.com",
password="password123",
name="some name"):
"""Create sample user for tests"""
return get_user_model().objects.create_user(email=email,
password=password,
... | 4d558ca16eb660fe7579ce470e5a2b1c66a369e7 | 47,953 |
def reduce(l):
"""
Args:
Rangelist: generic list of tuples (can be either float or int tuple)
Return:
Reduced int list based on average value of every tuple in input tuple list
"""
result = []
for s in l:
midVal = abs(float(s[0]) - float(s[1])) / 2.0
result.append... | 5db6214bc439dcc149d0d4cef1b66930f40694d7 | 47,954 |
def polygon_iou(pts1, pts2):
"""
Intersection over union between two shapely polygons.
"""
poly1 = Polygon(pts1).convex_hull
poly2 = Polygon(pts2).convex_hull
# union_poly = np.concatenate((pts1, pts2))
if not poly1.intersects(poly2): # this test is fast and can accelerate calculation
... | 0e68901bc422d77f1ba3e14d1285db22f81fd2eb | 47,955 |
import math
def choose_team_levels(num_teams, hackathon_level):
""" Calculates the average experience level per team and distributes any
remaining difference among some of the teams evenly
Returns a list of team_levels """
avg_team_level = math.floor(hackathon_level / num_teams)
team_levels = []
... | aaf372f00969da62b966a2a09aff64a188fbce82 | 47,956 |
def overall_random_accuracy_calc(item):
"""
Calculate overall random accuracy.
:param item: RACC or RACCU
:type item : dict
:return: overall random accuracy as float
"""
try:
return sum(item.values())
except Exception:
return "None" | 0e6cf8ae129235a41db084d2d9d5c92bb5788ed8 | 47,957 |
def infer_time_unit(time_seconds_arr):
"""
Determine the most appropriate time unit for an array of time durations
specified in seconds.
e.g. 5400 seconds => 'minutes', 36000 seconds => 'hours'
"""
if len(time_seconds_arr) == 0:
return 'hours'
max_time_seconds = max(time_seconds_arr... | 11f25a712d8d66e8546fea2f7e36309dcebbcc74 | 47,958 |
def user_is_author_of_snippet(user, snippet_type, snippet_id):
"""
Checks if the current user is
the author of the snippet provided
"""
snippet_models = {
"project": Project,
"skill": Skill,
"profile": Profile
}
snippet = get_object_or_404(snippet_models[snippet_type]... | 8408d18971005f3f00bc961f386193dffc28a9f5 | 47,959 |
def _batch_hard(query_features, positive_features, item_ids):
"""
Adapts the 'Batch Hard' triplet mining strategy of Hermans, Beyer, and Leibe.
This method differs from Batch Hard in that we don't search for the hardest positive
and just use the one positive example provided.
Args:
query_featur... | ac262b089a24dc48aa6c779c1c3b1772ce4a85ff | 47,960 |
def add_paper_grading_sheet(supervisor, modified_df):
"""Adding the Paper Grading sheet with all supervised student Papers and grading metrics"""
src_grading_wb = load_workbook('DataSources/Foik_GradingSheetSeminar.xlsx')
print("The available sheets in the xlsx file")
print(src_grading_wb.sheetnames)
... | 7a9a64eea8718cf56992b7163aadfece17edfd43 | 47,961 |
def getnuc(nuc = 430990001):
"""
This computes ORIGEN data based on ENSDF data.
FIXME: calculate B- and EC decays that end in metastable state after gamma transition
Parameters
----------
nid : nuc_id
a valid string or int that can be converted into a nuc_id
meta_t : float
... | 2582c0906037a7404ef71f3ced6352b776cce24b | 47,962 |
def addContraints(d, Ca):
""" Ajoute les conditions de Robinson qui ne sont pas encore satisfaites à Ca """
addedConstraints = False
precision=0.0001
nb=0
# print 'Contraintes ajoutees'
for i in range(d.n-2):
for j in range(i+2, d.n):
if (d[i,j] < d[i,j-1] - precision) and ([... | 7967c85ba7207fc2e525451b36432aec973cb95f | 47,963 |
from typing import List
def getTaxonomyKEGG() -> List[str]:
"""
Get KEGG taxonomy from KEGG BRITE.
Returns
-------
List[str]
Taxonomy of organisms in KEGG, in special text format, following KEGG's own scheme, line by line.
Raises
------
URLError
If connection ... | 58f4c406b401299da9e1aba24ccc9feef53d2e0d | 47,964 |
def fprint(prompt: str, question: bool=False, returnstr: bool=False):
"""
Fancy print function
"""
tags = {'[o]': '[\033[01;32m+\033[0m]',
'[ok]': '[\033[01;32m+\033[0m]',
'[+]': '[\033[01;32m+\033[0m]',
'[e]': '[\033[01;31m-\033[0m]',
'[er]': '[\033[01;31... | 27be27f40a112b5f14bbbf728deb319dccb77e7d | 47,965 |
import itertools
import random
def random_tuple_list(lst1, lst2, lb=1):
"""
Generate a random list of tuples (x,y) where x is in lst1 and y is in lst2;
"""
product = list(itertools.product(lst1, lst2))
if len(product) == 0:
k = 0
else:
k = random.randint(lb, len(product))
... | d21846b6d4cfee6479050f78046909329c5596b2 | 47,966 |
def tmp_img(tmpdir):
"""Get temp image fixture used by some test."""
img_path = tmpdir.join('image.jpg')
im = Image.new('RGB', (160, 160))
im.save(img_path.strpath)
return img_path | c6d9335e41b602ab50d54b370b4d671ae7bc433f | 47,967 |
def combine_stage1_stage2(df_1, df_2):
"""Combines the stage 1 and stage 2 submissions.
Replaces the positive class predictions in df_1 with those created in
df_2.
Args:
df_1 (pd.DataFrame): Stage 1 submission
df_2 (pd.DataFrame): Stage 2 submission
Return:
combined_df... | 107c20689ae339a115573a28358d5c29f1b9b269 | 47,968 |
import time
def swap_status_iterator(uuids_list: list, node_proxy: MMProxy) -> dict:
"""Builds swaps statuses dictionary"""
swaps_d = dict.fromkeys(uuids_list, 'unknown')
while True:
work_d = {} # intermediate dictionary to iterate unfinished swaps
values_list = []
for key in swap... | fccb72487afa117963da73457219630620ceddd6 | 47,969 |
from datetime import datetime
def from_utc(utcTime, fmt="%Y-%m-%dT%H:%M:%SZ"):
"""
Convert UTC time string to time.struct_time
"""
return datetime.datetime.strptime(utcTime, fmt) | e4fb9792f8254c6d3a5d20d3da491dbe254c594a | 47,970 |
def intersectGraphs(graph1={}, graph2={}):
"""Given two Graphs, create a new Graph that is their Relational Intersection
` Preconditions: Graph in Xaya Format
Postconditions: returns a graph in XAYA format with intersecting keys and values
Invariants: The input graphs do not change
... | 639d2ad4a0e5da223aefad13d62f11ad9ec74d9d | 47,971 |
def get_r2(reg, X, y):
"""Calculate the goodness of fit of regression model.
Arguments:
reg {model} -- regression model.
X {ndarray} -- 2d array object with int or float.
y {ndarray} -- 1d array object with int.
Returns:
float
"""
if isinstance(y, list):
y =... | 8e478325fd6790218bb89d5556bcf7190b9f72ae | 47,972 |
def h_m_emg_rvs(mu, sigma, *t_args,N_samples=1):
"""Draw random samples from negative skewed hyper-EMG probabaility density
Parameters
----------
mu : float
Nominal position of simulated peak (mean of underlying Gaussian).
sigma : float
Nominal standard deviation (of the underlying ... | 4b23267b7fe8ef4e1596e9ab6e4d8f4fbd32a208 | 47,973 |
def user_ajax_answer(request):
"""Submitting work to task (making Answer of it) is handled here.
Accepts only POST requests.
POST (ajax) params (all required):
wi: work id
ti: task id
ni: network id
a: action, (add or remove)
"""
if request.method !=... | 52138ff6defbce7fa07e6cdad14a991db22c1360 | 47,974 |
def get_diff(a, b):
"""比较图片差异"""
return get_match(a, b)[0] | 9cdeb2d5da40c58d1c295203502cb694a51bc877 | 47,975 |
def get_image_metrics_for_samples(
real_images, generator, prior, data_processor, num_eval_samples):
"""Compute inception score and FID."""
max_classifier_batch = 10
num_batches = num_eval_samples // max_classifier_batch
def sample_fn(arg):
del arg
samples = generator(prior.sample(max_classifier_b... | aa23d8694d0426d90cb3b502c49e13ef4346a87b | 47,976 |
from typing import Tuple
def load_data(
partition: int, num_clients: int
) -> Tuple[Tuple[np.ndarray, np.ndarray], Tuple[np.ndarray, np.ndarray]]:
"""Load partition of randomly shuffled Fashion-MNIST subset."""
# Load training and test data (ignoring the test data for now)
(x_train, y_train), (x_test,... | fa4d318d470b83ec0388f9da817f3f92aa435265 | 47,977 |
def flip_y(im):
"""mirrors an image over the x axis."""
source_pix = im.load()
im = im.copy()
dest_pix = im.load()
width, height = im.size
for i in range(width):
for j in range(height):
dest_pix[i,j] = source_pix[i, height-j-1]
return im | 9ad00b2de3e628cc6dd441884103b9d2e3492333 | 47,978 |
def augment_menpo_img_geom_dont_apply(img, p_geom=0):
"""geometric style image augmentation using random face deformations"""
if p_geom > 0.5:
lms_geom_warp = deform_face_geometric_style(img.landmarks['PTS'].points.copy(), p_scale=p_geom, p_shift=p_geom)
return img | 08b7ac4d6e05269ad037c044503110727f2525bd | 47,979 |
import torch
def lower_matrix_to_vector(lower: torch.Tensor) -> torch.Tensor:
"""Convert a lower triangular matrix to a vector.
Parameters
----------
lower : torch.Tensor
lower
Returns
-------
torch.Tensor
"""
shape = lower.shape
assert shape[-1] == shape[-2]
low... | e4fe825caf5926ce3219c4dd7720d1b7f180b998 | 47,980 |
import codecs
import subprocess
import os
def PoStag(filepath, output, postProc=lambda w, tag: (w,tag), preProc=lambda w: w):
"""Pass tokenized file to tagger convert file to CoNLL and write to output"""
inpt = codecs.open(filepath, encoding="utf-8")
text = inpt.readlines()
inpt.close()
... | 2c71bada39093e668c5d2a3a72d75d21fe131e6b | 47,981 |
def proxy_line(**kwargs):
"""
Generates a legend proxy for a line region.
Returns
----------
:class:`matplotlib.lines.Line2D`
"""
return matplotlib.lines.Line2D(range(1), range(1), **kwargs) | 62df36751f1de28a6267143844557d3e41adf8f5 | 47,982 |
from typing import Union
from typing import List
import os
def cluster_cr_conv(sources: Union[GalaxyCluster, ClusterSample], outer_radius: Union[str, Quantity],
inner_radius: Union[str, Quantity] = Quantity(0, 'arcsec'), sim_temp: Quantity = Quantity(3, 'keV'),
sim_met: Union[f... | 8c1a0cf1f180da275bd67eb60f7f4516b31ba17c | 47,983 |
def test_drawing():
"""Test circuit drawing"""
x = np.array(0.1, requires_grad=True)
y = np.array([0.2, 0.3], requires_grad=True)
z = np.array(0.4, requires_grad=True)
dev = qml.device("default.qubit", wires=2)
@qml.beta.qnode(dev, interface="autograd")
def circuit(p1, p2=y, **kwargs):
... | 1fcb0ab762582b971b70eccc7e09da9ae108377a | 47,984 |
from typing import Union
def encrypt_vault_password(key: bytes, password: Union[str, bytes]) -> bytes:
"""Encrypt and return the given vault password.
:param key: The key to be used during the encryption
:param password: The password to encrypt
"""
if isinstance(password, str):
password ... | 2f366ab3c560a5171e6697bc49fbfd971bc96b31 | 47,985 |
def t_to_col(t, tmin=6, tmax=11):
"""
Given a BPASS time bin, returns a value to input into the time colormap
Parameter
---------
t : float
BPASS log time bin between 6 and 11
Returns
-------
out : int
Input to tcmap to get the right color out
"""
co... | cf589a15d1efafaeef037d478cfae21317c2aac5 | 47,986 |
def create(user, request):
"""Create a new album for this user."""
# TODO validate the name in some manner?
# TODO also validate the permission ahem
album = model.Album(
name=request.POST['name'],
encapsulation=request.POST['privacy'],
)
user.albums.append(album)
model.sessio... | d8f5cabb363920beb726904e95be0607ee77e561 | 47,987 |
def blockify(sudoku):
"""
Converts 9x9 sudoku list into a list containing lists of values in given sudoku's blocks
args:
-sudoku - 9x9 sudoku list
returns: List with lists of values of sudoku blocks
"""
i=0
block_row = []
while i<len(sudoku):
j=0
while j<7:
... | 4f24aa3c3f8eb7132ab512bd74c03d8fd1947db0 | 47,988 |
def map_coords_to_scaled_float(coords, orig_size, new_size):
"""
maps coordinates relative to the original 3-D image to coordinates corresponding to the
re-scaled 3-D image, given the coordinates and the shapes of the original and "new" scaled
images. Returns a floating-point coordinate center where t... | f5e1e1523366a9e1e37f9d1a304d9deea8d53e00 | 47,989 |
def getPosition(junctionID):
"""getPosition(string) -> (double, double)
Returns the coordinates of the center of the junction.
"""
return _getUniversal(tc.VAR_POSITION, junctionID) | ecb12bb97a7ab1be52723611edb83ceb7de78614 | 47,990 |
def _structure_summary(structure):
"""
Extract messages from the structure.
Args:
structure: a Pymatgen Structure object
Returns:
dict of the following messages:
nsites (int): number of sites in the structure.
is_ordered (bool): whether the structure is ordered or not.
... | 65fe88a01d53df7ab487ae1d1ab24a4c2c746477 | 47,991 |
import logging
def _mock_run(*args, **kwargs):
"""Placeholder logic for logging tests."""
logging.debug(args)
logging.debug(kwargs)
logging.warning("warning")
logging.error("error")
return True | 9d57d30afa55e0a8a810a1a15979583fbe8d9440 | 47,992 |
def id_type_dict(obj):
"""Creates dictionary with selected field from supplied object."""
if obj is None:
return None
return {
'id': str(obj.id),
'type': obj.type,
} | 7c7d67eee81a3d1553392617304bda4166bce817 | 47,993 |
from typing import Sequence
from typing import Union
from typing import Tuple
from typing import List
from typing import OrderedDict
def _split_selections_property_and_vertex(
selections: Sequence[Union[SelectionNode]],
# OrderedDict is unsubscriptable (pylint E1136)
) -> Tuple["OrderedDict[str, SelectionNode... | 260df2df41c92dfdd8402ca686e03309e96934d8 | 47,994 |
from typing import Union
from typing import Dict
from typing import Optional
from pathlib import Path
import os
import tarfile
import shutil
def cached_path(
url_or_filename,
cache_dir=None,
force_download=False,
proxies=None,
resume_download=False,
user_agent: Union[Dict, str, None] = None,
... | de8f95c0760a0c186ff1ea63ccca37c46f9452ea | 47,995 |
def is_3d(mesh: Mesh) -> bool:
"""Check if a meshio mesh is 3-dimensional"""
for cell_block in mesh.cells:
# first 3D element type is enough.
if meshio_type_to_alpha[cell_block.type] in meshio_3d:
return True
return False | bd6b6bda26c6269121381ff6d9419f5b9129b76b | 47,996 |
import torch
def multiclass_nms(multi_bboxes,
multi_scores,
score_thr,
nms_cfg,
max_num=-1,
score_factors=None):
"""NMS for multi-class bboxes.
Args:
multi_bboxes (Tensor): shape (n, #class*4) or (n, 4)
... | f3152e30eda4286ecfedc1b3fa3cf922470e0ada | 47,997 |
def delete_case_study(case_study_id):
"""
Delete a case study
:param case_study_id:
:return:
"""
updater_json = validate_and_return_updater_request()
casestudy = CaseStudy.query.filter(
CaseStudy.id == case_study_id
).first_or_404()
audit = AuditEvent(
audit_type=A... | 4ad9b900f294e99b54f4e88d556a6074e7a0fa94 | 47,998 |
import random
def clustering_kmember(nec_set, k=25):
"""
group record accroding to QID distance. K-member
:param nec_set: natural EC
:param k: k
:return: grouped clusters
"""
clusters = [cluster for cluster in nec_set if len(cluster) >= k]
nec_set = [cluster for cluster in nec_set if l... | 0a18618cf39b688d703694b9700fe1fd0b074de2 | 47,999 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.