content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def _aggregates_associated_with_providers(a, b, prov_aggs):
"""quickly check if the two rps are in the same aggregates
:param a: resource provider ID for first provider
:param b: resource provider ID for second provider
:param prov_aggs: a dict keyed by resource provider IDs, of sets
... | b2da5ff44a0c8abf3204987d79a3eebdd783efb1 | 663,994 |
def get_closest_waveform(x, y, t, response):
"""
This function, given a point on the pixel pad and a time, returns the
closest tabulated waveformm from the response array.
Args:
x (float): x coordinate of the point
y (float): y coordinate of the point
t (float): time of the wave... | 64bf6649a6e84863dd3caa4cdf757f0a5960cfe9 | 663,995 |
import itertools
def GAC(variables, domains, constraints):
"""
Generalized arc consistency algorithm from the book
Artificial Inteligence: Foundations of computational agents
Figure 4.3 p136
Keyword arguments:
variables -- a list of the variables
domains -- a dictonary of domains for eac... | eb2ed55ee0adede038cea8082809c8bc15348b9c | 663,996 |
def hello(friend_name):
"""
say hello to the world
:param friend_name: a String. Ignore for now.
:return: a String containing a message
"""
return f'Hello, {friend_name}!' | 8401ae5e81c02f8a6038b31b9ba72b8dad0a75ef | 663,997 |
def getAuthorsUrls_ts(db):
"""师生关系表中未被爬取的作者"""
sql_at = """SELECT DISTINCT
url_teacher
FROM
`re_teacher_student`
WHERE
url_teacher NOT IN (SELECT url FROM author);
"""
sql_as = """SELECT DISTINCT
... | e9575da069b2060cdfa5981439876656073bc73a | 663,998 |
def register(array):
"""A decorator to add things to lists without stomping over its
value."""
def x(val):
array.append(val)
return val
return x | 171c3cac030d4f374c41214a6c6a0af430428d9e | 663,999 |
def test_name(msg_name):
"""Generate the name of a serialization unit test given a message name"""
return "test_{}_serialization".format(msg_name) | 261c4c4e215b84c0358ca51cbbd4723208dedb12 | 664,000 |
def absolute_date(resolution, start, end):
"""Select an absolute date range for a location selector.
:keyword resolution: Time resolution specifier, e.g. ``hours`` or ``days``.
:keyword start: UTC start time in ISO 8601 format.
:keyword end: UTC end time in ISO 8601 format.
>>> from pprint import ... | 1045a17fc6baf1f13357654345fe2a71f971dd59 | 664,001 |
import re
def natural_key(string):
""" Key to use with sort() in order to sort string lists in natural order.
Example: [1_1, 1_2, 1_5, 1_10, 1_13].
"""
return [int(s) if s.isdigit() else s for s in re.split(r'(\d+)', string)] | a474360aa2d8d10ea9283627219c0e86645f79be | 664,002 |
import os
from math import sqrt
def setup(i):
"""
Input: {
cfg - meta of this soft entry
self_cfg - meta of module soft
ck_kernel - import CK kernel module (to reuse functions)
host_os_uoa - host OS UOA
ho... | a6f3f177d48a363b81e32fd8db09aad2c5a65c2a | 664,003 |
def flipra(coordinate):
"""Flips RA coordinates by 180 degrees"""
coordinate = coordinate + 180
if coordinate > 360:
coordinate = coordinate - 360
return coordinate | 5db6cb5bc7c7cb0b23e0ea434b2f4815e75d4800 | 664,004 |
def get_location_from_object(loc_obj):
"""Return geo-location from a RefContext location object."""
if loc_obj.db_refs.get('GEOID'):
return loc_obj.db_refs['GEOID']
elif loc_obj.name:
return loc_obj.name
else:
return None | d97f9ebd442f1e32adf03c7d51a1d8acde65bfb7 | 664,005 |
def ExtractImageTag(obj):
"""
Function to extract and return all image tags present in a BeautifulSoup object
"""
taglist = obj.findAll("img")
return taglist | 0f50aa1a14836de59537ed557cafd8de7560ef13 | 664,006 |
import yaml
import pkg_resources
from pathlib import Path
def load_config(path=None):
"""Load a config file either from a user nominated location or, if no path is supplied, load the default config file from the *pinout* package.
:param path: [description], defaults to None
:type path: [type], optional
... | 08f74cd671cb7fa89aa566476bf9bbc9545ccbcb | 664,007 |
from typing import Union
from pathlib import Path
from typing import Tuple
from typing import List
from typing import Dict
def parse_synset_mapping(
synset_mapping_filename: Union[Path, str]
) -> Tuple[List[str], Dict[str, str]]:
"""Parses the synset mapping file.
Args:
synset_mapping_filename: a... | 25376c76f505e168e5be428d2deb62f2ed428568 | 664,008 |
def clear_all(client):
"""Delete all keys in configured memcached
:param client: memcached client object
"""
client.flush_all()
return True | e7a24f798a62aaa29c0e254cf1c22e0fee1d64ad | 664,010 |
def negate_implication_property(property_graph):
"""Returns a copy of given property with conclusion part negated."""
assumption, conclusion = property_graph.get_top_level_implication_subgraphs()
assumption = assumption.get_copy()
conclusion = conclusion.get_copy()
conclusion.logical_not()
assum... | 3b00985f315e47c9b61e3c90666a16379fe99809 | 664,011 |
from typing import Iterable
def list_get(instances: Iterable, index: int, default=None):
""" 根据索引号获取列表值或者默认值。get default value on index out of range for list.
Examples::
list_get([0, 1, 2], 3, 4)
# 4
"""
try:
return list(instances)[index]
except IndexError:
return... | 800f79e4e096fb9fe20038b71dd0b01a82b25768 | 664,012 |
import re
def clean(text):
"""
Arguments:
text: it is the string that is to be cleaned
this is a helper function that cleans the string
Return:
text: cleaned string
"""
text = text.lower()
text = re.sub(r'i\'m', 'i am', text)
text... | d3cee09aa42c224036bf60cabd265b5e31aa2131 | 664,013 |
import json
def convert_response_to_json(response):
"""Converts the response to a json type"""
json_response = json.loads(response.data.decode('utf-8'))
return json_response | cd89b2ff7e397bf84d0a6d717c1cb97ea6714e25 | 664,014 |
import re
def extract_points_from(result):
"""
Expected line: "Unlocked 31/50 Git Achievements for 248 points"
"""
pattern = re.compile(r'[^0-9]*Unlocked[^0-9]+(\d+)[^0-9]+(\d+)[^0-9]+(\d+)')
for line in result.readlines():
match = pattern.search(line)
if match:
return [int(n) for n in match.g... | 15066339d021506d7c3882239d34673ceb5fc7d8 | 664,015 |
from bs4 import BeautifulSoup
def strip_anchor_from_href(soup: BeautifulSoup) -> BeautifulSoup:
"""
Loop through every href anchor and strip it, without editing content.
Strip <a> tags such as
<a class="calibre17" href="part0017.xhtml#d00401">absolutisme</a>
Args:
soup (BeautifulSoup)... | 3bf6772ae809d7b34d1a15074febfbbefb1b0fe3 | 664,016 |
import statistics
def group_lines_y(all_lines_y):
"""
As some lines are detected multiple times, we need to group them to be able to work with a lines y coordinate
"""
all_lines_y.sort()
average_lines_y = []
one_line_group = [all_lines_y[0]]
for line_y in all_lines_y[1:]:
if line_y... | f34255de3a1ee5fab73ab8d1beed05114d024f37 | 664,017 |
import os
def _parts(path):
"""
>>> list(_parts('parent/child/'))
['parent', 'child']
>>> list(_parts('parent/child'))
['parent']
"""
parts = []
head, _ = os.path.split(path)
while head:
head, tail = os.path.split(head)
parts.append(tail)
return reversed(parts) | 4edc68325170d94731f690cc84271c550429833a | 664,018 |
def write_gif(clip, path, sub_start, sub_end):
"""Write subclip of clip as gif."""
subclip = clip.subclip(sub_start, sub_end)
subclip.write_gif(path)
return subclip | 64cdd6dafde695a093cf84bfec97f3644c904928 | 664,019 |
def strip_function_name(elements):
"""Strip function name."""
for i in range(len(elements) - 1):
if elements[i] == "@":
elements[i + 1] = "fn_0"
return elements | cf7718cc8c9b6424565a39fffc85e4d72de6865c | 664,021 |
def _parse_reflectivity(line, lines):
"""Parse Energy [eV] reflect_xx reflect_zz"""
split_line = line.split()
energy = float(split_line[0])
reflect_xx = float(split_line[1])
reflect_zz = float(split_line[2])
return {"energy": energy, "reflect_xx": reflect_xx, "reflect_zz": reflect_zz} | 16f15cb7621f02648942ebf1609f08c16ae91500 | 664,022 |
import pkgutil
import os
import importlib
def load_ospurge_resource_modules():
"""Import all the modules in the `resources` package."""
modules = {}
iter_modules = pkgutil.iter_modules(
[os.path.join(os.path.dirname(__file__), 'resources')],
prefix='ospurge.resources.'
)
for (_, na... | 3ceacd44e1ea0e4f8b95640f4920f7d694bdc0ff | 664,023 |
def decompose_chrstr(peak_str):
"""
Take peak name as input and return splitted strs.
Args:
peak_str (str): peak name.
Returns:
tuple: splitted peak name.
Examples:
>>> decompose_chrstr("chr1_111111_222222")
"chr1", "111111", "222222"
"""
*chr_, start, end = ... | b9a495572892445cd87d20a1c1bc9f9a0f9f1c5e | 664,024 |
from typing import Union
import os
from typing import Tuple
def find_labelfile(video: Union[str, os.PathLike]) -> Tuple[str, str]:
""" Function for finding a label file for a given a video """
base = os.path.splitext(video)[0]
labelfile = base + '_labels.csv'
if os.path.isfile(labelfile):
retu... | 5736870ee6ae512d2b53683246b0b4f7c7177f01 | 664,025 |
def are_keys_binary_strings(input_dict):
"""Check if the input dictionary keys are binary strings.
Args:
input_dict (dict): dictionary.
Returns:
bool: boolean variable indicating whether dict keys are binary strings or not.
"""
return all(not any(char not in '10' for char in key) f... | ef970da51bfc2f64b092795507c2f5b8ffe6628f | 664,026 |
import requests
def getCount(AUTH):
"""
Get Object Count
"""
url = "https://intersight.com/api/v1/asset/DeviceContractInformations?$count=True"
response = requests.request("GET", url, auth=AUTH)
countData = response.json()
return countData | dbf19abb5c5d134e740727a245e9e29ab253c2c6 | 664,027 |
def migratoryBirds(arr):
""". Your task is to print the type number of that bird and if two or more types of birds are equally common, choose the type with the smallest ID number."""
# Step 1 - Find the mode(s) of the array
# arr = 1, 1, 2, 3, 3, 3, 3, 5
total_counts = {}
# Step - 1.1 - Find uniqu... | c7f5754dd234e1f42ba3967fd2b541a7a4fc8463 | 664,028 |
def flatten_nparray(np_arr):
""" Returns a 1D numpy array retulting from the flatten of the input
"""
return np_arr.reshape((len(np_arr))) | bb8700b65c327227cce43a7ec6ba7363ecf13b7f | 664,029 |
def test(condition, true, false):
"""
Implements the C expression:
condition ? true : false
Required to correctly interpret plural forms.
"""
if condition:
return true
else:
return false | 89644f242c24f0d4e0905d30d70a3ceb2ef9762a | 664,030 |
def height(I):
"""returns the height of image"""
return I.shape[0] | 01e536605b8e65788506baa424614eb152908737 | 664,031 |
def read_names(filename):
"""File with name "filename" assumed to contain one leafname per line. Read and return set of names"""
names = set()
with open(filename, "r") as infile:
for line in infile:
leaf = line.strip()
if leaf:
names.add(leaf)
return name... | 29e3bf5a94fc32430b713c335b28e297cbeb0eca | 664,032 |
def select_best(neighs):
"""
Remove all but the single best neighbor from the list of neighs in-place
"""
max_score = 0
max_score_pos = 0
for pos, n in enumerate(neighs):
if n[1].score > max_score:
max_score = n[1].score
max_score_pos = pos
return [neighs[max_... | 80cb470903d6a578b6b0d3f4839e3dacda9d3ccf | 664,033 |
def learning_rate_decay(alpha, decay_rate, global_step, decay_step):
"""
Updates the learning rate using inverse time decay in numpy
alpha is the original learning rate
decay_rate is the weight used to determine the rate at which alpha will
decay
global_step is the number of passes of gradien... | 640f823ace92fdbd6fca198468864445a201b7e3 | 664,034 |
def inherit_docstring_from(cls):
"""Decorator for inheriting doc strings, stolen from
https://groups.google.com/forum/#!msg/comp.lang.python/HkB1uhDcvdk/lWzWtPy09yYJ
"""
def docstring_inheriting_decorator(fn):
fn.__doc__ = getattr(cls, fn.__name__).__doc__
return fn
return docstring_... | 9ae6e2fd70acb34bf7f22ee920c271cea3ccfcea | 664,035 |
from typing import Counter
def scan_vocab(sents, tokenizer, min_count=2):
"""
build vocabulary
sents: sentences in documents
tokenizer: str -> list of str
min_count: minimun number of occurrence in given documents (recommend 2~8)
"""
counter = Counter(w for sent in sents for w ... | 7ba82427bb7051f5f62a8a08ca3ccb954e9df826 | 664,036 |
def tanimoto(e1, e2):
"""
Tanimoto coefficient measures the similarity of two bit patterns.
Also referred to as the Jaccard similarity
:return: real 0-1 similarity measure
"""
return (e1 & e2).count() / float((e1 | e2).count()) | 2fe750d95da75af0ea9ae6e00688430cf541b2c1 | 664,037 |
import json
def set_filter_config(configuration):
""" Set configuration if provided
:param configuration:
:return:
"""
global rate
config = json.loads(configuration['config'])
if'rate' in config:
rate = config['rate']
return True | 6a53ab2eb91af21b16e6a13ae69ad6ebab602741 | 664,038 |
import colorsys
def convert_to_color_dict_list(colors: list) -> list:
"""Return a list of dictionaries of colors in different formats."""
color_dict_list = []
for color in colors:
hex_color = []
for color_index in range(0, 3):
hex_color_part = hex(color[color_index]).replace("... | edd476b91276a0b4fed55cb09b51d7f48fac888e | 664,039 |
import math
def thickness(p_value, significance_level):
"""Exponentially decreasing thickness.
This is a different function to convert p-values to edge
reliability scores. The default is the threshold function.
Args:
p_value: The p-value of the used test statistic on the edge.
signi... | b4af29e86e50c621def6c75f94c7215984710a9d | 664,040 |
def scaleValues(values):
"""Scale a numpy array of values so that (min, max) = (0,1)."""
values = values - values.min()
return values/values.max() | a7b02a8b0d7d8cf041843fe31929acd03d22cc0f | 664,041 |
import numpy
def selectWorstIndividual(scores):
"""
It is used to get the worst individual in a population based n the fitness value
"""
maxFitnessId = numpy.where(scores == numpy.max(scores))
maxFitnessId = maxFitnessId[0][0]
return maxFitnessId | fdcdf27fa12ce7b19f0cf8167e1e525764d9f474 | 664,042 |
def validate_spec(spec):
"""
Validates the incoming spec
@returns - True/False, Error Message
"""
# size = spec.get('size')
# if not size:
# return size, "Size must be set"
return None, None | 4c8f226268d68035a1f3a558625bb11d5488cacc | 664,043 |
def ranking_function(match_ratio, matched_attribute_list):
"""
sigma (i to no. of matched attributes) (matchRatio * ith weight)
"""
score = 0
for attribute in matched_attribute_list:
score += match_ratio * attribute.get('weight')
return score | eca0c17ec59afffb7dc372db79861a8795b3aa6d | 664,045 |
def Py_AddPendingCall(space, func, arg):
"""Post a notification to the Python main thread. If successful,
func will be called with the argument arg at the earliest
convenience. func will be called having the global interpreter
lock held and can thus use the full Python API and can take any
action ... | c01ee4b59e347585d170fa591b242dac96ea5653 | 664,046 |
import os
def local_excel_files(root_dir):
"""Returns filenames to excel files contained in the directory tree of root_dir
"""
excel_files = []
for root, dirs, files in os.walk(root_dir):
for file in files:
if ".xlsx" in file:
excel_files.append(os.path.join(root, f... | 763af1423189af6ab24b525bfe6bedc463ce24df | 664,047 |
def write_data_file(data, filename):
"""Compile lines into a file."""
data_file = open(filename, 'w') # write
for line in data:
assert type(line) == type([])
assert all(type(item) == type('') for item in line)
data_line = ' '.join(line) + '\n' # join together and add a carriage retur... | dfa6ab6190b3f2eb618cae5e0660ebc752a1f8c2 | 664,048 |
import random
import string
def random_string():
"""Return a random string."""
return random.choice(string.ascii_lowercase) | 9b286a088142fd4e3dacd79a8ad6215913af73d4 | 664,049 |
import time
def ValueOfDate() -> int:
"""
Return current unix time in milisecond (Rounded to nearest number)
"""
return round(time.time() * 1000) | cc0b51a1eb997ae12e19f40751fde28caad12877 | 664,050 |
def read_line_of_integers():
"""Read one line of numbers or detect EOF"""
try:
text = input()
return [int(i) for i in text.split()][1:]
except EOFError:
pass
return None | 1951368581003c21d3dfd931260223a82881b244 | 664,051 |
def register_versions(role, versions=None):
"""Decorator for connecting methods in the views to api versions.
Example:
class MyView(BaseView):
@register_versions('fetch', ['v4', 'v5'])
def _get_data(self, param1, param2):
...
@register_versions('re... | 3b318530f4bc9c0673fbb1bf2af1e90d6841d44e | 664,052 |
def _while(x):
""" _while """
ret = x * x
i = 2
while i <= 3:
ret = ret * i
i = i + 1
return ret | 4615569bbe4d562687b3f9b15d642063207f312f | 664,054 |
from datetime import datetime
def utc_time_str(dt=None):
"""返回 UCT 标准时间,按照 Java 的方式格式化:2011-02-18T08:30:30Z"""
date_format = "%04d-%02d-%02dT%02d:%02d:%02d.%03dZ"
if not dt:
dt = datetime.utcnow()
millisecond = int(dt.microsecond / 1000)
date_str = date_format % (dt.year, dt.month, dt.d... | fbb5c7787d3c535634427cb9faf6a1d8e615b6de | 664,057 |
def latex_safe(s):
"""
Produce laTeX safe text
"""
s = s.replace('_','\_')
return s | f816c96cb46b9707a5d173f61e6d956feade1fd5 | 664,058 |
def open_wordlist(path):
"""
open a wordlist
Note:
a wordlist should be a text document with one word per line
Args:
path(str): full path to the wordlist
Returns:
passwordlist(list): list of all the words (as strings) in the wordlist
"""
with open(path, 'r', errors... | 55de8c0424b25090067c38f8ac38c5c124f9dcb5 | 664,059 |
import functools
def register(cli, func, *args, **kwargs):
"""Register a function for a command line interface.
Args:
cli: Command line interface for which we register the function.
func: Function that we register.
args, kwargs: Optional positional and keyword arguments that will be
... | 2406c16199eb295c33844acc061690852ee79d83 | 664,060 |
def count_substring(string, sub_string):
"""
count=0
for i in range(0,len(string)):
print(string[i:i+len(sub_string)])
if string[i:i+len(sub_string)]==sub_string:
count+=1
"""
#chnage this to one line
return sum([1 for i in range(0,len(string)) if string[i:i+len(sub_s... | dc00f845d3ffc4ec0d1b067e7a5dfcdc1c1be9f7 | 664,061 |
import types
def add_node_by_type(g, node):
"""
Adds a node to the graph and initializes the node "properties" defined
in NODE_ATTRS class var of the node type.
"""
kw = {}
for k, v in node.NODE_ATTRS.iteritems():
value = v() if isinstance(v, types.FunctionType) else v
kw[k] = ... | 61c4e3df53ac4a06ef46de5d824905a19f4947e3 | 664,062 |
import argparse
def nonempty_string(argstring):
"""
Validate that the string is not of 0 length.
If the string is 0 length, raise an argparse exception.
Otherwise return the string.
"""
if argstring:
return argstring
raise argparse.ArgumentTypeError("appVersion may not be blank") | 67a9630d413e53b85301de4d190836829182f701 | 664,063 |
import re
import sys
def insert_new_nodes(tree, placements, verbose=False):
"""
Insert the new nodes in the tree at the correct place
:param tree: The phylogenetic tree
:param placements: the list of edges to place in the right place
:return:
"""
added = set()
for t in tree.traverse(... | fb3e3fdbbcc8b7c75195a9de3b92c4053630a82e | 664,065 |
import os
def db_url():
"""Default db url used by depending fixtures.
When CI key is set in environment variables, it uses `postgres` as host name:
postgresql://postgres@posgres/postgres
Else, host used is `localhost`: postgresql://postgres@localhost/postgres
"""
host = "postgres" if "CI" in... | 6b8e02f208abde20d94a76b5acac9739ee98ff66 | 664,066 |
def fahrenheit_to_celsius(temp):
"""Convert temperature in fahrenheit to celsius.
Parameters
----------
temp : float or array_like
Temperature(s) in fahrenheit.
Returns
-------
float or array_like
Temperatures in celsius.
bubbles
"""
try:
... | 8fc52f77268d38219cfd16f21540f8409dd006b5 | 664,068 |
def CallbackListConfig(argument_parser):
"""
Set CLI arguments
:param argument_parser: argument parser
:type argument_parser: ```ArgumentParser```
:returns: argument_parser
:rtype: ```ArgumentParser```
"""
argument_parser.description = "Container abstracting a list of callbacks."
r... | 84f77d8198c0bd00782aea6e858107a0fb525f6e | 664,069 |
def validateTime(time):
"""
Helper function that checks the value the user entered for time
:param time: the inputted time from the user
:return: the time the user entered, or 0
"""
response = time
if (time > 59 and time < 100) or \
(time > 159 and time < 200) or \
(tim... | dc8d9fdb7312a6ebcf207d77a7bcd7f9054c1c26 | 664,071 |
import os
import sys
def parse_requirements(requirements_file):
"""
Create a list for the 'install_requires' component of the setup function
by parsing a requirements file
"""
if os.path.exists(requirements_file):
# return a list that contains each line of the requirements file
... | 83b47d464cf41c6ecbd9a69a232d7c788fa6a341 | 664,072 |
from optparse import OptionParser
import sys
import os
def getCommandlineOptions() :
"""
get user options form the command-line and validate required arguments
"""
parser = OptionParser()
parser.add_option('-e', '--endpos', dest='endpos', type='string', help='path and name of the endpos index fi... | eeb9fb0d3cc8d1cbb31a7d79adaf0266af62eac8 | 664,073 |
def _is_literal(s):
"""
>>> _is_literal("http://example.org/bar")
False
>>> _is_literal('"my text"')
True
>>> _is_literal('"my text"@en-gb')
True
>>> _is_literal('"42"^^http://www.w3.org/2001/XMLSchema#integer')
True
>>> _is_literal('?var')
False
"""
return s.sta... | 21c2b80f1c90fea1fbc097f9bb530bfbce0d2cc6 | 664,074 |
import logging
def get_logger():
"""
Sets up and returns logger with Singleton handler.
:return: Command line logger
:rtype: :class: `Logger`
"""
logging.basicConfig(
format='%(asctime)s %(processName)s %(levelname)s %(message)s',
level=logging.INFO,
)
logger = logging... | 7f48f462594287d205923967d6a363f53ab78b89 | 664,075 |
import functools
def replace_all(text, replacements):
"""
Replace in `text` all strings specified in `replacements`
Example: replacements = ('hello', 'goodbye'), ('world', 'earth')
"""
return functools.reduce(lambda a, kv: a.replace(*kv), replacements, text) | b23efcc6198eb2652021600d505266ae16c903f2 | 664,076 |
def fixaLiniesComencenPerCometes(md):
"""
Si una línia comença per ` i no té un cr davant, li posa una línia nova a davant.
Ull! Només afecta un cas.
"""
new_md = []
md = md.replace("\r\n", "\n")
md_splitted = md.split("\n")
is_apos = False
is_cr = True
for line in md_splitted:
... | 547a08cfe28363d5b03b595f7c3f64185b2b4ec8 | 664,078 |
import glob
def get_files(data_dir_list, data_ext):
"""
Given a list of directories containing data with extention 'date_ext',
generate a list of paths for all files within these directories
"""
data_files = []
for sub_dir in data_dir_list:
files = glob.glob(sub_dir + "/*" + data_ext)... | e473a94ba9542d4813d7bf1e87a0773aecdaf1ce | 664,079 |
def supertype(tcon):
"""
Return the supertype of the given type constructor.
"""
return tcon.supertype | d12a1b1078a607b20da34aed2907507c75912f1d | 664,080 |
from typing import OrderedDict
def unflatten(container, flat):
"""Iterate over a [nested] container, building a clone from the elements of
flat.
Returns object with same type as container.
Note that unflatten(container, flatten(container)) == container
"""
def unflatten_inner(container, pos)... | 68dcd4b7dbe864f7ca00e9decaa08fad22ed5604 | 664,081 |
def pfx_path(path : str) -> str:
""" Prefix a path with the OS path separator if it is not already """
if path[0] != '/': return '/' + path
else: return path | 12b7068e850c7201e063f6b1cc559cf5e9c5a0d0 | 664,082 |
def check_entity_schema(
sg, logger, entity_type, field_name, field_types, required_values
):
"""
Verifies that field_name of field_type exists in entity_type's schema.
:param sg: An authenticated Shotgun Python API instance.
:param entity_type: str, a Shotgun entity type.
:param field_name: st... | 5ae2ed8a36199d7b570a6934fc54926856f056d6 | 664,083 |
def split_into_sets(array, tindx, eindx):
"""
Split data into train and validation (or evaluation) set with indices.
Args:
array (ndarray): processed without nans
tindx (array): train data indices
eindx (array): validation/evaluation data indices
"""
array_t = array... | ea69869434a399945958395a2705e7fad5ff2c28 | 664,084 |
import re
def get_module_runtime(yaml_path):
"""Finds 'runtime: ...' property in module YAML (or None if missing)."""
# 'yaml' module is not available yet at this point (it is loaded from SDK).
with open(yaml_path, 'rt') as f:
m = re.search(r'^runtime\:\s+(.*)$', f.read(), re.MULTILINE)
return m.group(1) ... | 2e8bae6f20f55e25a7a91d5e385af646f875a525 | 664,085 |
import math
import random
def subsampling(corpus, word2freq):
"""Randomly delete words with high frequency to reduce redundant information.
Args:
corpus: a list of word ids.
word2freq: a dictionary that maps word id to word frequency.
Returns:
a list of words.
"""
def reser... | 29c71e47650b04afd9c44feb8f5e7155e2410e82 | 664,086 |
def fetch_data_from_config(config_informations):
"""
Recupère les informations de configurations
:param config_informations: Les informations de configuration
:return: Un json des informations de configuration
"""
json_config = config_informations.to_json_data()
return json_config | 50f4e2c13d62482533cdde86e717971ccc463584 | 664,089 |
def get_pagetext_json_value(pagetext, key):
"""Return a value for a key in a JSON blob in the HTML of a page.
Args:
pagetext (string): Text to search through.
key (string): The key we want the value for.
Format: '<differentiating chars>"key"'
Note a colon would be the ne... | 07e4155468f10317cceceb8c1595b25ce9b1db6f | 664,090 |
import argparse
def parse_args() -> argparse.Namespace:
"""
Parses arguments sent to the python script.
Returns
-------
parsed_args : argparse.Namespace
Parsed arguments
"""
parser = argparse.ArgumentParser()
parser.add_argument(
"--model_training_output_dir",
... | 4947886b43d4239e6a67cd27860620cb08ee7700 | 664,091 |
def pixels_to_figsize(opt_dim, opt_dpi):
"""Converts pixel dimension to inches figsize
"""
w, h = opt_dim
return (w / opt_dpi, h / opt_dpi) | 6af279e64a8e2ba8d27a1815dec905436c0c3665 | 664,092 |
def get_line_slope_intercept(x1, y1, x2, y2):
"""Returns slope and intercept of lines defined by given coordinates"""
m = (y2 - y1) / (x2 - x1)
b = y1 - m*x1
return m, b | feba17f63579d514c47f82605a8de59d196a6eb7 | 664,093 |
def compare(n, p1, p2):
"""Compares two bits in an integer.
Takes integers n, p1, p2. If the bit of n at positions p1 and p2 are
the same, true is returned to the caller. Otherwise returns false. Bit
positions start at 1 and go from low order to high. For example:
n = 5, p1 = 1, p2 = 2
... | b71af5efffb31623e7d83289ee9cdf6928178a1d | 664,094 |
def count_query(tablename,condition):
"""
Function to process query for count process
"""
if isinstance(tablename, str):
pass
else:
raise ValueError("Tablename should be a String")
if condition == None or isinstance(condition, str):
pass
else:
raise ValueErro... | 64853d573f4ab41bf7524172f671b7a2c22711c6 | 664,095 |
def filter_output(issue_type, results):
"""
filter issues of a give type
"""
if not results:
return None
issues = []
for issue in results:
if issue["type"] == issue_type:
issues.append((issue['line'], issue['message']))
return issues | 47827ebcd4b1b41151a547991ba999fb4492172d | 664,096 |
from pathlib import Path
import os
def get_annotation_name(calc_params):
"""get the name of an annotation file for a specific sheet (only one annotation per sheet)
creates the directory for it as necessary"""
data_file=calc_params.data_path
sheet_name=calc_params.sheet_name
annotation_path = "anno... | db5cf05f04bb947fe831b95b2aba2739f375c837 | 664,097 |
def _get_all_commit_message(repo):
"""
すべてのcommit messageを取得する
"""
all_commit_message = ""
with open("log/eliminate_message.txt", "w", encoding="utf-8") as f:
for commit in repo.iter_commits():
# Mergeから始まるcommit messageは除外
if not commit.message.startswith('Merge'):
... | 7745bdfe27317c495a1e291614db97cc97fbbd17 | 664,098 |
def getDisabled(self, pos):
"""Get a boolean representing whether or not cell (i,j) is disabled."""
self.__checkIndices__(pos)
return self.__isdisabled__[pos[0]][pos[1]] | 4407ee1ae7c559caffc8905c0f553104c9e19622 | 664,099 |
import numbers
import numpy
def check_uniform_label(uniform_label):
"""Convert uniform label to numpy.array
:param uniform_label: label or list of labels (examples: 0, 1, [0], [1], [0, 1])
:return: numpy.array (with [0], [1] or [0, 1])
"""
if isinstance(uniform_label, numbers.Number):
ret... | b4b7d87f5aaa5f6e40b30337889349118c530388 | 664,100 |
def Diff(li1, li2):
""" get the difference between two lists """
list_dif = [i for i in li1 + li2 if i not in li1 or i not in li2]
return list_dif | faaa50a9a37d21654611c1df522099c2a45669ec | 664,101 |
from typing import Any
import ast
def read_option_from_config(config, section, option) -> Any:
"""
@param config: ConfigParser instance
@param section: string of the config section to read from
@param option: string of the config section option to read
@return: literal evaluated value of the confi... | 575bbf22edf2b0acce5f60ad85c4dba1724c2e47 | 664,102 |
from typing import List
from typing import Dict
import codecs
def load_dict(dict_path: str,
required: List[str] = ["<sos>", "<eos>"],
reverse: bool = False) -> Dict:
"""
Load the dictionary object
Args:
dict_path: path of the vocabulary dictionary
required: requ... | 7a4398f7dbc0fef4a2b52971881c2824e4f7afec | 664,103 |
def vander_det(x):
"""Vandermonde determinant for the points x"""
prod = 1
num = x.shape[0]
for j in range(1, num):
for i in range(0, j):
prod *= x[j] - x[i]
return prod | a3b48149af03fd2235b389437d44d8e0b231119e | 664,104 |
def argmax(pairs):
"""
Given an iterable of pairs (key, value), return the key corresponding to the greatest value.
Raises `ValueError` on empty sequence.
>>> argmax(zip(range(20), range(20, 0, -1)))
0
"""
return max(pairs, key=lambda x: x[1])[0] | 8b60662485b042eb815431e38961c9cbe77cd4ea | 664,105 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.