content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
import optparse
import os
def process_options():
"""Process options from the command line."""
prog_desc = 'Downgrade buildsteps in a directory of pickled builds.'
usage = '%prog [options] [master name or filename]'
parser = optparse.OptionParser(usage=(usage + '\n\n' + prog_desc))
parser.add_option('--list-... | 4d6d1f0b23d029d09a6e6d4c3b04bad8c623a64b | 31,241 |
def pandas_mode_(self):
"""
Boolean attribute defining whether a model was trained with pandas data.
"""
return hasattr(self, 'feature_names_') or hasattr(self, 'target_names_') | 4d46d11cabc13c3cb088e9046cd22b7568cdbf70 | 31,243 |
def get_rios_coefficient_fieldnames():
"""
Returns a dictionary of the field names in the RIOS coefficient table
"""
rios_fields = {}
rios_fields["landuse"] = "lucode"
rios_fields["sedimentexport"] = "sed_exp"
rios_fields["sedimentretention"] = "sed_ret"
rios_fields["nitrateexport"] = "N... | fb2d5b5fdc6ae80d5be52a5119a857eb9b0d4017 | 31,244 |
def get_var_names(component, intent='input'):
"""
Get a list of input or output variable names from *component* (a BMI-like
object). Use the *intent* keyword to specify whether to return input or
output variable names. *intent* must be one of *input* or *output*.
"""
assert(intent in ['input', '... | 3dcb6f1a7f181a42813755f582e1a2ca03de10e0 | 31,245 |
import json
def _make_defined_data(data, defined_keys):
"""Takes the incoming tweet data and pulls out
all of the items which go into fields of the
db and puts the rest into a json string under other_data
"""
# This will be the data that goes directly into the model
defined_data = {}
# Thi... | de64349d85b5bf31849038523e91794d34388cf6 | 31,246 |
import os
def _convert_path_to_function(clipped_path):
"""
Parameters
----------
clipped_path : str
api route with absolute path clipped
Returns
-------
fn : str -- function name
"""
components = [comp for comp in clipped_path.split(os.sep) if comp]
return "_".join(com... | 77eb308f1f3e87464a5b19d963546a55c5fd83ba | 31,247 |
def _merge_cipher(clist):
"""Flatten 'clist' [List<List<int>>] and return the corresponding string [bytes]."""
cipher = [e for sublist in clist for e in sublist]
return bytes(cipher) | 060af5ad69b11592029e4aaf10fdfff8354378a9 | 31,249 |
def ABCDFrequencyList_to_HFrequencyList(ABCD_frequency_list):
""" Converts ABCD parameters into h-parameters. ABCD-parameters should be in the form [[f,A,B,C,D],...]
Returns data in the form
[[f,h11,h12,h21,h22],...]
"""
h_frequency_list=[]
for row in ABCD_frequency_list[:]:
[frequency,A... | d4f54e6864a34b8b24b1afe599a9338be52f29fd | 31,250 |
def trimCompressionSuffix(fileName):
"""
Trim .gz, .bz2, .tar.gz and .tar.bz2
"""
try:
if fileName[-3:] == ".gz":
fileName = fileName[:-3]
if fileName[-4:] == ".bz2":
fileName = fileName[:-4]
if fileName[-4:] == ".tar":
fileName = fileName[:-4]... | 21732f395429a2a45e5a95fa0c6653de09d4c2c4 | 31,254 |
def rgb_int2pct(rgbArr):
"""
converts RGB 255 values to a 0 to 1 scale
(255,255,255) --> (1,1,1)
"""
out = []
for rgb in rgbArr:
out.append((rgb[0]/255.0, rgb[1]/255.0, rgb[2]/255.0))
return out | cd008e7b65085154d685cfba125912f3f908dfa8 | 31,255 |
def confidence_for_uniform_audit(n,u,b):
"""
Return the chance of seeing one of b bad precincts in a
uniformly drawn sample of size u, from a set of size n.
"""
miss_prob = 1.0
for i in range(int(u)):
miss_prob *= float(n-b-i)/(n-i)
return 1.0 - miss_prob | 16fc15a6a2bd32f9202ff545ca77c9a65abb0ffc | 31,256 |
import operator
def evaluate(paeseTree):
"""
递归实现计算二叉树
:param paeseTree:
:return:
"""
opers = {'+': operator.add, '-': operator.sub,
'*': operator.mul, '/': operator.truediv
}
leftValue = paeseTree.getLeftNode()
rightValue = paeseTree.getRightNode()
if le... | 3e22ed9716bd05245779b82fde96636b840a9ea8 | 31,257 |
def get_token(request):
"""Get token from cookie or header."""
token = request.COOKIES.get('jwt-token')
if token is None:
token = request.META.get('HTTP_AUTHORIZATION')
return token | 591d6f282969b3994a0d4b86ccf6eda19fe93530 | 31,258 |
def tet_f(note, tuning=440):
"""Returns the frequency of a note given in scientific notation."""
# parse note as nth semitone from A0
letter = note[:-1]
octave = int(note[-1])
note_names = ["C", "C#", "D", "D#", "E",
"F", "F#", "G", "G#", "A", "A#", "B"]
letter_index = note_n... | 17dd86af181c9ed0420f6dcb9f0af07e46607c91 | 31,259 |
def StripSuffix(s: str, suffix: str):
"""Strips the provided suffix from s, if present at its end."""
if s.endswith(suffix):
return s[:-len(suffix)]
return s | bb4457b754cefa8c96df2e668a0a92e8a6713517 | 31,260 |
def something():
"""
>>> something()
False
"""
return False | 3ba6d16e419e7afa79d96b0ebb2ae38a10df73ab | 31,261 |
from typing import Dict
from typing import List
def iterate_parent(ontology_label: str, ontology: Dict[str, List[str]],
family_tree: List[str], mappings: Dict[str, Dict[str, str]]):
"""
Iterate ontology to find matched mapping.
Parameters
----------
ontology_label
label... | da641d14d978c9a6010707dd7bbdfb95bbdd1ea4 | 31,262 |
def extract_red_channel(input_im, bayer_pattern='grbg'):
"""
Extract and return the red channel from a Bayer image.
:param input_im: The input Bayer image.
:param bayer_pattern: The Bayer pattern of the image, either 'rggb' or 'bggr'.
:return: The extracted channel, of the same type as the image.
... | f879f26b42333a82d8f5d8653a6b1bf8479d4732 | 31,263 |
def count_bits_set_kernighan(n: int) -> int:
"""
https://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetKernighan
>>> count_bits_set_kernighan(0b101010101)
5
>>> count_bits_set_kernighan(2 << 63)
1
>>> count_bits_set_kernighan((2 << 63) - 1)
64
"""
c = 0
while n:
... | d676e182733f12bf90dfbc74a5c96f60cc6f5eb0 | 31,267 |
import hashlib
def generate_mutex_name(target_name, prefix=""):
"""
A mutex name must be a valid filesystem path, so, this generates a hash
that can be used in case the original name would have conflicts.
"""
if not isinstance(target_name, bytes):
target_name = target_name.encode("utf-8")... | e36f03fc03ff29535bc95adef3c4425efcf7bd3e | 31,268 |
import os
import subprocess
def run_cmd(cmd, file_out, file_err):
""" """
ensure_mkdir = lambda a: os.makedirs(
os.path.abspath(os.path.join(a, os.pardir)), exist_ok=True
)
ensure_mkdir(file_out)
ensure_mkdir(file_err)
with open(file_out, "w") as fout, open(file_err, "w") as ferr:
... | da3c88ed7d385a88f4e012e77ea5c073b5eedd26 | 31,269 |
import requests
def http_get(domain: str, path: str):
""" Fetch resource """
accepted_protocol = any(
[domain.startswith("http://"), domain.startswith("https://")]
)
if not accepted_protocol:
raise ValueError("Domain protocol not recognized (eg http://)")
print("Getting url %s%s" ... | 4d762eb192ef6721d9c930b2df76c13364c18de9 | 31,270 |
import operator
def get_out_operands(instruction_form):
"""Returns a list indicating which operands are written by this instruction form"""
return tuple(map(operator.attrgetter("is_output"), instruction_form.operands)) | df85c3021268d820f1c7ad0b820d343ae4041a82 | 31,271 |
def partition(arr, first, last):
"""."""
pivot_val = arr[first]
leftmark = first + 1
rightmark = last
done = False
while not done:
while leftmark <= rightmark and arr[leftmark] <= pivot_val:
# print(f'first while: lm{leftmark}, rm{rightmark}, {arr[leftmark]}, {pivot_val}')
... | 2e52e347c7b1ce41f9aa0823f492a0e7637ba67e | 31,273 |
import re
def split_list(separator, mylist, n=0):
"""
returns a list of string without white space of separator
:param separator: the string to remove
"""
list = []
for item in mylist:
if re.search(separator,item)is not None:
if n > 0:
word = re.sp... | 50ecd0ac7993097314655fab36ce0625a4fa0920 | 31,274 |
import pickle
def load_nodes(path):
"""
load nodes from storage file
"""
nodes = {}
with open(path, 'rb') as file:
nodes = pickle.load(file)
for node in nodes.values():
# reset old properties
node.online = False
node.index = None
node.clientcount = 0
... | 9f444f6f1a010d2822045ee359fa8bc109576bc9 | 31,275 |
def generate_places():
"""
because all the places are on a positive x y axis, distance is calculable as
(x1 - x) * (y1 - y) = euclidean distance where x and y is the child, and x1 and y1 is the place
:return:
"""
places = {}
places['park_b'] = [0.8,0.7]
places['park_a'] = [0.6,1.0]
p... | b6e8fde4679099aa0e60e5c6c27d4446250a3c78 | 31,276 |
def get_all_countries(cache):
"""Just gets all possible countries"""
countries = set()
for tile, attribs in cache.iteritems():
countries.update(attribs['countries'])
countries = sorted(list(countries))
return countries | 2ab6448ab4c75bfd47b0dc6500a7e5134997995e | 31,277 |
from datetime import datetime
import pytz
def format_absolute_datetime(date_time: datetime) -> str:
"""Generate a human-readable absolute time string."""
now = datetime.now(tz=pytz.utc)
format_str = ""
if date_time.date() != now.date():
format_str += "%Y-%m-%d"
time_part = date_time.t... | 8d9ead27c415225d211fe45195a6c2df5e3e17d1 | 31,278 |
def sum_elements(elems):
"""Sum numbers stored as sequence of two digits pairs."""
nums = [a * 100 + b for a, b in zip(elems, elems[1:])]
if len(nums) == len(set(nums)):
return sum(nums)
return 0 | 7116b16c94e2145794a0ea092404bd938349b1eb | 31,279 |
def insertion_sort(l):
"""
@param {list} l - the list to sort
@return {tuple(list, number)} - Tuple(sorted list, number of iterations)
"""
sweeps = 0
for i in range(1, len(l)):
sweeps += 1
current_val = l[i]
j = i - 1
while (j >= 0) and (l[j] > current_val):
... | c8c0bf258c012561096e06d7a1366dd8556b870b | 31,281 |
import gzip
def gzip_file(file, file_name):
""" Gzip a file
:param file file:
:param str file_name:
:return: the gzipped file
:rtype: gzip file
"""
with gzip.open(file_name + '.gz', 'wb') as gzipped_file:
gzipped_file.writelines(file)
return gzipped_file | d1569b3ef8ebed46eb7a3fd128479d3999fb228c | 31,282 |
import csv
def computeCoverage(filename) :
"""Parses a jacoco.csv file and computes code coverage
percentages. Returns: coverage, branchCoverage. The coverage
is instruction coverage.
Keyword arguments:
filename - The name, including path, of the jacoco.csv
"""
missed_tested = 0
miss... | 6942732b9017e98e35440b6bd6843ae6ab48c9df | 31,286 |
import json
def to_review_json(s):
"""
Converts the string to json
:param s: A string
:return: A json formatted string representation of the object
"""
b = {}
if s:
b.update({"reviewComment": s})
return json.dumps(b)
else:
return None | 384f8e4f8d625081fa858e184ae7a559f590a420 | 31,288 |
def invertMove(move):
"""--> inverted move. (0 becomes1 and 1 becomes 0)"""
if move == 0: return 1
else: return 0 | 5a382f17a4be441287ffc8f899ab57acd0c1ce27 | 31,289 |
def get_my_profile(username):
"""Funkcija glede na vlogo vrača podatke za kartico osebe."""
return None | 52666ea4dc0d89f8c200eaa3b023f53f522309cc | 31,290 |
from typing import Callable
def identity(func: Callable) -> Callable:
"""
Helper function to be used when `settings.CHECK_CSRF` is `False`; in this case the
dispatch decorators should operate just as normally and therefore we return the
function (or method) itself as if nothing really changed.
Ar... | 7a7966879a82575512f14662a8c3fa22ffd8c3bc | 31,291 |
def INSPUR_HTTP_CONTENT_CHECK(content):
"""判断浪潮的登录响应报文"""
if content.find("SESSIN_COOKIE") >= 0 and content.find("Failure_Login_IPMI_Then_LDAP_then_Active_Directory_Radius") < 0:
return 0
else:
return -1 | 85e56bfcc0226306d1666ad4fc6fd69ae1713501 | 31,292 |
def _build_index_vcf_command_str(bgzipped_vcf):
"""Generate command string to index vcf file."""
command = " ".join([
'tabix -p vcf', bgzipped_vcf
])
return command | dbc1a370b2d97ffa5726d625135a4b484f41b5c6 | 31,293 |
def is_from(category, symbol):
"""Checks if the symbol is from the category given.
Args:
category (dict): The dictionary of the category to check.
symbol (str): The symbol or word given to analyze.
Returns:
bool: Whether the symbol is part of the category given.
"""
tr... | 69a2e9905a86d149aac6aff215e5f07542b3f8ab | 31,295 |
def format_list_of_seq(list_of_seq):
"""
:param list_of_seq:
:return: removes \n and converts to uppercase
"""
for i, seq in enumerate(list_of_seq):
list_of_seq[i] = seq.strip().upper()
return list_of_seq | 9c4252ea1234ca9dc2a1eb98b690202ddb7f4485 | 31,296 |
import re
def check_money(msg):
"""
checkMoney
:param msg:
:return:
"""
return re.search(r'经济', msg) or re.search(r'钱', msg) or re.search(r'利润', msg) | d022df389de57cd2ca9ab89f4a29f790fe7101a5 | 31,297 |
import os
def _get_size(filename):
"""Return the file size in bytes"""
return os.path.getsize(filename) | 4baedbe5a412727d19d2a7e61e8c55675959452b | 31,301 |
def varassign(v,X,E,rho, argument):
"""!
Assigns input to specified gate set variables
Parameters
-------
v : numpy array
New set of variables
X : numpy array
Current gate estimate
E : numpy array
Current POVM estimate
rho : numpy array
Current initial ... | ee71ca488883e12fb036acc31a1ec96f184bc4f0 | 31,302 |
def newman_conway(num):
""" Returns a list of the Newman Conway numbers for the given value.
Time Complexity: ?
Space Complexity: ?
"""
if num == 0:
raise ValueError
arr = [0,1,1]
for i in range(3,num + 1):
r = arr[arr[i-1]]+arr[i-arr[i-1]]
arr.append(r)
... | 77c2f26103a7b2d6ff340e46a8e999fa6d7191a7 | 31,303 |
def P_to_a(P, Mstar):
"""
Convenience function to convert periods to semimajor axis from Kepler's Law
Parameters
----------
P : array-like
orbital periods [days]
Mstar : float
stellar mass [solar masses]
Returns
-------
a : array-like
semi-major ... | 0596930a7f84679db0e050974a44ae8dfa437e10 | 31,304 |
def html_spam_guard(addr, entities_only=False):
"""Return a spam-protected version of email ADDR that renders the
same in HTML as the original address. If ENTITIES_ONLY, use a less
thorough mangling scheme involving entities only, avoiding the use
of tags."""
if entities_only:
def mangle(x):
return... | 239115425ab9a39fdea1a70ba07e648a63e91d2b | 31,305 |
def person_image_file(person):
"""Finds primary person image file name.
Scans INDI's OBJE records and finds "best" FILE record from those.
Parameters
----------
person : `ged4py.model.Individual`
INDI record representation.
Returns
-------
file_name : `str` or ``None``
... | fb8682f66a938ae14690486880d62c6ec4e6995f | 31,307 |
from typing import Union
import torch
def torch_advantage_estimate(
signal,
non_terminal,
value_estimate,
*,
discount_factor: float = 0.95,
tau: float = 0.97,
device: Union[str, torch.device] = "cpu",
normalise: bool = True,
divide_by_zero_safety: float = 1e-10,
):
"""
Computes... | ca538453364afa73f132c3e0b196782dd9747717 | 31,308 |
def update_sheet(service, sheet_id, range_string, body):
"""Fires a spreadsheet update request through the Google API client."""
return service.spreadsheets().values().update(spreadsheetId=sheet_id,
range=range_string,
... | 2203b01e430afdf48e1bbac5a33f00ba23ff58a9 | 31,309 |
import pandas
def combine_wq(wq, external, external_site_col):
"""
Combines CVC water quality dataframes with the `tidy`
attributes of a `bmpdb` or `nsqd` object.
wq : pandas.DataFrame
A dataframe of CVC water quality data
external : nsqd or bmpdb object
external_site_col : str
... | 3fdcd754e257d61ec40a4cd15b55f52a5ad1a2be | 31,310 |
def entity(reference):
"""Return a numeric (&#reference;) or symbolic: (&reference;) entity,
depending on the reference's type
"""
try:
return '&#{0:d};'.format(reference)
except ValueError:
return '&{0};'.format(reference)
# | 1b547a9506badd9fc3ddd575c3e67acebe6af539 | 31,312 |
import torch
def aggregate(d_p, crit_buf, func, kappa=1.0):
"""
Reusable aggregation function to join current iteration gradient and critical
gradients
:param d_p: Current-iteration gradient
:param crit_buf: Buffer of Critical Gradients
:param func: String name of aggregation. Should be "sum"... | 96d3a22724cf866079c90d94bc668910456abe1e | 31,313 |
import time
def retry(function, exception, max_attempts=5, interval_seconds=5):
"""
Retry function up to max_attempts if exception is caught
"""
for attempt in range(max_attempts):
try:
return function()
except exception as e:
assert attempt < (max_attempts - 1)... | 5d33e2d2909a8b2a377e2b5127f52f5f2c23eabd | 31,314 |
def obstacle_generator(obstacle_map):
"""
Generates a grid map with obstacles for testing
Args:
obstacle_map: Numpy array of zeros of shape atleast 100x100x100
Returns:
Numpy array with obstacles marked as 1
"""
for i in range(20, 41):
for j in range(20, 41):
... | 8d9a8cbf0a61fe3918d18ee575a9fad9e464e1a8 | 31,315 |
import pandas
def getDataFrame(arr):
"""
Convenience method to print out wide 2D matrix using pandas
:param arr: 2D array
"""
pandas.set_option('display.width', 500)
pd = pandas.DataFrame(arr)
return pd | 9d9015de07330044da4f37234a6044f1051a0e5a | 31,316 |
def remove_added_loadgen(net_t, loadorgen):
"""
Removes load or sgen namned Cap test
INPUT
net_t (PP net) - Pandapower net
loadorgen (str) - 'sgen' or 'load' for generation or load for additional capacity connected
OUTPUT
net_t (PP net) - Updated Pandapower net
"""
if l... | 73ccf198c096454fef4676a18355c6359a076b2c | 31,317 |
def Echovaluate(operation):
"""
Evaluate an expression
"""
return eval(operation) | 52cc43c31997f410f409c4d5f0ca40ce7c90d492 | 31,319 |
def get_b(pvalue,siglevel):
"""Bonferroni correction"""
pvalue = sorted(pvalue, key = lambda x: x[-1])
#y=0
pp=1.0
for i in pvalue:
p=float(i[-1])*len(pvalue)
if p<=siglevel:
i.append(p)
i.append('yes')
if p<pp: pp=p
else:
i.append(p)
i.append('no')
return pvalue | a8ad34eeb0a93cc1165aa87c160738cdbf04ed39 | 31,321 |
from typing import Optional
def _term_converter(term: Optional[int]) -> Optional[int]:
"""
Converter function for ``term`` in :class:`~.BaseProduct``.
:param term: The number of months that a product lasts for if it is fixed length.
"""
if term is None:
return None
else:
return int(term) | 65277a31fe4666d410c9aa46a8b01fe59dbcb4fc | 31,322 |
def millerORweber(ITN):
"""
Determine which kind of coordinates to use
"""
if ITN > 194 or ITN < 143:
return "m" #"rest"
return "w" #"hP, hR" | cf8001cd61f98dddff790bc2e628d3ced267590a | 31,323 |
def generate_block_data(data, index, blocktype):
"""Generates the largest block possible starting at index in data.
returns (output, new_index) where output is the generated block and
new_index points to where the next block in data would be extracted"""
output = bytearray()
output += b'\x3c'
ou... | ddf6af222b22be7e1c73ee98c3ebd982ea23fe5b | 31,325 |
def sort_tasks(tasks):
"""sort task with task_priority
each task contain type & priority
sort task with task_priority
Args:
tasks (List[function]): task contain type & priority
Returns:
List[function]: sorted tasks
"""
return sorted(tasks, key=lambda task: task._task_prior... | 487d60c6508df3346852d93b424cad7a50589c7b | 31,327 |
import json
def to_json_fragment(Entries, stripdepth=1):
"""Return a json fragment representing the provided objects"""
return json.dumps(Entries, indent=4)[stripdepth:][:-stripdepth] | 0b5cfe4ce9cec7899b0b14612e7898c29d76f862 | 31,328 |
from warnings import warn
def pc2in(picas):
"""
Converts picas to inches
Parameters
----------
picas : int or float
dimension in picas
Returns
-------
inches : float
dimensions in inches
"""
if picas not in [19, 27, 33, 39, 68]:
warn("Not a standard AM... | 4fee36743e00b263f0f46fca90bf07edca083002 | 31,329 |
def validate_reading(data):
"""Some sensors read "Disabled"."""
return data != 'Disabled' | 4ce007332c000d679d2c067009e901f02d38a407 | 31,331 |
def support_count(itemset, transactions):
"""
Count support count for itemset
:param itemset: items to measure support count for
:param transactions: list of sets (all transactions)
>>> simple_transactions = ['ABC', 'BC', 'BD', 'D']
>>> [support_count(item, simple_transactions) for item in 'AB... | 2d533a81a646b1973980386c9b85998d8fb65be0 | 31,332 |
from typing import Counter
def total_useful_clusters(model):
"""A useful cluster here is defined as being a cluster with > 1 member."""
clusters = Counter(model.labels_)
useful_clusters = 0
for cluster_num, total_members in clusters.items():
if total_members > 1:
useful_clusters +... | 93df3354c37f5f252f2071b50b7937c61ce81946 | 31,333 |
def hours(time_str):
"""
Get hours from time.
time_str: str (hh:mm:ss)
"""
h, m, s = [int(x) for x in time_str.split(':')]
return(h + m/60.0 + s/3600.0) | c5f95ac4bed1198eba616f959595d6ce7a9c79fd | 31,335 |
def update_params(paramDict, keys, indices, values):
"""paramDict: gets modified and returned.
keys: indicate which items in paramDict to be modified.
indices: parallel to keys; indicate which element in paramDict[key] to be modified.
values: parallel to above; indicate new value to substitute."""
assert len(keys)... | d988f090dcaad9232c6a2af334fbdacc8a0cd412 | 31,336 |
from typing import Mapping
from typing import Dict
from typing import List
def convert_mime_db(mime_db: Mapping) -> Dict[str, List[str]]:
"""Convert mime-db value 'extensions' to become a key
and origin mimetype key to dict value as item of list.
"""
converted_db: Dict[str, List[str]] = {}
for mim... | 65a6332e0463f32be1b27b39b44f95917995118d | 31,338 |
def get_vector(tensor):
"""
- input: torch.tensor(n_time_steps, n_samples, n_features)
- output: np.ndarray(n_time_steps * n_samples, n_features)
where:
output[0:n_samples, :] = input[0, 0:n_samples, :],
output[n_samples:2*n_samples,:] = input[1, 0:n_samples, :],
..."""
n_features = ten... | 89da4391bbd8e99212f7bebb0f93a511e1712ff5 | 31,339 |
import redis # lazy import so that redis need not be available
import sys
import subprocess
import os
import time
def redis_connect(host="localhost", port=6379, maxmemory=4.0, **kwargs):
"""
Open a redis connection.
If host is localhost, then try starting the redis server.
If redis is unavailable, ... | 25a7aa5585fe1698391c1ecd7735825d622f4191 | 31,340 |
import re
def get_nom_val(atrv):
"""Given a string containing a nominal type, returns a tuple of the
possible values.
A nominal type is defined as something framed between braces ({}).
Parameters
----------
atrv : str
Nominal type definition
Returns
-------
poss_vals : tu... | 4b059ff48779ce631ed95c4bc9471eafdf617ecb | 31,341 |
def to_array(an_object):
"""convert a reader iterator to an array"""
array = []
for row in an_object:
array.append(row)
return array | 6bd242eb4d33f8aacb50df7434a0452af8d8c33f | 31,342 |
import re
import string
from collections import Counter
def count_words(phrase):
"""
Returns a dict with count of each word in a phrase
keys are the words and values the count of occurrence.
"""
phrase = phrase.lower()
tokens = re.findall(r'[0-9a-zA-Z\']+', phrase)
tokens = [word.strip(str... | b8b7abaa7330906335ed38c59fdc58a6b47dc48b | 31,344 |
def IsTrivialAttrSpec(attr):
"""Determines whether a given attr only has its name field set.
Args:
attr: an AttrSpec instance.
Returns:
true iff the only field that is set is the name field.
"""
return (attr.DESCRIPTOR.full_name == 'amp.validator.AttrSpec' and
attr.HasField('name') and len(... | 1ff22c6f7cb5d6457430a8d4220fb6caa798cc1f | 31,349 |
def _generate_mark_list(data_list):
"""Generate a mark list to filter a specific operation
:param data_list:
:return:
"""
mark_list = []
name_set = {'q3007', 'q2994', 'q3006', 'q2972', 'q3003', 'q2963', 'q2989', 'q2901', 'q2994', 'q3001'}
for d in data_list:
if d.name[:5] in name_se... | fba3335cdfc882845414adbd91617e10942bd4f1 | 31,350 |
import traceback
def format_traceback_the_way_python_does(type, exc, tb):
"""
Returns a traceback that looks like the one python gives you in the shell, e.g.
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
NameError: name 'name' is not defined
"""
tb = ''.join(tra... | e11783b2215bcd22cd08f7e8657d6ff7a5fc7f35 | 31,352 |
def _get_xml_declaration(version='1.0', encoding='UTF-8'):
"""Gets XML declaration (for the specified version and encoding).
:param version: XML version
:param encoding: encoding
:return: XML declaration
:rtype: str
"""
return '<?xml version="' + version + '" encoding="' + encoding + '"?>' | 2f9125ca02624cd9c74a80fe9668a6801220f898 | 31,353 |
def get_study_collections(studies, irods_backend):
"""Return a list of all study collection names."""
return [irods_backend.get_path(s) for s in studies] | 53ff6851d12612467d045604c676ea7ed6b0081c | 31,354 |
def _set_stats(context, key):
"""
Users select stats to run from config field in manifest.json. All string options
are handled by the "function_options" field. Other types (with input values) are
handled by this method.
Args:
key (str): Statistic requested, which is not handled by the "func... | c4f7ba90172f5ad85e41ac15d8b948bc1e5170d9 | 31,356 |
def discrete(items):
"""Sweeps over discrete variable."""
return items | 7fc0a6393bc404ee0dfa3e72953a6a13af6a15d6 | 31,357 |
import logging
def get_logger(logger_name: str) -> logging.Logger:
"""Return the logger with the name specified by logger_name arg.
Args:
logger_name: The name of logger.
Returns:
Logger reformatted for this package.
"""
logger = logging.getLogger(logger_name)
logger.propagat... | 505f6c89c46dd95c86a5b9193389b64142c31d81 | 31,358 |
import math
def wien(x):
"""
Wien's displacement constant is defined by b = h * c / (k_B * x), where
x is described by this nonlinear equation.
"""
return 5 * math.exp(-x) + x - 5 | 6db7749651dd72fbaee1971bc940b59944a52db3 | 31,362 |
def asfolder(folder):
"""
Add "/" at the end of the folder if not inserted
:param folder: the folder name
:type folder: str
:return: file names with / at the end
:rtype: str
"""
if folder[-1] != "/":
return (folder + "/")
else:
return (folder) | 07340a8c9b21bcc1d7be210bc7f9fa80378cb3a8 | 31,364 |
def tieBreak(sets, l, i, j, distM):
"""
Tie-breaking operation betwen two cometing sets for inclusion of new image
Input: {sets, l, i, j, distM}: {sets = collection of all different sets
(clusters) as a list, l = current images to be assigned clusters,
i,j = index of clusters competing for the new i... | 2957858a97201ca12029e9a4c69b9300d441f2a6 | 31,365 |
import torch
def split(value, num_or_size_splits, axis=0):
"""
Splits a tensor into sub tensors.
Parameters
----------
value : tensor
The Tensor to split.
num_or_size_splits : list
Either an integer indicating the number of splits along split_dim or a 1-D integer Tensor or
... | b997285da46db1e20ca92916f46ebc51b8840786 | 31,366 |
def get_indicators():
"""Get recommendations from db."""
return {
"appearance": {
"grammar": {
"name": "Grammar",
"values": {
"0": {"label": "Poor"},
"1": {"label": "Decent"},
"2": {"label": "Proper"}... | f2396886191b55c8062b5ecaef42ff7d6d601bca | 31,367 |
import requests
def parse_configdb(configdb_address='http://configdb.lco.gtn/sites/'):
"""
Parse the contents of the configdb.
Parameters
----------
configdb_address : str
URL of the configdb, must be inside LCOGT VPN
Returns
-------
sites : list of dicts
... | 501f9217901f0db30e2bddfebb0a85fbb266a766 | 31,371 |
def fleur_local_code(create_or_fake_local_code, pytestconfig):
"""
Create or load Fleur code
"""
executable = 'fleur' # name of the KKRhost executable
exec_rel_path = 'local_exe/' # location where it is found
entrypoint = 'fleur.fleur' # entrypoint
fleur_code = create_or_fake_local_code(e... | 61c87db29678082746ff85ff3f6d91f1d68ccb85 | 31,373 |
def reverseStringv1(a_string):
"""assumes a_string is a string
returns a string, the reverse of a_string"""
return a_string[::-1] | e4c8ff9a496e54170ba1fdc988f4be9dd2437f34 | 31,374 |
from functools import reduce
def chain_maps(*args):
"""Similar to collections.ChainMap but returned map is a separate copy (ie. changes
to original dicts don't change the dict returned from this function)."""
def merge(d1, d2):
d1.update(d2)
return d1
return reduce(merge, reversed(arg... | a91584647e9d3f83f99680d28960db1b64ef923b | 31,376 |
def test_function_arbitrary_arguments():
"""Arbitrary Argument Lists"""
# When a final formal parameter of the form **name is present, it receives a dictionary
# containing all keyword arguments except for those corresponding to a formal parameter.
# This may be combined with a formal parameter of the ... | a3729f1d7846a41e45db65382ada9cbad8b877f0 | 31,377 |
import numpy
def k_max_index(array, k):
""" Return index of max values, more eficient. Example: k_max_index2([2, 4, 5, 1, 8], 2)"""
array = numpy.array(array)
if len(array) < k:
k = len(array)
indexs = numpy.argpartition(array, -k)[-k:]
return indexs[numpy.argsort(-array[indexs])].tolist() | baf4db247a566193a39440fdc0049bd3de1a98bf | 31,379 |
def tatextcleaner(string):
""""Cleaner function, add desc"""
temp = string
if(True): # cleaned, removes iban, bic and uci
if("IBAN" in string and "BIC" in string):
temp = string[:string.index("IBAN")]
temp += " || "
if("UCI" in string):
tem... | 9f34f698c28e6105f46568c7eae933693c35d892 | 31,380 |
import random
def sample_with_replacement(population, k):
""" Sample <k> items from iterable <population> with replacement """
n = len(population)
pop = list(population)
return [pop[int(n * random.random())] for _ in range(k)] | 4114a49faae9981dc2f850db4465ec1ccdc7101c | 31,381 |
def sin_series(x):
"""Returns sin(x) for x in range -pi/2 .. pi/2"""
# https://en.wikipedia.org/wiki/Sine#Series_definition
C=[1.,0.16666666666666666,0.05,0.023809523809523808,0.013888888888888888,0.00909090909090909,0.00641025641025641,0.004761904761904762,0.003676470588235294,0.0029239766081871343,0.00238... | d0a2f7aaa0b86494eae8562cc9bf3d0105462606 | 31,383 |
def NDVI(spectra):
"""Normalized Difference Vegetation Index"""
ndvi = ((spectra.iloc[550,] - spectra.iloc[330,])/(spectra.iloc[550,] + spectra.iloc[330,]))
return ndvi | 424e1f0a583907743d35c2c5a0426adadfd6895b | 31,385 |
import argparse
def cmdLineParse():
"""
Command line parser
"""
parser = argparse.ArgumentParser(description="""
Stage and verify DEM for processing. """,
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_... | 243881de15733e7432c218c362e7cef33ac61f0e | 31,386 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.