content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def get_pubkey(elem) -> str:
"""Returns the primary key element from a tag"""
return elem.get('key') | 2f11661dee73d858dbd8c37b5045442c192f8799 | 34,525 |
def getcoroutinelocals(coroutine):
"""
Get the mapping of coroutine local variables to their current values.
A dict is returned, with the keys the local variable names and values the
bound values."""
frame = getattr(coroutine, "cr_frame", None)
if frame is not None:
return frame.f_local... | 8fdc3a968b1c0eeaf503ba6c5ab167f22dcb54f8 | 34,526 |
from unittest.mock import call
def info_default(proc, var):
"""wrapper for 'info default'"""
return call("safe_info_default", proc, var, to=tuple) | 14eb8e0457d592045274df279cd4846cfdb073ed | 34,527 |
import re
def get_urls(clean_text):
"""
returns a link of potentially clickable emails
"""
for text in clean_text:
urls = re.findall('http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+',
text)
return urls | 5b6199a2e187e81af8e178fef2ded55c181b9faf | 34,528 |
def prepare_credential_content(filename, itype=False, use_file=True):
"""
Format strings for inclusion in radl templates
"""
if use_file:
with open(filename) as file_in:
content = file_in.readlines()
else:
content = []
for line in filename.split(b'\n'):
... | 9a685636b6a057bef7847f2a88c269e818c2bb17 | 34,529 |
def round_tat(num):
"""Changes the turnaround time from a float into natural language hours + minutes."""
remain = num%1
if num.is_integer():
if int(num) == 1:
return str(int(num)) + " hour."
else:
return str(int(num)) + " hours."
else:
if num < 1:
return str(int(remain*60)) + " minutes."
elif num-... | cccf14355b7fc090df855a45b88e9b8562449f9a | 34,530 |
import idna
def domain_to_idna(passed_domain):
"""
Change unicode domain to bytes
:param passed_domain: bytes or str object
:return: bytes domain in idna format
"""
# make sure we are unicode
if not isinstance(passed_domain, str):
# domain is already bytes. Return as-is
ret... | 7bd1cceb3e46134da5b574a668b7870bc8d3483e | 34,531 |
def score_pop(
population_value, min_population_acceptable=10, max_population_acceptable=30
):
"""
:param population_value: population value to be scored
:param min_population_acceptable: minimum population value in the scoring range (saturates at 0)
:param max_population_acceptable: maximum populat... | 074837e892cea618705139513ea03889aa76fac3 | 34,532 |
from typing import Mapping
from typing import List
def get_docstring(sections: Mapping[str, List[str]]) -> List[str]:
"""Get (unindeted) docstring from docker-compose <cmd> --help. Use general and usage section.
:param sections: Output from `collect_help_lines`
"""
lines = sections["general"]
if u... | e0d811fcd037b712288692103eccd71fc9c8dfad | 34,533 |
import random
def cpu_choise():
"""This function randomly selects five of the seven
colors and returns them as a list."""
all_color = ("green","red","blue","pink","yellow","orange","gray")
chois_color = random.sample(all_color,5)
return chois_color | 3a1e8d00677d1c3eeb0923b064c91d74bc7ef1b3 | 34,534 |
def _first_upper(k):
"""Returns string k, with the first letter being upper-case"""
return k[0].upper() + k[1:] | f28bfa9f6457c4c0b3d75704e44486f31f247831 | 34,535 |
def last_third_first_third_mid_third(seq):
"""with the last third, then first third, then the middle third in the new order."""
i = len(seq) // 3
return seq[-i:] + seq[:i] + seq[i:-i] | e09a4ea8d5f59b6d98b94b80290eeac148594a1d | 34,536 |
def has_samples(args):
"""Returns whether there's some kind of sample option in the command
"""
return args.sample or args.samples or args.sample_tag | 47728a442d90538e72f47b72882ba22dd102d61a | 34,537 |
def graph_order(graph):
"""Get graph order."""
graph = graph.get_vertices()
order = len(graph.keys())
return order | 1ea6fea10bdd80033a67fac1e5326f6a80239c58 | 34,538 |
def find_all_indexes(text, pattern):
"""Return a list of starting indexes of all occurrences of pattern in text,
or an empty list if not found.
Time Complexity: O(n) where n is the number of characters between index 0 and our max_index
Space Complexity: O(n) where n is the number of items in the array h... | 2dbcb5101053a5255f8d7a03cd87b5b557e0df04 | 34,539 |
def remove_close(df, primary_distance_cutoff):
"""
This code will take what should ideally be a merged dataframe and cut any rows
out according to the difference in their aa1_loc and aa2_loc columns. Which is
to say, it will get rid of comparisons between amino acids that are too close
to each other... | 3907f1328d66f3d8cff945b2ad8ec2786f9720f2 | 34,540 |
def reload_attribute(model_instance, attr_name):
"""Fetch the stored value of a model instance attribute.
:param model_instance: Model instance.
:param attr_name: Attribute name to fetch.
"""
qs = type(model_instance).objects.filter(id=model_instance.id)
return qs.values_list(attr_name, flat=Tr... | 1bfc60ba34ff4687aae8d5404e545949232f9066 | 34,542 |
import doctest
def doctest_test():
"""run test procedure with doctest"""
# invoke the testmod function to run tests contained in docstring
stats = doctest.testmod()
print(stats)
return stats | ac1d43ac9e712f64e3c0ed076a023d2e5ed4da2c | 34,543 |
import os
def get_jpeg(path):
"""
Returns all JPEG files given a path
:param path:
"""
image_names = []
for f in os.listdir(path):
if f.endswith(".jpg"):
image_names.append(path + f)
return image_names | 5de6ea54f7ebbf561101e37953468fdeace84290 | 34,545 |
import json
def make_json(data_dict, simple=None):
"""Make well formatted JSON for insertion into cascade word docs.
JSON will be enclosed by '$ like: '${"key":"value"}$'
JSON will be on one line (simple) if it contains only one key/value pair, or if
the argument simple==true
"""
if simp... | c7b8400995ed105f88de4bb6c3e22c5b17aedd4a | 34,546 |
import collections
def get_sorted_transitive_dependencies(top, deps_func):
"""Gets the list of all transitive dependencies in sorted order.
There should be no cycles in the dependency graph (crashes if cycles exist).
Args:
top: A list of the top level nodes
deps_func: A function that takes a... | 7e758410c785e7f1b6df0dbd2a3571a402b95641 | 34,547 |
def r1_p_r2(R1, R2):
"""
Calculate the Resistance of a parallel connection
"""
return R1 * R2 / (R1 + R2) | 3c98e8a24020e76b008d151a2611fa85856b8417 | 34,549 |
def enum2str(enumType, enum):
"""
Translates a pokerth_pb2 enum type to a string.
:param enumType: enum type class
:param enum: the enum element of the type
:return: identifier string of enum
"""
return [k for k, v in enumType.items() if v == enum][0] | 46de0fcd78f2e8b450ede050679f9e776b5a0bf9 | 34,550 |
def get_data_from_context(context):
"""Get the django paginator data object from the given *context*.
The context is a dict-like object. If the context key ``endless``
is not found, a *PaginationError* is raised.
"""
try:
return context['endless']
except KeyError:
raise Exception... | 304fd11f75ec72f703e03e7a8431c613a3648f47 | 34,555 |
def window_width(g_core: float, t_in: float, t_out: float, g: float, t_r: float, g_r: float) -> float:
"""
is the calculated winding width if there
x g_core - is the distance between the core and the inner winding in [mm]
x t_in - is the thickness of the inner winding in [mm]
x t_out - is the t... | fd86eeb816c75b8e7d940d5321259c62abc0ec50 | 34,556 |
import yaml
def _parse_top_cfg(content):
"""Allow top_cfg to be YAML"""
try:
obj = yaml.safe_load(content)
if isinstance(obj, list):
return obj
except Exception as e:
pass
return content.splitlines() | acd7e83cd5978873d0eae3fc08c40dba4dd4ef64 | 34,557 |
def build_key_name(app_name, os_name, file_name):
"""
Creates key using app name, os and filename
:param app_name: app name
:param os_name: OS the app is written for
:param filename: the name of the file
:return: S3 bucket key for given app/os/filename combination
"""
return (app_name.... | 845e6c2734ec105c6a9bbcd5032bc7569063c297 | 34,558 |
import re
def name_in_string(string: str, name: str) -> bool:
"""Checks if string contains name.
Args:
string (str): input searchable string
name (str): input name
Examples:
>>> assert name_in_string("Across the rivers", "chris")
>>> assert not name_in_string("Next to a l... | 168abc4ebfd078a2d9220bcea3c0efd2e0e79091 | 34,559 |
def filter_boxes(boxes, skip_ts=int(5e5), min_box_diag=60, min_box_side=20):
"""Filters boxes according to the paper rule.
To note: the default represents our threshold when evaluating GEN4 resolution (1280x720)
To note: we assume the initial time of the video is always 0
Args:
boxes (np.ndar... | 021ce5e60501538e84aa897a70fd2704b651eab9 | 34,561 |
import re
def parse_expression(expr, local_data=None):
""" Parses a math expression into a list """
i = 0
data = []
while True:
if i >= len(expr):
break
if expr[i] == ' ':
i += 1
elif re.search(r'^[\d,.]+', expr[i:]):
number = []
... | 4e426e3e1b04562f44a9183131d4c9fee2ef15a7 | 34,562 |
from typing import Dict
from typing import List
from typing import Set
from typing import Tuple
def _validate_reply(
reply: Dict[str, List[str]], performatives_set: Set[str]
) -> Tuple[bool, str]:
"""
Evaluate whether the reply structure in a protocol specification is valid.
:param reply: Reply struc... | 2243e60edd6497a7f699676be5fe765711db4134 | 34,563 |
def get_contrib_read_ids(indexes, reads):
"""
Takes a set of indexes from assign_reads and the list of read signatures
plus the dictionary mapping signatures to aligned read IDs and returns
the set of corresponding aligned read IDs (BAM query IDs).
"""
hap_read_ids = set()
for read_idx in in... | 1839790b85917bed53675ae43cd04fafedfceea9 | 34,566 |
import os
def is_mp3(path):
"""
Determines whether a file looks like an MP3.
@param str path
The path to the file to check.
@return bool
True if the file seems like an MP3, False if not.
"""
if path.startswith('._'):
return False
if path.lower().endswith('.mp3'):
return os.path.isfile(... | 3a37437efd9c70710c8676eee34e067949bfcfa6 | 34,568 |
from typing import Optional
def _builtin_schema(type_name: str, type_format: Optional[str],
event_name: str, datatype: type) -> dict:
"""
Build type schema for predefined datatypes
"""
schema = {
"type": "object",
"required": [
event_name
],
... | 0ab5cdf1a99dd724ac1894a09551769f400d83e4 | 34,571 |
def scs(qs):
""" Gets the number of occurrences of each state in qs/each unigram in bis """
ss={}
for q in qs:
ss[q]=ss.get(q,0)+1
return ss | 317abacce8f3dcdc49c5b0ea61fca6ddbe4deaaf | 34,572 |
import re
def simple_sql_parse(data, periscope_type):
"""Extract table names used in the SQL code using regex
Args:
data ([type]): [description]
periscope_type (str): 'view' or 'chart'
Returns:
tables_list (array of dict): one table/persicope entity per row
"""
exp = r... | a0b2eb37fe3f1182a42c0906158bfdb6609fe1df | 34,573 |
def use_autoparal(request):
"""
This fixture allows to run some of the test both with autoparal True and False
"""
return request.param | a1116cb2937acf490177fb82055e8dbc7d39e434 | 34,575 |
def default_cost(alignment_matrix, i, j, tokens_1, tokens_2):
"""
Ignore input and return 1 for all cases (insertion, deletion, substitution)
"""
return 1 | ab5c721fad6d6a6cd5f5e7ee3262b0beed8c56e9 | 34,576 |
def summary_stats_from_file(input_file):
"""
:param input_file: The name of the file that has the information in the next manner:
1) A set of measures names separated by tabulator
2) A undefined number of lines with:
classifier name: \t measure_value_0 \t measure_value_1 \t etc.
:return: Sum... | 31933beac52d398266bb0e451766194bb957fccf | 34,577 |
import argparse
def get_arguments():
""" gets command line arguments.
:return:
"""
# init parser:
parser = argparse.ArgumentParser("Downsample ModelNet40 by category.")
# add required and optional groups:
required = parser.add_argument_group('Required')
optional = parser.add_argument... | 599f698cc80bdb4de9f8f61e6e3684fd80d064d9 | 34,578 |
import traceback
def get_loan_budget_details(obj):
"""备用金,费用预算明细
:param obj:
:return:
"""
try:
return obj.LoanBudgetDetails.count()
except:
traceback.print_exc()
return 0 | c6df82ef62f0851fb9d8d690f8344359abd61d69 | 34,581 |
def saved_certificate_to_cnf(file_path):
""" Load a certificate from file
Parameters
----------
file_path :string
Path of the file that contains the certificate fo a cnf
Returns
-------
set[(string,bool)]
The object that represents the loaded... | b8a5b6d327c406fa9f8b1abdac97781f5813208b | 34,582 |
def speaking_player(bot, state):
""" A player that makes moves at random and tells us about it. """
move = bot.random.choice(bot.legal_positions)
bot.say(f"Going {move}.")
return move | 58392931510a86ddf1fd6bdc3402cdf1665241d0 | 34,583 |
def permission_classes(permission_classes):
"""
Specifies authorization requirements.
"""
def decorator(func):
func.permission = permission_classes
return func
return decorator | c0c4af8dc4007e979104f1b77e71af5f1af4337e | 34,584 |
def trim(d, prepended_msg):
"""remove the prepended-msg from the keys of dictionary d."""
keys = [x.split(prepended_msg)[1] for x in d.keys()]
return {k:v for k,v in zip(keys, d.values())} | a7bf495750713a51c74dfd95dbbabcbab76f1910 | 34,587 |
from datetime import datetime
def part_of_day() -> str:
"""Checks the current hour to determine the part of day.
Returns:
str:
Morning, Afternoon, Evening or Night based on time of day.
"""
am_pm = datetime.now().strftime("%p")
current_hour = int(datetime.now().strftime("%I"))
... | 5736b7049924197595341a173e642b8e3ea9e856 | 34,588 |
def format_tarball_url(package):
"""
Creates the url to fetch the tar from github.
>>> format_tarball_url({'owner': 'elm-lang', 'project': 'navigation', 'version': '2.0.0'})
'https://github.com/elm-lang/navigation/archive/2.0.0.tar.gz'
"""
return "https://github.com/{owner}/{project}/archive/{ve... | 44304d62797730de2a4b9bd8dd43d4588b287607 | 34,591 |
def _GetChartFactory(chart_class, display_class):
"""Create a factory method for instantiating charts with displays.
Returns a method which, when called, will create & return a chart with
chart.display already populated.
"""
def Inner(*args, **kwargs):
chart = chart_class(*args, **kwargs)
chart.displ... | 10741f18bf78bb2b7f301e50b7a98306678d6a31 | 34,592 |
import os
def listdir(directory, split_ext=False):
"""Lists directory"""
try:
if split_ext:
return [os.path.splitext(dir_)[0] for dir_ in os.listdir(directory)]
else:
return os.listdir(directory)
except OSError:
return [] | be46d83134eb42f21e602e59480a2219389a22eb | 34,594 |
def update_vcf_motifs_info(outline, names, varscores, refscores, varht, refht,
vargc, refgc, options, chips, col):
"""
Used in conjunction with update_vcf() to add motifs information to the line.
Reduces code maintenance by putting update code in 1 place
Args:
see update_vcf for definit... | a819df250faaf4eb3ef39aa3069f000d941d7d1b | 34,596 |
def generate_big_data():
"""
Generate some data.
The data=True in the job decorator tells jobflow to store all outputs in the "data"
additional store.
"""
mydata = list(range(1000))
return mydata | 9f82ac51bec24986afa395fbfe5ca91904f361f1 | 34,597 |
import glob
def find_file(path):
"""
Search file
Parameters
----------
path : str
Path and/or pattern to find files.
Returns
-------
str or list of str
List of files.
"""
file_path = glob.glob(path)
if len(file_path) == 0:
raise ValueError("No such... | 7f7dad61a2faddd4ab6e6735419abb0b50196d67 | 34,598 |
from typing import List
def parse_tags(s: str) -> List[str]:
"""
Parse comma separated tags str into list of tags.
>>> parse_tags('one tag')
['one tag']
>>> parse_tags(' strip left and right ends ')
['strip left and right ends']
>>> parse_tags('two, tags')
['two', 'tags']
>>> pa... | 7529f0b6746bdfe7996eb4a963ae4e07622183aa | 34,599 |
def bfs(initial_state, step_fn, eval_fn, max_depth=None, not_found_value=None):
"""Bread-first search"""
queue2 = [initial_state]
states = set(queue2)
depth = 0
value = eval_fn(initial_state, depth)
if value is not None:
return value
while queue2 and (max_depth is None or depth <... | d0edf20a9b5899a232cfb2bb1f6f9e6e7ff55c80 | 34,600 |
def encipher_kid_rsa(msg, key):
"""
Here ``msg`` is the plaintext and ``key`` is the public key.
Examples
========
>>> from sympy.crypto.crypto import (
... encipher_kid_rsa, kid_rsa_public_key)
>>> msg = 200
>>> a, b, A, B = 3, 4, 5, 6
>>> key = kid_rsa_public_key(a, b, A, B)
... | 37ccf5d80e10c5f90e1b2cfb0a085f718ba3d845 | 34,602 |
def _ansible_verbose(verbose_level=1):
"""
Return an ansible verbose flag for a given Cliff app verbose
level to pass along desired verbosity intent.
"""
flag = ''
if verbose_level > 1:
flag = '-{}'.format("v" * (verbose_level - 1))
return flag | 0313b5f7c41858c6d2ecaba2275cb56cd89b628a | 34,603 |
def format_proxies(proxy_host, proxy_port, proxy_user=None, proxy_password=None):
"""Sets proxy dict for requests."""
PREFIX_HTTP = 'http://'
PREFIX_HTTPS = 'https://'
proxies = None
if proxy_host and proxy_port:
if proxy_host.startswith(PREFIX_HTTP):
proxy_host = proxy_host[len(... | f8f8539a1caff91d5ea4cee1159dc2d5916dd3c0 | 34,604 |
import math
def neg_exp_distribute(mean_time, U):
"""
Generate series satisfied negative exponential distribution
X = -mean*lnU
Parameters:
-----------
mean_time: mean time
U: a list as a parameter for negative exponential time
Return:
-------
X: Generated time (interarr... | 680c92d629208268aae9c8835da9e70a6a9263d3 | 34,605 |
def figshare_metadata_readme(figshare_dict: dict) -> dict:
"""
Function to provide shortened dict for README metadata
:param figshare_dict: Figshare API response
:return: README metadata based on Figshare response
"""
readme_dict = {}
if 'item' in figshare_dict:
print("figshare_m... | 5c7a5559d4e09767032888465156eb9ea291d6c2 | 34,608 |
def add_response_tokens_to_option(_option, response_tokens, response_tokens_from_meta):
"""
:param _option: (delivery_api_client.Model.option.Option) response option
:param response_tokens: (list<str>) list of response tokens from decisioning context
:param response_tokens_from_meta: (list<str>) list of... | 7c30f7cdfda5db9cc4e3e9ea3eb8d887ad491747 | 34,609 |
import os
def get_timestamp(trg_dir):
"""a little function to read a time stamp from a csv file placed in
the target directory the last time we backed everything up.
Returns None if a timestamp file cannot be found in the source
directory, in which case all reports will be copied.
Arguments:
... | f4d0dd7891ceafd05d4c62c780e766c6017b50e9 | 34,611 |
def pos_embed(x, position_num):
"""
get position embedding of x
"""
maxlen = int(position_num / 2)
return max(0, min(x + maxlen, position_num)) | 1364ca51b76f3690bc73de743056b1ab435e1805 | 34,612 |
def render_string(s, f, colour, background, antialiasing = True):
"""
Create pygame.Surface and pygame.Rect objects for a string, using a
given font (f) and colour.
Parameters:
s: the string to render.
f: the font in which to render s.
colour: the colour of text to use, expr... | 5f6c72d55a864fd607503ff887edc132cfdd5e3c | 34,613 |
def replace_entities(df, col_name, entity_dict):
""" A function to replace values in a Pandas df column given an entity dict, as created in associate_entities()
Args:
df (DataFrame) : A Pandas DataFrame
col_name (string) : A column in the Pandas DataFrame
entity_dict (dict) : A dic... | 71aa5bbf5f8a42a6fa7a85d51c280307dec2ee96 | 34,614 |
from typing import List
def clean_strings(string_list: List[str]) -> List[str]:
"""
Clean up a list of strings ready to be cast to numbers.
"""
clean_string = []
for string in string_list:
new_string = string.strip()
clean_string.append(new_string.strip(","))
return clean_strin... | 59b7653f36771b79588381ba255acf89c0294c02 | 34,616 |
def vertical_path(size):
"""
Creates a generator for progressing vertically through an image.
:param size: A tuple (width, height) of the image size
:return: A generator that yields a set of columns through the image.
Each column is a generator that yields pixel coordinates.
"""
width, heigh... | 91d42be4bdd8f501405f226a0a158491932d6b2b | 34,617 |
def getProperties(object) :
"""
Extracts and returns properties of an object from the FBX tree.
"""
dict = {}
Prop70 = object.find("Properties70")
if Prop70 != None :
allProp = Prop70.findall("P")
for prop in allProp :
allinfo = prop.text.split(",")
for info in allinfo :
dict[allinfo[0]] = [info.str... | d4cea99aa0d2bf6507909c6fa0f462532bcd98b9 | 34,618 |
from unittest.mock import patch
def patch_init_modem():
"""Mock modem."""
return patch(
"homeassistant.components.modem_callerid.PhoneModem.initialize",
) | 19f7c8e19f0e5c77922e7a956f349647b3a3b5ba | 34,619 |
def hourly_info(x):
"""
separates the hour from time stamp. Returns hour of time.
"""
n1 = x.hour
return n1 | 2c6277e1ccc3f40706241541a1674fc8690159c6 | 34,622 |
from typing import List
import shlex
def bash_and_fish_remove_path(value: List[str]) -> str:
"""Renders the code to remove directories from the path in bash and fish.
:param value: A list of values to prepend to the path.
:return: The code to prepend to path.
"""
return "\n".join(f"remove_path {s... | fb207ba333cff0431ede497593df22f3f1a806c0 | 34,623 |
def binary_encoder_decoder(obj):
"""
Assumes value is already in binary format, so passes unchanged.
"""
return obj | e0de5bfd00e043f95cbac680fa9499c8037055c3 | 34,624 |
def _find_max_power(grid, size):
"""Find the maximum power in the grid for a given size."""
size -= 1
max_power = grid[size][size]
max_coords = (1, 1)
for coord_x in range(300 - size):
for coord_y in range(300 - size):
power = grid[coord_x + size][coord_y + size]
if... | fb451e3d8cad1b85cc014e43f917da74c207cb37 | 34,626 |
def retrieve_usernames(list_of_ids, dict_of_ids_to_names):
"""
For retrieving usernames when we've already gotten them from twitter.
For saving on API requests
"""
usernames = []
for user_id in list_of_ids:
usernames.append(dict_of_ids_to_names[user_id])
return usernames | edf0f8baca112f1741813b35261042f4e19f8d08 | 34,627 |
def create_search_criterion_by_date(datetime, relative=None, sent=False):
"""Return a search criteria by date.
.. versionadded:: 0.4
:param relative: Can be one of 'BEFORE', 'SINCE', 'ON'.
:param sent: Search after "sent" date instead of "received" date.
"""
if relative not in ['BEFORE', 'ON',... | e7d6d6bb8a85c277bc45ec3b2c30d586927a58e4 | 34,628 |
def read_config(filename):
"""read the config file and return a dict"""
try:
with open(filename, 'r') as conf_file:
lines = conf_file.readlines()
token: str
procd = dict([[token.strip() for token in line.split("=")] for line in lines])
return procd
exc... | 44f4723377d872f04326dfa5ef3e38ead30019ba | 34,629 |
def get_cleaned_string(string):
"""
Return ``string`` removing unnecessary special character
"""
if string:
for replaceable in ("'", '"', '{', '}', '[', ']', '%q', '<', '>', '.freeze'):
string = string.replace(replaceable, '')
return string.strip() | e20549e2f46e65be17c04edeb62b3d7a8c60f2fb | 34,630 |
def setitimer(which, seconds, interval=0):
"""Sets given interval timer (one of :const:`signal.ITIMER_REAL`,
:const:`signal.ITIMER_VIRTUAL` or :const:`signal.ITIMER_PROF`) specified
by *which* to fire after *seconds* (float is accepted, different from
:func:`alarm`) and after that every *interv... | 8b1d56245813e7851b0157d5f5e9e50b6d0b67ac | 34,631 |
import os
def same_partition(f1, f2):
"""Returns True if both files or directories are on the same partition
"""
return os.stat(f1).st_dev == os.stat(f2).st_dev | 18a36780732ad6cbe317f01326ccec13475fc4a6 | 34,633 |
def evaluate(f, x ,y):
"""Uses a function f that evaluates x and y"""
return f(x, y) | 894bea46653312e7a600788df268af0e9e26fbee | 34,635 |
def withattr(**kwg):
"""
Set attributes to a func, example:
>>> Class Model(DjangoModel):
... @withattr(alters_data=True)
... def delete(self):
... delete(self)
:param kwg: attributes dict
"""
def foo(func):
for name, value in list(kwg.items()):
s... | 3a51f9f7f04af4b23152e43fe21053f12a333158 | 34,637 |
def pyimpl_universe_setitem(universe, handle, value):
"""Implement `universe_setitem`."""
return universe.set(handle, value) | 87198c2c3d8072979da775576babb8fb8de885b4 | 34,638 |
def test_fetch_doc_by_id(client, db, _id):
"""Test document fetch by Id."""
try:
response = client.get_document(
db=db,
doc_id=_id
).get_result()
if "error" in response:
raise ValueError(f'Document with id {_id} not found')
else:
p... | c3eb74d924d779bcbf7d5403dd2a1fd028c6bd84 | 34,639 |
import copy
def filter_date_in_range(phase_dates, starttime, endtime):
"""
Exclude phases date outside range, and handle its date boundary.
"""
phases = copy.deepcopy(phase_dates)
for item in phases:
if not (item[0] >= starttime and item[0] < endtime):
item[0] = None
if... | e8cd8a893e5375959ecc498c3a7c90ce896e29dd | 34,640 |
import logging
def final_policy(policy_network, policy_params, alpha, x):
"""Rollout the final policy."""
logging.info("jit-ing final_policy")
n_policies = len(policy_params)
prefactor = alpha / (1 - ((1 - alpha)**n_policies))
def weighted_policy(k, params):
return prefactor * (
(1 - alpha)**(n... | a497d1d38b69c9a6582b60e32a44dad0f5bb716a | 34,643 |
def _common_gpipe_transformer_params(p):
"""Add GPipe params to layer."""
p.Define(
'is_transparent', False,
'If set, encoder outputs a list of layer outputs while decoder '
'expects a list of source input vectors.')
p.Define(
'num_transparent_outputs', 0,
'Number of transparent outp... | a848f0bc36a0a4c4fac2028d4c2b99026af1d180 | 34,646 |
def calculate_consonant_magnification(velocity):
"""子音速度を倍率に変換する。
"""
return 2 ** ((100 - velocity) / 100) | 892b44a6df77107860dc92844bbea98c4f816d53 | 34,647 |
def compare(initial, candidate):
"""
Compares two shingles sequence and returns similarity value.
:param initial: initial sentence shingles sequence
:param candidate: compared sentence shingles sequence
:return: similarity value
"""
matches = 0
for shingle in initial:
if shingle ... | 07bd224c422db70382875647028cb159a2810686 | 34,649 |
def field_to_int(field):
"""
Return an integer representation. If a "-" was provided return zero.
"""
if field == "-":
return 0
return int(field) | 1cb3910a77abce808fd35a208af91945a5759322 | 34,651 |
def stress_model(strain, modulus):
"""
Returns the linear estimate of the stress-strain curve using the strain and estimated modulus.
Used for fitting data with scipy.
Parameters
----------
strain : array-like
The array of experimental strain values, unitless (or with cancelled
... | 5e84742805ecfcfda0299d88ed28e439adbfbadc | 34,652 |
def vdiv_scalar(vector, scalar):
""" div vectors """
return (vector[0] / scalar, vector[1] / scalar) | 0bdfae21fd6c831c280ac54319f3ff43c138bf47 | 34,653 |
import time
def time_current():
"""Returns the number of second since the epoch."""
return int(time.time()) | 01ed89d69d5cfa529e8e4b921c8985d957df996f | 34,654 |
from typing import List
def get_requirements() -> List[str]:
"""read the contents of the requirements file"""
with open('requirements.txt', encoding='utf-8') as f:
return [line.replace('==', '>=') for line in f.readlines()] | 26d652ef8ac9ea2d1e96d1a06b7d07d860ea9d13 | 34,655 |
from numpy import zeros, where
def calc_13_category_usda_soil_type(clay, sand, silt):
"""Calculate the 13 category usda soil type from the clay sand and silt
0 -- WATER
1 -- SAND
2 -- LOAMY SAND
3 -- SANDY LOAM
4 -- SILT LOAM
5 -- SILT
6 -- LOAM
7 -- SANDY CLAY LOAM
8 -- SILTY... | e70a9e2ac1ec20e0106adedccf6548f096a5ac8d | 34,656 |
def mapping_ids_dicts(unique_ids, filtered_align_df_positive):
"""
makes dict from ids mapping to one another
meeting criteria set above
"""
ids_dict = {}
for i in unique_ids:
ids_dict[i] = []
ids_dict[i].append(filtered_align_df_positive[filtered_align_df_positive[0] == i][2].t... | 840206a999a23b30063b7ce8a55b947b97f95718 | 34,657 |
import pickle
def load_dictionary(file_path):
"""
Loads a categorical variable dictionary that was saved in pickle format.
"""
with open(file_path, "rb") as dictionary_file:
return pickle.load(dictionary_file) | ea500d9739d725f2889f83a3d935f708600eb52e | 34,658 |
def evaluate(predictions):
""" Calculates scores for the predictions"""
legit_predictions , spam_predictions = predictions
true_legit = legit_predictions.count("legit") # count true legit predictions
false_legit = spam_predictions.count("legit") # count false legit predictions
true_spam = ... | 7d05ad2f0dac67c986dc66cfcd7082ef9a592bf3 | 34,660 |
import math
def p_largest_prime_factor(num : int, start : int, largest : int) -> int:
"""Find the largest prime factor of an odd number"""
if largest * largest > num:
return num
lim = int(math.sqrt(num)) + 1
for i in range(start, lim, 2):
if num % i == 0:
largest = i
... | 50cd80b662dca0d94aebfc569aec5c464143c254 | 34,661 |
def getRawName(path):
"""
Given a filename with no path before it, returns just the name, no type
:returns filename
"""
loc = path.rfind(".")
if loc == -1:
return loc
else:
return path[0:loc] | b3d48fe92f52899346beae0929eedab48bd7dfef | 34,662 |
def filter_index(collection, predicate=None, index=None):
"""
Filter collection with predicate function and index.
If index is not found, returns None.
:param collection:
:type collection: collection supporting iteration and slicing
:param predicate: function to filter the collection with
:... | 11ad880ab62a0b8c06bf9888fd486ef2bf76888b | 34,663 |
from pathlib import Path
def load_html(filename):
"""
Load HTML from file
"""
return Path(filename).read_text() | 50ddc08e7fc7a90bc9e1f3818d7b7eb564b1c98b | 34,664 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.