content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def to_budo_format(value):
"""融通情報を budo 形式に変換する
Args:
value (dict): 融通情報
Returns:
dict: budo 形式の融通情報
"""
result = dict()
result['id'] = value.get('dealId')
result['dischargingUnit'] = value.get('dischargeUnitId')
result['chargingUnit'] = value.get('chargeUnitId')
result['isMasterDeal'] = value.get('isMa... | 011e7ce0d94330a60d22c962831a60dd68158b48 | 661,175 |
import os
def _get_package_path(relpath):
"""Get the full path for a file within the package
Args:
relpath (str):
A path contained within the flask_resize
Returns:
str: Full path for the file requested
"""
pkgdir = os.path.dirname(__file__)
return os.path.join(pkg... | 45475c574b3ab227b1e554912f1ab6fc3f1d7136 | 661,176 |
def remove_formatting(ingredients_series):
"""Remove text formatting and non alphabetic characters,
replace . with ,"""
return (
ingredients_series.str.replace("<strong>", "", regex=False)
.str.replace("</strong>", "", regex=False)
.str.replace(" \(.*?\)", "", regex=True)
.st... | b60d56385eadf77b5174af9809651728a46310ee | 661,178 |
def _swift_target_for_dep(dep):
"""Returns the target for which the dependency was compiled.
This is really hacky, but there's no easy way to acquire the Apple CPU for which the target was
built. One option would be to let this aspect propagate transitively through deps and have
another provider that p... | 44c3fde8ec9b2f9949e8fcfaa551ba2b805475f7 | 661,179 |
import numpy
def get_translation_matrix(trans):
"""
Returns a 4x4 numpy array representing a translation matrix from
a 3-element list.
trans (list)
3-element list (x,y,z).
"""
trans_matrix = numpy.identity(4, 'd') # four floats
trans_matrix[0][3] = float(trans[0])
trans_matr... | a31ff58ad639cc2bb5915725db8e5d9ff5802bd4 | 661,180 |
import re
def add_requirements(text):
"""Add required definitions at the appropraite positions."""
packages=r"""
%blablatex
\\usepackage{framed}
\\usepackage{xcolor}
%/blablatex"""
blabla_environment=r"""
%blablatex
\\newenvironment{blabla}[2]
{%
\\def\\FrameCommand
{%
{\\color{#2}%
... | a8d3704411c8af6288defedd12abbcfefd60d75a | 661,181 |
def darken(color, ratio=0.5):
"""Creates a darker version of a color given by an RGB triplet.
This is done by mixing the original color with black using the given
ratio. A ratio of 1.0 will yield a completely black color, a ratio
of 0.0 will yield the original color. The alpha values are left intact.
... | 3799437d126f27745710c1cd2db12c13cff1bab4 | 661,182 |
def bin_num(n, n_bits):
"""
Produce a signed representation of the number n using n_bits.
:param n: Number n
:param n_bits: Number of bits
:return:
"""
mask = (2 << n_bits - 1) - 1
num = int(n) & mask
f_str = '{:0' + str(n_bits) + 'b}'
f_res = f_str.format(int(num))
return f... | 55a95d8327a06af46365191e12a8d71ca30bd0e5 | 661,183 |
def normalize_link(link, split_url):
"""
Break the base_uri and piracy policy path apart and rebuild
the link to ensure it contains all the necessary http elements.
:param link: html link tag w/ href
:param split_url: split url (urlib.parse)
:return: string
"""
url = link.get("hre... | 518adb4a4c74f76a740462d7c5578e57d42acb07 | 661,184 |
from typing import List
def find_disappeared(nums: List[int]) -> List[int]:
"""
Explanation:
We have two ways to encode information: the values in the array,
and the indices of the array. We iterate through the array,
and store info about the values at their corresponding index: value - 1.
W... | 548b81e293aa88c73af342420a31e0a39686cf5f | 661,185 |
def __retrieve_func_id(tdm, tsuid_list):
"""
Retrieve func ids if exist for input tsuids in tsuid_list
:returns: list of functional identifiers
:rtype: list of string
:param tdm: Temporal Data Manager client
:param tsuid_list: list of TS Identifiers of the time series
:type tdm: TemporalD... | cede0417b2c1641fdec9c3d7823886c68d6862cc | 661,186 |
import torch
def compute_q_retraces(
q_values: torch.Tensor,
v_pred: torch.Tensor,
rewards: torch.Tensor,
actions: torch.Tensor,
weights: torch.Tensor,
ratio: torch.Tensor,
gamma: float = 0.9
) -> torch.Tensor:
"""
Shapes:
- q_values (:obj:`torch... | 8e921b68ac128ecbab26795e90ad8f358f6784e4 | 661,187 |
def _array_feature_extrator(data, indices):
"""
Implementation of operator *ArrayFeatureExtractor*
with :epkg:`numpy`.
"""
if len(indices.shape) == 2 and indices.shape[0] == 1:
index = indices.ravel().tolist()
add = len(index)
elif len(indices.shape) == 1:
index = indices... | 0740428d19f93d2539bc4b13517c2dc5358835e0 | 661,188 |
def getType(string: str):
"""getType
Gives type of a type string (right hand side)
:param string:
:type string: str
"""
if '#' in string:
string = string.rsplit('#', 1)[1]
return string.rsplit('.', 1)[-1] | cce9ea98be7789935526d3b00154d84731a5fb6b | 661,189 |
def strtol(value, strict=True):
"""As most as possible close equivalent of strtol(3) function (with base=0),
used by postgres to parse parameter values.
>>> strtol(0) == (0, '')
True
>>> strtol(1) == (1, '')
True
>>> strtol(9) == (9, '')
True
>>> strtol(' +0x400MB') == (1024, 'MB'... | 536105199b6aea7bad50ff2a107711834e6f9579 | 661,190 |
def _mock_check_state(_):
"""Mocked check_state method."""
return True | 1db16fd64d93147d1b1eb849e6afb4463b0f6ff3 | 661,191 |
import argparse
def parse_args():
"""Parses arguments provided in command line into function parameters."""
ap = argparse.ArgumentParser(
description='Classify objects and noise/artifacts from processed video data.')
ap.add_argument('-u', '--unlabeled_path_tmp', default='unlabeled/*.pkl',
... | ea9131c3bd73a2c629db729d5a57630e67c3d678 | 661,192 |
import math
def conv_float2negexp(val: float) -> int:
"""Least restrictive negative exponent of base 10 that achieves the floating point convergence criterium `val`."""
return -1 * int(math.floor(math.log(val, 10))) | e237466afa0fec8f128e1c4f72a81e0ca8dcb6bb | 661,194 |
def decode_spans(extractor, docs):
"""
:type params: dict
:type extractor: nlplingo.nn.extractor.Extractor
:type docs: list[nlplingo.text.text_theory.Document]
:type labels: list[str]
:rtype: (list[nlplingo.tasks.sequence.example.SequenceExample], list[list[str]])
"""
#model = SequenceM... | 460e2aba508eae97da68cf3bd52e7ff8bd9192c6 | 661,195 |
def get_keys_by_value(dict_of_elements, value_to_find):
"""
Parse a dict() to get keys of elements with a specified value
:param dict_of_elements:
:param value_to_find:
:return:
"""
list_of_keys = list()
list_of_items = dict_of_elements.items()
for item in list_of_items:
if i... | 6d547ca6c4cfc3f2cb4c62a8675e8d88e084e100 | 661,196 |
def compat_is_coresight(dcompat):
"""
Check if a device tree node claims compatibility with CoreSight.
We don't check for "arm" here because an architecture-licensee core might be
ETM-compatible but not be an Arm device.
We also expect to see "primecell".
"""
for dc in dcompat:
if dc... | d339acfc95976c27141b800527ba64c655c578a4 | 661,197 |
import re
def parse_ancestor_offsets(date_arg):
"""Parse any ancestor offsets in date runtime argument.
The date argument passed in doesn't *need* to have any of these
offsets.
Args:
date_arg: A string containing a date argument to be
parsed.
Returns:
A two-tuple con... | 855db68cc3245e06bb4742c2cc677571b31340e6 | 661,198 |
import os
def normpath(path):
"""
Normalize Path
"""
return os.path.abspath(os.path.normpath(path)) | e073a07784366b52a5941e74650aebf27f3bcb59 | 661,199 |
def create_new_file():
"""
A simple function to generate response from the user.
:return: bool
"""
response = input("\nIf you have ensured the file is writable press enter, "
"OR to create a new Excel type new filename OR to use the "
"existing file_name with a suffix ... | 6dbffc219dbdd07715d39b25b9ca8884403d2243 | 661,200 |
import torch
def match_corr(embed_ref, embed_srch):
""" Matches the two embeddings using the correlation layer. As per usual
it expects input tensors of the form [B, C, H, W].
Args:
embed_ref: (torch.Tensor) The embedding of the reference image, or
the template of reference (the averag... | 29c5889b62e8e4a82646d19404b0facb474e106a | 661,201 |
import yaml
def parse_yaml_config(config_file):
"""Parse YAML format file """
with open(config_file, "r") as f_handle:
try:
parsed_data = yaml.safe_load(f_handle)
except yaml.YAMLError as error:
print("Failed to parse builde cofig %s [%s]" % (config_file, error))
... | 45e5dd5fae432fefd7070dd43aa7b89480abfc74 | 661,202 |
import argparse
def get_parser():
"""
Get the parser.
:return: parser
:rtype: argparse.ArgumentParser
"""
parser = argparse.ArgumentParser(description = 'Read LMDBs.')
parser.add_argument('mode', default = 'read')
parser.add_argument('--lmdb', default = 'examples/cifar10/trai... | 93007eab7a498cb1c43c72979aa827ea8c30b9cc | 661,203 |
import numpy as np
def get_sample(df, col_name, n=100, seed=42):
"""Get a sample from a column of a dataframe.
It drops any numpy.nan entries before sampling. The sampling
is performed without replacement.
Example of numpydoc for those who haven't seen yet.
Parameters
----------... | 090dabf0b7ba9d9bf13d284a1a4d8877abedfe10 | 661,204 |
def sum_list(x):
"""Takes a list, and returns the sum of that list.
If x is empty list, return 0.
>>> sum_list([1, 2, 3, 4])
10
>>> sum_list([])
0
"""
return sum(x) | adc3b608afe0868898a9822d041634170256acf5 | 661,205 |
def InsertionSort(arr):
"""
To insert an array of integers
Input:
An array of integeres
Output:
Sorted array
"""
for i in range(1, len(arr)):
j = i - 1
temp = arr[i]
if temp != int(temp):
raise Exception("Array should have integers only")
... | 113f209ff55b3f75afa3628fc18f17f18381a314 | 661,206 |
def locate_tifs(file_list) -> list:
"""identify the .tif files in a list of files
Parameters
----------
file_list : list
list of files to parse
Returns
-------
list
list of files where the extension is .tif
"""
return list([s for s in file_list if '.tif' in s.lower... | 554244a7f321ac201f05a71f4585bc48d8feaf41 | 661,208 |
def skip_add(n):
""" Takes a number n and returns n + n-2 + n-4 + n-6 + ... + 0.
>>> skip_add(5) # 5 + 3 + 1 + 0
9
>>> skip_add(10) # 10 + 8 + 6 + 4 + 2 + 0
30
>>> # Do not use while/for loops!
>>> from construct_check import check
>>> # ban iteration
>>> check(this_file, 'skip_add... | 06f51a030ed0dfc4b92da9451af4c4a9ae83dc47 | 661,209 |
import re
def is_valid_domain_format(domain):
"""
Check whether a provided domain is valid.
Parameters
----------
domain : str
The domain against which to check.
Returns
-------
valid_domain : bool
Whether or not the domain provided is valid.
"""
if domain ==... | 0d823c85c206e16f45da47d6c5b84ce3021338cf | 661,210 |
import binascii
def macaddr_aton(mac_addr):
"""translate mac addr into network bits"""
return binascii.unhexlify(mac_addr.replace(':', '')) | eb169f4593e5a3bfafc7c3ec01f6565ccb9b2bf2 | 661,211 |
import io
def cloud_prep(wrd_tok_lst):
"""
do_cloud calls this to create kind of a text blob from tweets for cloud to process
:param wrd_tok_lst: preferably list of list of word tokens for tweets
:return:
"""
cloud_text = io.StringIO(newline="")
for tok_rec in wrd_tok_lst:
if isins... | ecf41f087e2c23e8c196ef4383692e170baade2b | 661,213 |
from typing import OrderedDict
def strip_values(it):
"""Convert OrderedDict of OrderedDict in dict of dict.
Parameters
----------
it :
return:
Returns
-------
"""
if isinstance(it, OrderedDict) or isinstance(it, dict):
new_dict = dict()
for key, value in it.i... | 7b4d78cb4231f31983b8b223a4a4c24f69587469 | 661,214 |
import resource
def li_worker(func, storage, time, memory, *args, **kwargs):
"""limits the memory consumption and time taken to execute given function
Args:
func (`function`): function to execute
storage (`list`): multiprocessing.Manager().List() to store the peak memory
time (`int`):... | 9a4d3622c7a9c144c684f2fd6ef8ed243d5b497f | 661,215 |
import random
def random_system(tree):
"""Returns random system node.
"""
systems = tree.xpath('.//system')
idx = random.randrange(0,len(systems))
return systems[idx] | 97d16be47082fb7cf56ac8a3ba9dc2b31298854c | 661,216 |
import math
def resize(size, hwRatio):
"""
Return the minimum size of image that is at least "size" but
maintains the provided aspect ratio
"""
if size[0] * hwRatio > size[1]:
return (size[0], int(math.ceil(size[0]*hwRatio)))
else:
return (int(math.ceil(1.0*size[1] / hwRatio)),... | 15db9734e6d0b7314d8a51f2b918d37cdf065620 | 661,217 |
def fun_acquire_negs_tra(tra_pois, all_pois_neighbors):
"""
根据每个poi邻居所组成的字典,顺序检索tra,从字典里取出某poi的邻居它自己的负样本。
"""
# item_num = len(all_pois_neighbors)
all_negs = []
for utras in tra_pois:
unegs = []
for i, utra in enumerate(utras):
negs = all_pois_neighbors[utra]
... | a372fc9a7b210fd1ad71464590461779f20730e1 | 661,218 |
import os
def can_use_network():
"""
Return True if network access is allowed
"""
if os.environ.get('NOSETESTS_NO_NETWORK', False):
return False
if os.environ.get('TRAVIS') == 'true':
return False
return True | 5aac27c18cb9c16009fef6b77c6e9f4d94e91f1e | 661,219 |
def blockchain_buyin_calc(desired_buyin: int):
"""blockchain.poker clean buy-in calculator with 2.5/2.5% tournament rake"""
fee = desired_buyin / 19
return round(desired_buyin + fee) | 8dfbcf6c4291ae37b609526ee83be5ad3ecf1b3c | 661,220 |
def _consume_until_marker(it, marker):
""" Consume data from the iterator, until marker is found (compared using
operator `is`).
Returns tuple of number of elements consumed before the marker and bool
indicating whether the marker was found (False means the iterator was
exhausted. """
i = -1
... | 230641058856c4576b5de4a186568707454a4f6f | 661,221 |
import email
def email_parser(raw_email):
"""parse email and return dict
@raw_email str
"""
msg = email.message_from_string(raw_email)
# print msg.keys()
return {
'subject': msg.get("subject"),
'from': msg.get('from'),
'to': msg.get('to'),
'date': msg.get('Date'... | 4ce739186557886e2d6ae194a163d5e3bd464afb | 661,222 |
from typing import Dict
from typing import Any
def deep_update(src: Dict[Any, Any], dest: Dict[Any, Any]) -> Dict[Any, Any]:
"""
Similar to ``dict.update``, except that we also ``deep_update``
any dictionaries we find inside of the destination. This is useful for
nested default settings, for instance.... | 73ca42fc487f3a5055528b43460c3fb12743b940 | 661,225 |
def train_collate_fn(batch):
"""
# collate_fn这个函数的输入就是一个list,list的长度是一个batch size,list中的每个元素都是__getitem__得到的结果
"""
imgs, pids = [],[]
for item in batch:
imgs.append(item['img'])
pids.append(item["pid"])
return list(imgs), list(pids) | 9e85efc7e0be6406cbc6f629ea5743d0d1f5043f | 661,226 |
def simpleArraySum(ar):
""":return the sum of all the numbers in the ar array as integer
:param ar: list() of items
:return: int() with the sum of all numbers
"""
_sum = 0
for item in ar:
try:
_sum += item
except:
pass
return int(_sum) | 4f26ee98e43f7334f969e0556f00c9a00330a229 | 661,227 |
async def create_index_weight(weights: dict[int, float]):
"""FastApi will convert and validate the JSON keys to ints."""
return weights | c1155a86b6b69878cfa7cf01416f7618361781db | 661,228 |
import os
def dist_input_arguments(parser):
""" Check input for estimation script.
"""
# Parse arguments
args = parser.parse_args()
# Distribute arguments
init_file = args.init_file
request = args.request
# Check attributes
assert os.path.exists(init_file)
assert request in [... | 3ff3bbed4fcb6b2342f5b7ac4534d31b0c298618 | 661,229 |
def spark_df_to_records(df):
"""Dump a Spark DF as a list of tuples representing rows ('records')."""
return [tuple(r) for r in df.collect()] | 31536a740fb997cbd4eb4e700068c7093bab054b | 661,230 |
def findRdkitMolRadicalAtomIds(rdkitMol):
"""Returns a list of atom ids with radical sites."""
radicalAtomIds = []
for atom in rdkitMol.GetAtoms():
if atom.GetNumRadicalElectrons() > 0:
radicalAtomIds.append(atom.GetIdx())
return radicalAtomIds | 8a8494c4c1a4a2a8af99e92498e0fb73ce45701c | 661,231 |
def region_slice(dset, x0=None, x1=None
, y0=None, y1=None):
"""
DESCRIPTION:
===========
Returns lon / lat rectangle slice of a xarray data set
USAGE:
=====
sliced_dataset = region(dset, x0, x1, y0, y1)
dset: xarray dataset
x0: long... | b98bcfe49fed526539ab121944c1e03f4ade6d0f | 661,233 |
def find_link(search, soup):
"""Find and return the first <a> tag's href element in `soup`."""
link = soup.find("a", text=lambda t: search in t)
return link.attrs["href"] | c0feb33f6f216b1a8665c061ac72e19ac4aaaf77 | 661,234 |
def _ev_remaining_range_supported(data):
"""Determine if remaining range is supported."""
return (
data["isElectric"]
and data["evStatus"]["chargeInfo"]["drivingRangeKm"] is not None
) | 4e038c5deea3899f54cd8616075536dced694525 | 661,235 |
def normalize_by_chrom_lengths(counts_dict, chrom_lengths_dict):
"""
Normalize the number of counts by the length of the chromosome
Parameters:
counts_dict(dict): count_chrom_alignments
chrom_lengths_dict(dict): output from determine_chrom_lengths()
Returns:
counts_dict (dict):... | c31a8fb8371960ce4740316abcb4dd9c35eff15a | 661,236 |
import numpy
def parse_tadm_weights(paramfile):
"""
Given the stdout output generated by ``tadm`` when training a
model, return a ``numpy`` array containing the corresponding weight
vector.
"""
weights = []
for line in paramfile:
weights.append(float(line.strip()))
return numpy... | 7f520f32d187b13a46665d3171387e412c0a8e3d | 661,237 |
def fpr_95_tpr(fpr,tpr):
"""
Helper method for FPR at TPR 95 computation
"""
a=[i for i,v in enumerate(tpr) if v > 0.95]
index=a[0]
return fpr[index] | 730b21f4d15397115610f69c01a089fbb537e0fc | 661,238 |
import random
def new_state(b_car, b_cost, b_tt):
"""
Computes a new beta using a random error. The new beta is part of the annealing process
:param b_car: beta parameter of the car
:param b_cost: beta parameter of the cost
:param b_tt: beta parameter of the travel time
:return: beta plus an e... | d5aceab8b98e47f2a22581c90d59b576e950b5cb | 661,239 |
def rule2string(lhs,rhs,isCopy=False):
"""
Makes a string from a rule. Used in printing and in making a dict of rules and probs.
Arguments:
lhs : string
rhs : string list
isCopy : boolean indicating a copy rule. Only used in cky_constituent_copy
"""
s = "%s->%s"%(lhs,".".join(rhs)... | 17b8cd69729c695866c4306f26f3806fa57352ee | 661,241 |
import requests
def scrape_results(params, useragent):
"""
Contacts the WP-JSON endpoint and returns the posts
"""
response = requests.get(
"https://udemy.coupons/wp-json/wp/v2/posts",
params=params,
headers={
"User-Agent": useragent
})
return response.j... | 9debf95d4369f14c51e518e51de528e0fc6fb002 | 661,242 |
import requests
def create_oauth_token(grant_type, client_id, client_secret, workspace_id=None, scopes='', username=None, password=None, uri='https://plaidcloud.com/oauth/token', proxy_settings=None):
"""Attempts to create an Oauth2 auth token using the provided data
This is designed primarily for password-t... | ce7d164166d8fefca87cddbbdae2ed6bfbaca23d | 661,243 |
def _get_group_key(revision, aggregate_type, computed_object):
"""Get key for aggregate objects group.
These groups are meant for easier calculation and optimization of
calculation of computed attributes.
"""
related_types = {computed_object, aggregate_type}
key = None
if revision.resource_type == aggreg... | df9f26e392d1390ba2ec33a8440ad9ad3a92bd89 | 661,244 |
from typing import List
def path_for_class(cls) -> List[str]:
"""
A list describing the import path for a given class.
Parameters
----------
cls
A class with some module path
Returns
-------
A list of modules terminating in the name of a class
"""
return f"{cls.__modu... | ddacd912e8742d0017cdb4d9eb7feb540fd78ae8 | 661,245 |
def _build_backend_map():
"""
The set of supported backends is defined here.
"""
return {"pytorch"} | a2073e85ae90cf843bc94e71f5cd1d86c04c0228 | 661,246 |
def change_to_revision(c):
"""Handle revision == None or any invalid value."""
try:
return int(str(c.revision).split('@')[-1])
except (ValueError, TypeError):
return 0 | 684d5fbb471d8365e430ca6a76313952cf9134e0 | 661,247 |
def ReOrderArray1(lists):
"""
新创建一个数组
时空复杂度均为O(n)
:param lists:
:return:
"""
if len(lists) == 0:
return []
newlist = []
for i in range(0, len(lists)):
if lists[i] % 2 == 1:
newlist.append(lists[i])
for i in range(0, len(lists)):
if lists[... | ea450daa49d354f6fef94a5b705a04790a73c004 | 661,248 |
def check_defaults(options, default):
"""Adds the values in default to options.
Args:
options (dict): base options.
default (dict): default options.
Returns:
dict: options with the missing values that are in default but not in
options.
"""
if options is None:
... | 44010dd033da1ec4dceaa1b89111157489b71e61 | 661,249 |
def st_align(self,t_start):
"""
Shifts the current spike train to a different t_start.
The duration remains the same, this is just a shift.
"""
diff = self.t_start - t_start
new_st = self[:] - diff
new_st.t_start = t_start
new_st.t_stop = self.t_stop - diff
return new_st | d6ada6279bd020a1f3ce854dc76028e44cf0c3f4 | 661,250 |
def uniq(x):
"""Remove duplicated items and return new list.
If there are duplicated items, first appeared item remains and
others are removed.
>>> uniq([1,2,3,3,2,4,1])
[1, 2, 3, 4]
"""
y=[]
for i in x:
if not y.count(i):
y.append(i)
return y | 4fa8d2e55518d2794175002e1826be59fb6ec542 | 661,251 |
def AlternatesInModel(model):
"""Returns a set of altloc names of all conformers in all chains.
:param model: pdb.hierarchy.model to search for alternates.
:return: Set of strings. The set is will include only the empty string if no
chains in the model have alternates. It has an additional entry for every alt... | 2a156ee07f5187f8d8a4f173cf338889e7a1f0ad | 661,252 |
import argparse
def parse_args():
""" Parses input arguments. """
parser = argparse.ArgumentParser(
description='This script uses output of test.py (mmdetection) to '
'calculate precision, recall and f-mean of predictions.')
parser.add_argument('config', help='test config file ... | 35f77251a51cc3a4956f851580c4d94f4135f36e | 661,253 |
def createCPEEntry():
"""Create empty CPE entry for easy initialisation."""
return {
"part": "",
"vendor": "",
"product": "",
"version": "",
"update": "",
"edition": "",
"language": "",
"softwareEdition": "",
"targetSoftware": "",
"... | 8c4af1353cc2f7e51d956abc8c58cc0dedac3003 | 661,254 |
from typing import Optional
def decode_bytes_str(input_value=None, charset='utf-8') -> Optional[str]:
"""
Decode input value to string using the given charset
:param charset: charset to use while decoding (defaults to utf-8)
:param input_value:
:return:
"""
if input_value is not None and n... | d5c8aadaf7cff5ef5b0003d5e8f74da35de37a5b | 661,255 |
import json
def get_participant_json():
"""
Loads JSON file with participants from Lookit v1
"""
try:
with open('../participants.json') as data_file:
data = json.load(data_file)
return data
except Exception:
print('../participants.json does not exist. Quitting..... | 5dc4cc2e4010b5a3e5bbf6d9370c0410d46da34f | 661,256 |
import os
def to_outname(folder, path, ext):
"""Convert filename.org to folder/filename.ext"""
return os.path.join(folder, os.path.splitext(os.path.split(path)[1])[0] + ext) | 2479dc1ffc2a4d62af75f601a263d4b2a5e41563 | 661,257 |
def convert_to_bin(int_value):
"""Retorna um Dictionary contendo uma propriedade cujo o valor é uma
lista de 0's e 1's e a outra propriedade é uma string de 0's e 1's
Keyword arguments:
int_value -- Um número inteiro em base decimal
"""
bin_arr = []
leftover = 0
result = int_value
while(result >= ... | 9b4a47f94ef1984af7e05c792634bc1d4d183936 | 661,258 |
def collapse_inner_join(loc_row, b_merge_fn):
"""
Collapse a merged row. The merge was through inner join so both sides are
known to exist
"""
final_geom, source = b_merge_fn(loc_row)
return {
"ts": loc_row.ts,
"longitude": final_geom.x,
"latitude": final_geom.y,
... | 84404abe75d223710ea15471f71696c4f2ebfa3b | 661,259 |
def instance_with_scenario_name(instance_name, scenario_name):
"""Format instance name that includes scenario."""
return f"{instance_name}-{scenario_name}" | 2ce13b41e604e7caaa2d9ccc1a7f042dfa223244 | 661,261 |
def nvmf_create_target(client,
name,
max_subsystems=0):
"""Create a new NVMe-oF Target.
Args:
name: Must be unique within the application
max_subsystems: Maximum number of NVMe-oF subsystems (e.g. 1024). default: 0 (Uses SPDK_NVMF_DEFAULT_MAX_SUBSYS... | 7b10540651b169406f942889caabef95506c4232 | 661,262 |
def confusion_matrix(classify=lambda document: False, documents=[(None, False)]):
""" Returns the performance of a binary classification task (i.e., predicts True or False)
as a tuple of (TP, TN, FP, FN):
- TP: true positives = correct hits,
- TN: true negatives = correct rejections,
... | 6521e24c3283fff6409609f9ace760b5d318c8f3 | 661,263 |
def setdeepr(obj, name, value):
"""Function to set deeper attributes, replaces setattr."""
names = name.split('.')
for name in names[:-1]:
obj = getattr(obj, name)
return setattr(obj, names[-1], value) | 933d93f7b020c63889ed4993048f9533343cc56f | 661,264 |
def correct_suffixes_in_list(input_pd, lst, substring="_index"):
"""
Remove suffixes from a list of column names if
they don't appear in a target dataframe
"""
dataframe_columns = list(input_pd.columns)
missing_from_dataframe = [item for item in lst
if item not i... | 9995bc2bbaa3aac99e86f279aa3071d44e428427 | 661,265 |
def pos_upper(num, string):
"""
Returns a string containing its first argument, and its second argument in upper case.
:param num: int
:param string: str
:return: str
"""
return f'{num}:{string.upper()}' | 06d6ee1f41fc2d81e39e39b35f339f138ae3606a | 661,267 |
def uncheckedcompute_bool() -> bool:
"""
post: __return__ == False
"""
return False | 18bc0e54cd002be1d8b30e89dc52fcb14393ae0a | 661,268 |
def replace_first_line(text: str, first_line: str) -> str:
"""Replaced the first line in 'text', setting it to 'first_line' instead.
A modified copy of the text is returned.
"""
lines = text.splitlines()
lines[0] = first_line
return '\n'.join(lines) | 5037ba434c34bfee6e89e7c1453f673748813cd8 | 661,269 |
def space_name(prefix, index):
"""Construct name of space from the prefix and its index."""
return "{p}{i}".format(p=prefix, i=index) | 079e36992f315a42abec40a4c1a58b11ecc7c5f4 | 661,270 |
import math
def square_distribution(size):
"""
Determines the "most square" x and y values which will make a grid of
the specified size.
args:
size - the size of the grid (int)
returns:
size_prime - True if size is prime (bool)
x ... | 8d61fae19bbd9e5c4b0300686f9318db30678100 | 661,271 |
def play_opposite_corner(computer_piece, board_state):
"""Play on the corner opposite of the user's last move"""
# All the possible corner pairs in Tic-Tac-Toe
corner_pairs = [[1, 9], [3, 7]]
squares_played = []
last_square_played = int(board_state[-1][1])
# Get all the squares from the board... | c7c19c579044b9315081383bd419581132dd6100 | 661,272 |
import re
def sanitise_input(question, input_type, characters=None, words=None):
"""
The keyboard input is only kept if the data abides by certain
rules otherwise nothing is returned.
If the expectation is a number an int or float is allowed.
Free form text allows only a set of re... | 06dd44fc161c5962f6f6102dfc0bb20c5f48e795 | 661,273 |
def get_shape_input_flatten():
"""Get shape of the dataset for Thyroid dataset"""
return (None, 36) | 9627c83f69b9bded139f777f2edf6f6f982188f7 | 661,274 |
import pickle
def get_reference_tree(file):
"""
load gating hierarchy from a pickle file to a nested list
:param file: filename of the pickle file
:return:
"""
file = open(file, 'rb')
return pickle.load(file) | 4bb16ae9aec2c45bfbf38b43b0d96277d1520055 | 661,275 |
import numpy as np
def temp_multivar_normal_dist_sampling(n_dim, n_size, mean_val=0, var_val=1):
"""
多次元正規分布の簡易的なサンプリングを行う.
各変数は独立, 平均と分散は共通のものを使用する.
np.random.multivariate_normalを使用.
Args:
n_dim : int
多次元正規分布の次元
n_size: array-like
mean_val: float, op... | 149066e4df760f86d2f1270ed01d00b7dc442e13 | 661,277 |
def is_in_subnet(ip, subnet):
"""True if given IP instance belongs to Subnet."""
return ip.bits == subnet.bits and (ip.value & subnet.mask) == subnet.base | ac1e4e00e6a2eff64f75c08bd4057aceadb823cf | 661,278 |
def write_header_prefixes(base_uri, base_prefix, prefixes):
"""
Write turtle-formatted header prefix string for list of (prefix, iri) tuples.
Parameter
---------
base_uri : string
base URI
base_prefix : string
base prefix
prefixes: list of 2 or 3-tuples
each tuple ... | f91387799e29f8f225d597debe4e9434309885a6 | 661,279 |
import yaml
def dump_to_string(data)-> str:
"""
Dumps 'data' object to yaml string
"""
result = yaml.safe_dump(data,
default_flow_style=False,
default_style=None,
explicit_start=None)
return result | 234927a81831d92820bf8599a7b27ee7e256793f | 661,280 |
def is_useless(ch):
"""
"""
code = ord(ch)
return code == 0xfffd or \
0x80 <= code <= 0x9F or \
0x00 <= code <= 0x1F | 2079a7afc75414615b9dd7d2802dd683d3c5be5e | 661,281 |
def xml_combine(root, elements):
"""Combine two xml elements and their subelements
This method will modify the 'root' argument and does
not return anything.
Args:
root (Element): The Element that will contain the merger
elements (Element or list): If an Element, merge all subelements o... | 9667c4cb8dd9cc02ea84808c866a23068b4f4830 | 661,282 |
def changed(requestContext, seriesList):
"""
Takes one metric or a wildcard seriesList.
Output 1 when the value changed, 0 when null or the same
Example:
.. code-block:: none
&target=changed(Server01.connections.handled)
"""
for series in seriesList:
series.name = "changed(%s)" % (series.name)... | 030c5c84afa59228f1aa87b7315abe6c6c49e170 | 661,283 |
def check_deal(cursor, dealid):
"""Check if deal was already logged."""
return cursor.execute(f"SELECT * FROM deals WHERE dealid = {dealid}").fetchone() | ce47288a0b4595f05d45abb518625a759516acfa | 661,284 |
def rescale(values, factor):
"""
Returns a new dictionary of scaled values
The values are scaled by the scale factor given
"""
return {key: value * float(factor) for (key, value) in values.iteritems()} | 4d1326512e755fabfdd475105cbf1f4502c37892 | 661,285 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.