content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def compute_pascal(n):
"""
Compute the nth row of Pascal’s triangle
Parameters
----------
n : integer
which row too compute
Returns
-------
pascal_n : a list of integers
The nth row of Pascal’s triangle.
"""
pascal_n = [1]
prev = 1
for k in range(1,n+1)... | 54b2d5ca80412d2da4da4e9f09dff25026205d3d | 29,012 |
def param_case():
"""
decorator to make new test case class using params
"""
def _wrapper(cls):
name = cls.__name__
test_funcs = {}
for attr in dir(cls):
it = getattr(cls, attr)
if not hasattr(it, '__parameters__') or not callable(it):
con... | 69aca82239591a159d22d1bcc0361daba00bd13d | 29,013 |
def maximumWealth(accounts):
"""
:type accounts: List[List[int]]
:rtype: int
"""
res = []
for i in accounts:
res.append(sum(i))
return max(res) | e369f3532e0bca1056bdafbd38570dee9c0e0076 | 29,014 |
def merge_sorted(xs, ys, key=lambda x: x):
"""
Merge two sorted lists.
:param inplace
Insert ys into xs.
"""
i = 0
j = 0
# xs: 5 6 7 8
# ys: 1 2 3 4 5 9 10 11
# zs = []
zs = [None]*(len(xs) + len(ys))
m = 0
while i < len(xs) and j < len(ys):
... | d68cecd81384419e0691f2820efc0acef8d494e9 | 29,015 |
def to_snake_case(string: str) -> str:
"""Quick function to return snake_case from camelCase."""
fmt: list[str] = []
for character in string:
if character.isupper():
fmt.append(f"_{character.lower()}")
continue
fmt.append(character)
return "".join(fmt) | 14bfd281c748af1ae3ad8522705d43865f73e4bb | 29,017 |
def __api_reverse_suffix(path):
"""Return the normalized suffix of a url without any api information so that the correct version can be added."""
if path.startswith('/api/'):
components = path.split('/', 3)
if len(components) >= 4 and components[2].isdigit():
return '/' + components[... | 57534f79a8162769a6a236d5b4df307021d3b573 | 29,019 |
def _capitalize_first_letter(c):
"""Capitalize the first letter of the input. Unlike the built-in
`capitalize()` method, doesn't lower-case the other characters. This helps
mimic the behavior of `proto-lens-protoc`, which turns `Foo/Bar/BAZ.proto`
into `Foo/Bar/BAZ.hs` (rather than `Foo/Bar/Baz.hs`).
... | d5370fd75d7b8a1f566052b9843981a0d3b71951 | 29,021 |
def dbt_cloud_job_factory(job_specs, **kwargs):
"""
Update keywords in job_specs with values that can be templated
"""
job = job_specs
job["id"] = None
job["state"] = 1
job["generate_docs"] = True
for key, val in kwargs.items():
job[key] = val
return job | 70686e701968aba9b9d977a1eccc77d1818241a2 | 29,025 |
def GenerateBlock(group):
"""group is a list of (name, value) pairs in which all values have the
same Most Significant Byte.
Prefix the list with, and insert dummy (name, value) pairs so that
value % 256 = position in the list for all values.
Example input:
[
("GL_FOO", 0xcc02),
("GL_BAR", 0xcc03),
("GL_B... | d22e6223ede2c60f16f9716aefe1fbc9ac928478 | 29,026 |
def determine_prepend(vid_path):
"""
Create the string to prepend to the file name.
Parameters:
vid_path - full path name to video directory
Returns:
prepend - string to prepend to filename.
"""
vid_1 = vid_path.rstrip('/').split('/')[-1].split('(')[0]
vid_2 = vid_path.rstri... | 8f0d18d8c88b26039fea27a152995685f74d8769 | 29,027 |
def get_fprimer_percent_aln(fprimer, percent_alignment):
"""
Gets the len of the fprimer and calculates minimum percent alignment
based on user input of maximum alignment between 2 primers allowed.
See percent alignment help for info.
Args:
fprimer (str): the forward primer
Returns:
... | 07316dabe0cfc12606bf6caddb8cee58a26534f1 | 29,028 |
def linearEOS(S,S0=1.0271,beta=1.0,RHO0=1000.0):
"""
Linear equation of state
Returns density from salinity and/or temperature
"""
return RHO0 * ( beta * (S-S0) ) | 51b23beff235905f0aa107e148121860c70a5de8 | 29,029 |
from typing import Tuple
def get_report_format_types() -> Tuple:
"""
Get all graph summary report formats supported by KGX.
Returns
-------
Tuple
A tuple of supported file formats
"""
return 'yaml', 'json' | fd3626a21551734179eaeef5423267c302c31013 | 29,030 |
import re
import collections
def cmd_output_split_parser(out, columns=(), starts_at=0, stops_at=0, split_re=r'\s+', column_info_at=-1,
start_after_columns_line=False):
""" Function to parse the output from a command in a shell
:param out: list with the values separated by split_r... | 4d64fca8ff5cb71795a4ae1d79b0c31132b85e05 | 29,031 |
def dictdict_to_listdict(dictgraph):
"""Transforms a dict-dict graph representation into a
adjacency dictionary representation (list-dict)
:param dictgraph: dictionary mapping vertices to dictionary
such that dictgraph[u][v] is weight of arc (u,v)
:complexity: linear
:returns: tuple with... | 4dbd8f57230ba1a94a3eb861dddb3b9f35b2a80e | 29,032 |
import os
def get_ps_includes():
"""
Add directory to list as required
"""
polysync_install = os.path.join('/', 'usr', 'local', 'polysync')
polysync_include = os.path.join(polysync_install, 'include')
polysync_pdm = os.path.join(polysync_install, 'pdm')
polysync_deps = os.path.join(polysyn... | 2cda9a73dbd01abef1c2ea1aeb151c9073a7417a | 29,033 |
import json
def get_host_osd_map(cls):
"""
Method to get the OSDs deployed in each of the hosts
Args:
cls: cephadm instance object
Returns:
Dictionary with host names as keys and osds deployed as value list
"""
out, _ = cls.shell(args=["ceph", "osd", "tree", "-f", "json"])
... | 2ce441001814b1fbdd00b32255f3365ade8a5ad5 | 29,034 |
def bool_formatter(attr):
"""Format a boolean into a more readable format
Args:
attr (bool): a boolean attribute
Returns:
str: the string "True" or "False", depending of the boolean value of the given
attribute.
"""
return str(attr) | b263320919a13d3f870b7474fbf1f371ef375fe2 | 29,037 |
import yaml
def read_cfg(cfg_file):
"""
Read configurations from yaml file
Args:
cfg_file (.yaml): path to cfg yaml
Returns:
(dict): configuration in dict
"""
with open(cfg_file, 'r') as rf:
cfg = yaml.safe_load(rf)
return cfg | ee44f0f6310240ea5e5d56ebe2ce68fabeb9dcec | 29,038 |
def after_p(text, meta):
"""Even if there are no save_vars, we will add some standard info
about the build, so user can turn it off with 'save_var: False'
"""
return meta.get('build_strings', '[]') != False | b1388754561a8b75265c332cd41eddf0a00b9ffa | 29,039 |
def intersection(bb1, bb2):
""" Calculates the Intersection of two aabb's
"""
min_w = min(bb1[2], bb2[2])
min_h = min(bb1[3], bb2[3])
if bb1[0] < bb2[0]:
leftbb, rightbb = bb1, bb2
else:
leftbb, rightbb = bb2, bb1
if bb1[1] < bb2[1]:
topbb, bottombb = bb1, bb2
el... | 368177cc00fcfff507198f39be3184fc2eed1855 | 29,040 |
import functools
import time
def get_dura(func):
"""获得函数的运行时间"""
print('begin')
@functools.wraps(func)
def wrapper(*args, **kwargs):
s_t = time.time()
ret = func(*args, **kwargs)
print("spend time:{} s".format(time.time() - s_t))
return ret
return wrapper | 401a94172d09491b271ea175affe861265005df9 | 29,043 |
def find_bgn_fin_pairs(locts):
"""Find pairs of [bgn, fin] from loctation array
"""
if len(locts)==0:
return []
else:
bgns = [locts[0]]
fins = []
for i1 in range(1, len(locts) - 1): # range from locts[1] to locts[-2]
if locts[i1] - locts[i1 - 1] > 1:
... | 96eae4eb08fa3cdf951ec4f70149660517c70f86 | 29,044 |
def WIFEXITED(status):
"""Return ``True`` if the process exited using the :manpage:`exit(2)` system call,
otherwise return ``False``."""
return False | 6d5364bb9ec5399986223f338a68bf2230252dcb | 29,045 |
def any_invalid_file_path(any_invalid_directory_path):
"""Invalid file."""
return any_invalid_directory_path / "i-am-not-a-real-file.txt" | c3a2831a429f820bfbd7f8b6cf8a5c66fc89d196 | 29,046 |
import requests
def get_owner_to_roster(player_id_to_custom_id, roster_id_to_owner, league_id, week):
"""
Gets a map of the owner team name to the roster players
Also determines which two teams are in each matchup by getting a map of
matchu pid to the two owners playing the game
"""
owner_to_r... | 708a8aa30f347ce278876b44bb7d6eca8bc17530 | 29,047 |
def prds_worked_weekly_idx_rule(M):
"""
Index is (window, tour type, week) if more than one shift length
in tour type.
:param M: Model
:return: Constraint index rule
"""
return [(i, t, w) for (i, t) in M.okTourType
for w in M.WEEKS
if len(M.tt_length_x[t]) > 1] | 478182485e9bd199550172cf54856d5d867ad010 | 29,048 |
def string_to_type(string):
"""Convert user input to types.
Useful for passing user input to ParseKey. Accept str, int, float, or bool.
"""
if string.lower() in ["string", "str"]:
data_type = str
elif string.lower() in ["float", "number", "decimal"]:
data_type = float
elif stri... | 71099e95609a6fa26d0bc36f7fa5d63d18ad858a | 29,050 |
def notas(*n, sit=False):
"""
=> A função analisa as notas de um número não fixo de notas
:param n: notas dos alunos (Tupla);
:param sit: Booleano para definir aparição ou não da situação de cada aluno;
:return: retorna a quantidade de notas cadastradas, maior e menor nota, média, situação e a situa... | 262e2b9a574f1f9119c1876415cfdaff8b3b53b5 | 29,051 |
def provides_facts():
"""
Doesn't really provide any facts.
"""
return {} | 61d68007ad7b182116ff0d3f86ac3311e151313b | 29,052 |
def create_data_model():
"""Stores the data for the problem."""
data = {}
data['time_matrix'] = [
[0, 5.6, 8, 12.8, 17.4, 13.8, 13.7, 3.4, 4.2, 11, 16.6, 10.4, 18.1, 44, 7.4, 2.4, 17.8],
[5.6, 0, 4.7, 17.2, 2.4, 12.4, 12.8, 7.5, 8.8, 10.1, 16.4, 9, 15.9, 37.4, 11.9, 6.5, 22],
[8, 4.7, 0, 19.5, 3... | e29847ba9566819374baece4a01af2227f0a2b22 | 29,053 |
def ngramname(n):
"""Return the name of the nth n-gram"""
ngrams = ['bigrams', 'trigrams']
return ngrams[n] | b8ecbb832319824ef85f49528f59791fa8ecec40 | 29,054 |
def inverse_lagrange(x, y, ya):
"""Given two lists x and y, find the value of x = xa when y = ya, i.e., f(xa) = ya"""
assert(len(x) == len(y))
total = 0
for i in range(len(x)):
numer = 1
denom = 1
for j in range(len(x)):
if j != i:
numer *= (ya - y[j])
denom *= (y[i] - y[j])
... | 12a70d7fe78438de17f5430562e66b0f4a40ce63 | 29,055 |
def pt_txt_replace (firstname, surname, pt_txt,
redact_message_fname = 'XXXfirstnameXXX',
redact_message_sname = 'XXXsurnameXXX'):
"""
FACTORISING FUNCTION
replaces firstname and surname in pt_txt with default redact messages.
"""
pt_txt_fnamefilter = pt_txt.... | f8786a19789a6ef987d1db1190a0dde2aaf7b93f | 29,057 |
import os
def get_size(file):
"""
get file size, in megabytes
:param file:
:return: size of file
"""
size_in_bytes = os.path.getsize(file)
size_in_megabytes = size_in_bytes / 1000000
return size_in_megabytes | 1dd21941cf6ff3bd4b2a36b2b64bddaddb5a2dd8 | 29,060 |
def primary_key(data_base, key, key_value):
"""Check the primary key value duplicate or not
Make sure the primary key of the database is unique, check if the primary
key value has been existed in the database.
Args:
data_base (dict): The data base you want to check
key (str): The prima... | 3858b1ea24d86bf9fc63bfdc768686ab0453189e | 29,061 |
def letter_swap_rules():
"""
Define a subcategory of rules consisting of long-s replacement and other common mismatches.
This rules must be absolute, meaning we should never add a mistake where there were not when we apply them.
"""
letter_swap_dict = dict()
f_to_s_dict = {"Préfident":... | 80d56869bbfc2b032120a58eec3b19b952a6b84a | 29,063 |
def cm2nm(E_cm):
"""Converts photon energy from absolute cm-1 to wavelength
Parameters
----------
E_cm: float
photon energy in cm-1
Returns
-------
float
Photon energy in nm
Examples
... | ff7034356a42f01e1c876d0983e581b8c6860dd3 | 29,065 |
def render_chart(word_list):
"""
Renders a bar chart to the console. Each row of the chart contains the frequency
of each letter in the word list.
Returns:
A dictionary whose keys are the letters and values are the freqency (N) of the
letter. The value is a string co... | 7d004d7a3ca61151e9b58b68aa769fdb8c3ab98e | 29,066 |
def clean_popest(table):
"""Cleans the population estimate data"""
return table[["Code", "All ages"]].rename(
columns={"Code": "geo_code", "All ages": "pop_2020"}
) | ef0b7bb8d9a61709f03889833baba6e3b0ef7a00 | 29,067 |
def has_chr(s):
"""Returns whether the ``str`` starts with ``"chr"``."""
return s.startswith("chr") | 43b6e00a3deefe9d88cb7c74413eeb94a3ec6856 | 29,068 |
def event_type(play_description):
"""
Returns the event type (ex: a SHOT or a GOAL...etc) given the event description
:param play_description: description of play
:return: event
"""
events = {'GOAL SCORED': 'GOAL', 'SHOT ON GOAL': 'SHOT', 'SHOT MISSED': 'MISS', 'SHOT BLOCKED': 'BLOCK'... | cefd67ae82a3e22a8f8598218887eb9c6a5ea06c | 29,069 |
def cmr_filter_json(search_results, request_type="application/x-hdfeos"):
"""
Filter the CMR json response for desired data files
Arguments
---------
search_results: json response from CMR query
Keyword arguments
-----------------
request_type: data type for reducing CMR query
Ret... | 757953aabe2a83040f8e2e206396b80076288242 | 29,070 |
import re
def version_as_list(version):
"""
Returns a list of the integer components of the supplied version string.
Components are separated by , or . characters
"""
rv = []
for val in re.split("[.,]", version):
if val:
rv.append(int(val))
else:
rv.app... | 1cd4073fd0a127b9f833953a0a8d7b8555e3b38c | 29,071 |
import imp
def check_modules_installed(modules:list):
"""Checks if the given modules are installed
Returns list of not installed module
"""
not_installed_modules = []
for module_name in modules:
try:
imp.find_module(module_name)
except ImportError as e:
# W... | 8b6df1124467132dea9a1548adadd7a6d52606fc | 29,072 |
def expandValues(inputs, count, name):
"""Returns the input list with the length of `count`. If the
list is [1] and the count is 3. [1,1,1] is returned. The list
must be the count length or 1. Normally called from `expandParameters()`
where `name` is the symbolic name of the input.
"""
if len(in... | 6e4fb34cccaf627c7d8d2fedadf35f3ce131d522 | 29,073 |
def rectAt(cen, size):
"""Returns a rectangle of the given `size` centered at the given location.
The coordinates are inclusive of borders."""
x, y = cen[:2]
w, h = size[:2]
return [x-w//2, y-h//2, x-w//2+w-1, y-h//2+h-1] | 98fff599be25853eeb488dac58a22ec2f7caaa66 | 29,074 |
import signal
def RelaySignal(handler, signum, frame):
"""Notify a listener returned from getsignal of receipt of a signal.
Returns:
True if it was relayed to the target, False otherwise.
False in particular occurs if the target isn't relayable.
"""
if handler in (None, signal.SIG_IGN):
return Tr... | 4c4b8c2cd5af7ce4981321571747cab20a5bc01c | 29,075 |
import re
def parse_show_snmp_system(raw_result):
"""
Parse the 'show snmp system' command raw output.
:param str raw_result: vtysh raw result string.
:rtype: dict
:return: The parsed result of the show snmp system\
command in a dictionary of the form
::
{
'Syst... | 3132ab88965bc04198a7d9c6deb290d4ab035280 | 29,076 |
def _setup_app_blueprints(app):
"""
Setup application blueprints.
:param mydojo.base.MyDojoApp app: MyDojo application to be modified.
:return: Modified MyDojo application
:rtype: mydojo.base.MyDojoApp
"""
app.register_blueprints()
return app | bd6b5bf9229bfb09b83899baebb9a4f378b70087 | 29,078 |
import requests
def login_session(email, password):
"""
Returns a requests session with FPL login authentication.
:param string user: email
:param string password: password
"""
session = requests.Session()
# initial request to retrieve csrftoken
session.get('https://fantasy.premierle... | ebc50f75c9cbc14b6bd9c0a554c855e968c169c9 | 29,079 |
def required_columns(row_to_add, wanted_keys):
"""
:param row_to_add: Contains the rows from the input file.
:param wanted_keys: List of required column header names to be displayed at the end.
:return: Dict of keys,values formatted data.
"""
required_keys = dict((k, row_to_add[k]) for k in wan... | 8643a592662939cf8b00f009c4dc3f87d1df4e6c | 29,080 |
def _parse_line(s):
"""Parses a line of a requirements.txt file."""
requirement, *_ = s.split("#")
return requirement.strip() | 5c0c96898c288a7c358bf978a4415c17c7fb19c4 | 29,081 |
import requests
def download_content():
"""Downloads contributor data from github."""
resp = requests.get('https://api.github.com/repos/kubernetes/kubernetes/stats/contributors')
resp.raise_for_status()
data = resp.content
return data | 043830e12e2ecf3ad4e5f585f6411079a36c52dc | 29,083 |
def get_cpgs_orig_methylated(df, cells_to_use):
"""
Get a list of cpg which where methylated to begin with using a specific set of cells
:param df: The df to work on
:type df: pd.DataFrame
:param cells_to_use: A list of cells to use, should match the rows names of the df
:return: The indexes of ... | 569b0dcf2befd521a5328108ec725f35fdb60c7a | 29,084 |
import torch
from typing import Tuple
def calculate_gae(
values: torch.Tensor,
rewards: torch.Tensor,
dones: torch.Tensor,
next_values: torch.Tensor,
gamma: float,
lambd: float
) -> Tuple[torch.Tensor, torch.Tensor]:
"""
Calculate generalized advantage estimator... | be8deb444fdc8c708deab9e638ac9a223f85aba6 | 29,085 |
import platform
import os
from pathlib import Path
def detect_store_path(bl_check_path_exist=True, srt_sub_path=None, st_local_path=None):
"""Detects checks if program is running on an AWS Linux Instance
In our case, all code that run on AWS linux are running inside conda containers.
If running on contai... | ed13a1380b5f50ab6a364461852ce7c08fc492a6 | 29,086 |
def get_ema_vars(ema, model):
"""Get ema variables."""
if ema:
try:
return {
ema.average(v).name: ema.average(v) for v in model.trainable_variables
}
except: # pylint: disable=bare-except
ema.apply(model.trainable_variables)
return {
ema.average(v).name: ema.aver... | 4fb63ebc85e627e8a246fbdaa0c35002bcd808bb | 29,087 |
def any_feature(tidy, replace={}, invert=False):
"""This method...
.. warning: Might have an inconsistent behaviour when
a replace value is included. Ideally keep
just as a boolean outcome.
Parameters
----------
tidy:
replace:
invert:
Returns
------... | 882d6e3d5980d1b5b5ada32334a40f2bd044e6a7 | 29,088 |
def enclose_string(text):
"""enclose text with either double-quote or triple double-quote
Parameters
----------
text (str): a text
Returns
-------
str: a new string with enclosed double-quote or triple double-quote
"""
text = str(text)
fmt = '"""{}"""' if len(text.splitlines())... | c0ce87633da75b019f2b59fa561172e851283fa8 | 29,089 |
def _set_PhiScalMARJ_grid_placement(fig, gs):
"""
using the add_subplot method create the following fig layout
+-------------------------------+
| | |
| | |
| M vs AR | J vs M |
| all_ax[1] | all_ax[2] |
| ... | 38be5b8ecb14861c29cf565f991a7661a10cc808 | 29,090 |
def summarise_app(app):
"""Return a string the summarises the important information about the app"""
state = app["state"]
if state != "Installed":
state = state.upper()
pin_status = "Pinned" if app["is_pinned"] else "NOT PINNED"
known_status = "UNKNOWN" if app["application_version"]["is_un... | 547cf213843e1aa635def247c23e6d353d1ceaaf | 29,091 |
def collapse_redundant_nodes(tree):
"""
function takes Tree object, tree, and counts number
of tips per clade, if the number of
tips in the current clade == the
number of tips in the previous clade
the clade is collapsed because it is
redunant. Rendundant clades can arise
because of us... | 947006892381d44d740938d7a38e45b6fb24d7ac | 29,092 |
def has_key(attr, key_name):
"""
dict key
:param attr:
:param key_name:
:return:
"""
for it in attr.keys():
if it == key_name:
return True
return False | fc959d47d0bb582ed7c891090d48637ef33f279a | 29,093 |
import math
def getExpectationValue(bitScore: float, searchSequenceLength: int, foundSequenceLength: int, numberOfSequencesInDatabase: int) -> float:
"""
Returns the E-value of a single query in a sequence database.
Parameters
----------
bitScore : float
Comparison score, normalised t... | 01c8440c4be67ada93daf4ebbb519e9a550ae34a | 29,095 |
from typing import Any
def get_type_name(t: Any) -> str:
"""Find the name of a type passed. It will look in sequence for "__name__" and "_name" and if both fail it will
take the str(t)
Args:
t: Any object
Returns:
String: string with the name of the type
"""
return getattr(t,... | bfd81cc4cb93dc636e93c44f7cd94706724d64c0 | 29,096 |
def mi2km(mi):
"""
Converts to miles to kilometers.
"""
if mi == None:
return None
return mi * 1.60934 | 2000ad884b375c525da5d11a9b948354b170d59d | 29,097 |
def construct_path(relation, start, end):
"""
Constructs a path between two actors using a dictionary of child-parent
relationships. Returns a list with actor IDs.
"""
path = [start]
while end != start:
path.append(relation[start])
start = relation[start]
path.reverse... | f1cfb7cd1544406a32c2934956020a4ab768a7e0 | 29,099 |
def strfdelta(time_delta, fmt):
"""
A way to convert time deltas to string formats easily.
:param time_delta: timedelta object to convert
:param fmt: string format to output
:return: String form of timedelta
"""
d = {"d": time_delta.days}
d["h"], rem = divmod(time_delta.seconds, 3600... | e9b2711dc09e4f0b6087938e9790d11adb5908cb | 29,100 |
import shutil
def find_installed_player():
"""Find an installed player."""
# find installed player
if shutil.which("ffplay"):
player = ["ffplay", "ffplay", "-nodisp", "-loglevel", "panic"]
elif shutil.which("cvlc"):
player = ["cvlc", "cvlc"]
elif shutil.which("mplayer"):
pl... | 36b15abac37c3fbbd7da5ecb45d58c8c352c62eb | 29,101 |
def _sleep_time(iter):
"""Return the time-to-sleep for the n'th iteration of a retry loop.
This implementation increases exponentially.
:param iter: iteration number
:returns: number of seconds to sleep
"""
if iter <= 1:
return 1
return iter ** 2 | 6abd614bbabc872758049ea35d9ee0ebafd0f2ba | 29,102 |
from typing import OrderedDict
def tag_pairs(tags, index=False):
"""
Return an OrderedDict whose keys are pairs of tags in the format "tag1:tag2"
and whose values are a tuple of the two tags used to construct each key, or
a tuple of the indices of the two tags in the original tag list, if ``index``
... | 97ce0a2815b5542275eb5b15c6b3ff434c456a6e | 29,103 |
def add_saved_artists(auths, artists):
"""
Adds/follows artists.
:param auths: dict() being the 'destinations'-tree of the auth object as returned from authorize()
:param artists: list() containing the artists IDs to add to the 'destinations' accounts
:return: True
"""
for username in auths:... | aeaca1469ab7b74a22a838f2b193d40f75e6461f | 29,104 |
def label_id_map(images_info, num_class):
"""
将图像按照类别分组
:param images_info: 图像字典{'img_path': 图像路径,'label': 类别,'img_id':图像id}
:param num_class: 类别数
:return:
"""
# 初始化
label_id_dict = dict()
for i in range(num_class):
label_id_dict[i] = []
# 逐个图像归类
for i in range(len(i... | 3f910818990c9a9f054e9cc94c014868ff657a8f | 29,105 |
import sys
def is_windows(min_release=None, max_release=None):
""" True if OS is WINDOWS (between min / max_release) """
global _RELEASE
if sys.platform != 'win32':
return False
if _RELEASE is None:
_RELEASE = sys.platform.release()
if min_release is not None and int(_RELEASE) ... | 5339f0a8a489f1f56df0dea67a50415da8a08c1b | 29,108 |
import io
def parseChart(chartFN):
"""
@return chartDict
��� ==> g,a
��� ==> k,i
������ ==> k,ya
Similarily for Hiragana
@setrofim : http://www.python-forum.
org/pythonforum/viewtopic.php?f=3&t=31935
"""
with io.open(chartFN, "r", encoding="utf-8") as fd:
chart = fd.re... | 61fbd7b2342a553fb0e28d9dfc9eb037eafd2ba9 | 29,109 |
from typing import Dict
def dict_is_subequal(data: Dict, full_data: Dict) -> bool:
"""检查两个字典是否相等,忽略在 `full_data` 中有,但 `data` 里没有提供的 key"""
for key, value in data.items():
if key not in full_data:
return False
if value != full_data[key]:
return False
return True | 59c19b538554eaa4b7e6e1bf78f812723fff7b67 | 29,112 |
def lily(the_note):
"""Sets Lilypond accidentals."""
s = the_note.note.lower()
if the_note.accidental == '+':
s += 'qs'
elif the_note.accidental == '#':
s += 's'
elif the_note.accidental == '++':
s += 'tqs'
elif the_note.accidental == '-':
s += 'qf'
elif the_note.accidental == 'b':
s += 'b'
elif the_n... | e04c14bb13d91ccec5a83de36436aec7d55a7e30 | 29,113 |
import ast
def get_test_functions(filename):
"""
Returns a list of test functions.
ie. [{'id': 'test_empty_array', 'line': 1}, ...]
"""
with open(filename) as f:
read_data = f.read()
module_ast = ast.parse(read_data)
funcs = []
for stmt in module_ast.body:
if isinsta... | 2936e3a1e6759837a3a543f62727fb26303cb758 | 29,114 |
def pretty_ti_txt(line):
"""Make given TI TXT line pretty by adding colors to it.
"""
if line.startswith('@'):
line = '\033[0;33m' + line + '\033[0m (segment address)'
elif line == 'q':
line = '\033[0;35m' + line + '\033[0m (end of file)'
else:
line += ' (data)'
return... | 91fc1cfb5dba9467ca58da3154e7343d9845f44a | 29,116 |
import networkx
def draw_graph(g: networkx.Graph, fname: str):
"""Draw a graph using pygraphviz and return the AGraph object.
Parameters
----------
g :
A graph to draw.
fname :
The name of the file to write the graph to.
Returns
-------
:
A graphviz graph obje... | 761eeb2d44e41ecf704f4aa09eb5e30fbe665030 | 29,117 |
def sfc_sw(swup_sfc, swdn_sfc):
"""All-sky surface upward shortwave radiative flux."""
return swup_sfc - swdn_sfc | de51cf2b3ad410788e041117df01e19e959e3abe | 29,119 |
def read_runlist(filepath):
"""Read a list of runs from a txt file
Parameters
----------
filepath : `str`
The input file with the list of runs.
Each line should contain raft and run number, e.g., RTM-004-Dev 6106D
Returns
-------
outlist : `list`
A list of tuples wi... | de106013ef1cb1de32ed7120b2c5aeab2bf1aafb | 29,120 |
import pathlib
def is_pardir(pardir, subdir):
"""
Helper function to check if the given path is a parent of another.
"""
return pathlib.Path(pardir) in pathlib.Path(subdir).parents | c7b14ef578f24f2565ae2e88aff248eea3abf963 | 29,121 |
def parse_tags(src_mappings: list) -> tuple:
"""Parse tags.
If there are any tags at the end, an no-op instruction will be added.
"""
dst_tagged = {}
dst_mappings = []
dst_cursor = 0
last_tagged_line = -1
last_source_line = -1
for (src_cursor, src_line) in src_mappings:
try... | c871bc4511f1f37c4ffec4768f4ced320183e676 | 29,123 |
def merge_top(a_list, accessor):
"""
multiple weights can produce the same top-score, this function merges all top weights.
:param a_list:
:param accessor:
:return:
"""
a_list.sort(key=lambda x: x['score'], reverse=False)
result = a_list[0]
weights = []
result['weights'] = wei... | 1f96bd3c9fd688badbcd4948c9e71b3728934198 | 29,124 |
def energy(layer, data):
"""
Finds total E deposited in a given layer for each event.
"""
return data[layer].sum(axis=(1, 2)) | d8f73ac1b9fb9a03fdb89420f434a03306872d8a | 29,127 |
from os.path import dirname
import unittest
def suite():
"""Returns unittest.TestSuite of tests.
"""
py_dir = dirname(dirname(__file__))
return unittest.defaultTestLoader.discover(py_dir, top_level_dir=dirname(py_dir)) | 6e2a13e474e142c181456a419c3bfefa44e35e44 | 29,128 |
def logPPDNA(misfits):
""" Calculate the log-posterior probability density function of model
This routine converts the input data array to a log posterior probability density
function.
For example if the input data for each model is a simple sum of squares of residuals weighted by
a priori... | 49db6cb6148ab094ea848a7e1f2ee4f07df451b6 | 29,129 |
import six
def _get_query_dict(**kwargs):
"""Returns query dict by kwargs.
Skip None-values, but keeps False etc.
>>> res = _get_query_dict(url=None, test='a', page=True, full=False)
>>> res == {'test': 'a', 'page': True, 'full': False}
True
"""
def __get_quey_dict(**kwargs):
for k... | 6d4ba22bb82853356765498f45bd7fda82000921 | 29,130 |
def _extract_time_from_disk(parent_ref, name, is_matrix=False):
"""
This is for handling Matlab save vs Python save when we get to that point.
"""
temp = parent_ref[name].value
if is_matrix:
wtf = temp
else:
# Assuming vector, need to fix for eigenvectors
if temp.shape[... | 8a398a6853c482f0ffe6ff85230e0745518c46b3 | 29,131 |
import csv
def read_data_from_csv():
"""
Function to read CSV data and pass it to test functions.
:return: test_data_zip - list
"""
test_data_zip = []
csv_file_path = '/Users/ahamouda/study_projects/API_testing_CI_pytest/request_basics/exercises/ex02_csv_test_date.csv'
with open(csv_file_... | cd5024fb0d93431de0d9c23e583266f74a54bece | 29,132 |
import subprocess
import re
def find_hostname(SETTINGS, file_name):
""" """
hostname = 'HOSTNAME-IS-UNKNOW'
command = ('git --no-pager diff HEAD^ HEAD -U$(wc -l '
'{file}) {file}').format(file=file_name)
output = subprocess.run(command, shell=True,
stdout=subpr... | 421d63b3228b0fce0dc6d1db0d24725ad6516208 | 29,134 |
import time
def time_strptime(*args, **kwargs):
"""Version of time.strptime that always uses the C locale.
This is because date strings are used internally in the database, and
should not be localized.
"""
return time.strptime(*args, **kwargs) | 5410a4b4154471834f70818bf2a0a2356bdc25dd | 29,135 |
import torch
def beta_regularizer(mean, std, lmbda, param, function=None):
"""Beta-distribution regularizer for parameters in range [0, 1].
Functional version utilizing closure technique.
Args:
mean (float): Mean of beta distribution.
std (float): Standard deviation of beta distribution.... | ae806508368022c4f45028a6f45c54352526b884 | 29,137 |
import socket
import contextlib
def get_available_port():
"""
:rtype: int
"""
# this relies on the kernel not reusing previously assigned ports immediately
socket_fd = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
with contextlib.closing(socket_fd):
socket_fd.bind(('', 0))
... | 992e32b903801cb6e3498c781df7578ba58434e9 | 29,138 |
def prepare_text(text):
"""Remove unnecessary spaces and lowercase the provided string"""
return text.strip().lower() | 337859656670fa9bcd7b4296318ea9a3c4b730f1 | 29,139 |
import os
def __get_encoded_string(path):
"""
get the encoded authorization string
"""
with open(path.format(os.getcwd())) as log:
return log.read() | 9db9a01981ccc1fbac6c0a28ba92fa1028452647 | 29,140 |
def encrypt(key,mensaje):
"""Funcion que cifra el mensaje mediante una funcion XOR con la llave. Retorna un ciphertext"""
cipher=""
for i in range(len(mensaje)):
t = mensaje[i]
k = key[i%len(key)]
x = ord(k) ^ ord(t)
cipher += chr(x) #Vamos añadiendo los valores producto del XOR al cipher.
retur... | a7ded9223ca8291d2f5cc748bc0e26890bd1d42c | 29,141 |
import torch
def pca(X, k, center=True):
"""
Principal Components Analysis impl. with SVD function
:param X:
:param k:
:param center:
:return:
"""
n = X.size()[0]
ones = torch.ones(n).view([n, 1])
h = ((1 / n) * torch.mm(ones, ones.t())) if center else torch.zeros(n * n).view... | e2abebfeecb48543f645581820fd095c3718f2fb | 29,143 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.