content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def meanEdgeValue(imgdata, w=0):
"""
get the average values for the edges of width = w pixels
"""
xmax = imgdata.shape[0]
ymax = imgdata.shape[1]
leftEdgeAvg = (imgdata[0:xmax, 0:w]).mean()
rightEdgeAvg = (imgdata[0:xmax, ymax-w:ymax]).mean()
topEdgeAvg = (imgdata[0:w, 0:ymax]).mean()
b... | dcd314402b23e61f84b0557d6ee622ad4e601de6 | 670,928 |
import sys
import io
import tokenize
def stdin_get_value() -> str:
"""Get and cache it so plugins can use it."""
stdin_value = sys.stdin.buffer.read()
fd = io.BytesIO(stdin_value)
try:
coding, _ = tokenize.detect_encoding(fd.readline)
fd.seek(0)
return io.TextIOWrapper(fd, codi... | 295d4747a5cb8a2034c3372087347ebc4c8a95ee | 670,929 |
import copy
def get_fillin_graph2(old_graph, peo):
"""
Provided a graph and an order of its indices, returns a
triangulation of that graph corresponding to the order.
The algorithm is copied from
"Simple Linear Time Algorithm To Test Chordality of Graph"
by R. E. Tarjan and M. Yannakakis
... | 737b86b9fe1aa5eb02f2e4a527c49abae383c040 | 670,932 |
def isint(val):
"""
check if the entry can become an integer (integer or string of integer)
Parameters
----------
val
an entry of any type
Returns
-------
bool
True if the input can become an integer, False otherwise
"""
try:
int(val)
return Tru... | 5ca720162b31fdaae5c536d3e89c01ff12dad059 | 670,933 |
def simp38(h, y1, y2, y3, y4):
""" h is defined as (b-a) in which a and b are the limits of integration """
return h * (y1 + 3*y2 + 3*y3 + y4)/8 | 16f55c690e01ed19ba44f6a2a19007e463c5e1a3 | 670,934 |
def update_vocab(vocab):
"""Add relevant special tokens to vocab."""
vocab_size = len(vocab)
vocab["<unk>"] = vocab_size
vocab["<s>"] = vocab_size + 1
vocab["</s>"] = vocab_size + 2
return vocab | c8ce10a70e522301e7fb78b66bd35c11aa5c12f6 | 670,936 |
def json_for_user(user, session_id):
""" Convert the provided user to a dictionary (for JSON)
Args:
user: the User object
Returns:
An object containing user details
"""
return {
"user_id": user.user_id,
"name": user.name,
"title": user.title,... | 7d18539352b17d5d84c2041256645ae56300ea37 | 670,937 |
def parse_vec(s, size = 3):
"""Parse a vector and return it as a list of values. Upon failure, return a
vector containing all 0s.
"""
if s.count(" ") < size - 1:
return [0] * size
try:
return [float(value) for value in s.split(" ")]
except ValueError:
return [0] * size | 5aec04e1c43067fb58a671393b266354f96c94f2 | 670,938 |
def group_count(elements, group=None):
"""
Groups the elements of elements in the groups dictionary
:param List[List[str]] elements: A list of str or a recursive list of lists of str
:param Dict[] group: where to group the elements, used for recursion
:return Dict[str, int]: dictionary with the numb... | 664ea51aa4b2c891c9caa2560cdb3d3e70d8b91e | 670,939 |
from typing import Callable
def _integrate(function: Callable[[float, ], float],
start: float, end: float, n: int) -> float:
"""
Calculate defined integral of given `function` in range of
[start, end]
:param function: Function to integrate
:param start: Left bound
:param end: R... | 34dd7c962dd329cff73c4f9c4a4878d6aefd7143 | 670,940 |
def _rectangle_rule(func, a, b, nseg, frac):
"""Обобщённое правило прямоугольников."""
dx = 1.0 * (b - a) / nseg
sum = 0.0
xstart = a + frac * dx # 0 <= frac <= 1 задаёт долю смещения точки,
# в которой вычисляется функция,
# от левого края отрезка ... | 4140d17c01b73deeddf5ff34b8591a87f7dea09e | 670,942 |
import os
def optimize_endpoint(xyz_file, n_atoms, atom_labels, method):
"""
After the IRC finishes: compare the resulting reactant and product
structure with the original reactant and product structures
Use xyz2mol in order to compare the smiles
submits the .com file created using the bash submit... | 61cbe87f4fa92773b6e2b5f09730fb2306e18616 | 670,943 |
def reject(position_store, particles, random_particle):
"""Reject the move and return the particle to the original place.
Parameters
----------
position_store: float, array_like
The x and y positions previously held by the particle that has moved.
particles: util.particle.dt, array_like
... | b268d9125d70b872efa8737aa622e946abbd9b63 | 670,944 |
from typing import Tuple
from typing import Dict
def parse_method_vars(names: Tuple[str, ...]) -> Dict[str, Tuple[int, ...]]:
"""
Parses out names ending in `__` from list of CSV file column names.
Return a dict mapping sampler variable name to Stan CSV file column, using
zero-based column indexing.
... | ed2131f156a3e809d8481af4898b29a6afd60f16 | 670,945 |
def filterResultsByOptions(runSets, form, allOptions):
"""
Filters out result sets that don't match the command line options selected
by the form input parameters.
For options with no value selected (e.g., none of the --unroll checkboxes
were checked), result sets will not be filtered based on thi... | 799431594b4916af729455f456e9615ed0fea602 | 670,946 |
from functools import reduce
def factors(n):
"""
Decomposes a number into its factors.
:param n: Number to decompose.
:type n: int
:return: List of values into which n can be decomposed.
:rtype: list
"""
return set(reduce(list.__add__,
([i, n//i] for i in range(1, int(... | 7526528966fefb32d430f3a58735ae312ed02280 | 670,947 |
import functools
def is_instrument(func):
"""Wrapper for instrument determining functions
Tries the function, if there is a :class:`TypeError`, then return False.
The :class:`TypeError` will occur when the label's :meth:`get` method
returns ``None``
"""
@functools.wraps(func)
def wrapper... | 88fc95183a019c8512e7061461e366da84ca712e | 670,948 |
def compute_rank_measures_(args_list):
"""
The function for parallel computation of ranking measures.
"""
_, _, _, _, k_list, return_topk = args_list[0]
precision_list = {k: [] for k in k_list}
recall_list = {k: [] for k in k_list}
ranking_list = []
for args in args_list:
if args... | bf29a24e35f4f2ad2e905ba6f627ad96c028c060 | 670,949 |
def stats(list_name):
"""Takes a list of an international currency,
retrives the 10 most recent entries, five days
calculates the max(), the min() and finally the mean
it returns all three plus the generated list
Arguments:
list_name {float} -- List of exchange rates
"""
n_range = li... | 87300ef0b302227b8c61fbe420294784cdbbd341 | 670,950 |
def getNthDict(df, n):
"""
Rend un dictionnaire des données de la n-ième ligne
Arguments:
df {pandas.dataframe} -- le pandas.dataframe contenant les données
n {int} -- le numéro de la ligne
"""
return df[n:n + 1].to_dict(orient='records')[0] | a53303db1be676c6b5a44691fabf96a062457428 | 670,952 |
def generate_distances(netlist, gate_coordinates):
"""
Make a dictionary of all gates with the calculated distances between them.
"""
distances = {}
for item in netlist:
gate_start = int(item.gate_1)
gate_end = int(item.gate_2)
# Create tuple for gates that have to be conne... | af94bd06794e8be929bab50630912f4f7f07df1f | 670,953 |
def process_distance(distance):
"""
处理缺口距离
:param distance:
:return:
"""
x = -12 * 0.808 + (distance + 10) * (384 - 85.64800000000001 + 24 * 0.808) / (384 - 40)
return int(round(x / 0.808 + 44)) | 585945e49114579160fb92f9df068baf2d2568b6 | 670,955 |
import traceback
def atomic_method(method):
""" Decorator to catch the exceptions that happen in detached thread atomic tasks
and display them in the logs.
"""
def wrapper(*args, **kwargs):
try:
method(*args, **kwargs)
except Exception:
args[0].exceptionq.put("A... | b85f429886bdd0da137e02e073c0f1cf2af6c3cb | 670,956 |
def _font_pt_to_inches(x):
"""Convert points to inches (1 inch = 72 points)."""
return x / 72. | 6edcd171a1d943be2b51178da19b4ee6df5fa0eb | 670,957 |
import os
import time
async def create_file(path, data):
"""
:param path: location for the creation
:param data: lines to be written to path
:return: bool
"""
if os.path.isfile(path) or data == None:
return False
else:
with open(path, 'w+') as fp:
... | 043224bc10fbdb1f9c34f121af873782ed3031de | 670,958 |
def dimcolor(rgb, prop):
"""
Dims a given rgb color to prop, which should be in the interval 0.0 - 1.0.
"""
return tuple(map(lambda x: int(round(x * prop)), rgb)) | dfe049720f2b95a81ba384b640dce8428bb9438d | 670,959 |
import numpy
def gaussian(omega, cent, delta):
"""Normalized Gaussian line shape
"""
return numpy.sqrt(numpy.log(2.0)/numpy.pi)\
*numpy.exp(-numpy.log(2.0)*((omega-cent)/delta)**2) \
/delta | 550583435b406f242655aaee434454a1138f84c9 | 670,960 |
def create_output(seqs, stags):
"""
Create final output from characters and BMES tags.
"""
output = []
for seq, stag in zip(seqs, stags):
new_sen = []
for c, tag in zip(seq, stag):
new_sen.append(c)
if tag == 'S' or tag == 'E':
new_sen.append('... | ae53372abad32f1cd3a3aedd4cf63e294f45e999 | 670,961 |
import math
def beta_coefficient(vector): # beta coefficient
"""
function to get beta coefficient
@param vector:
@return: beta
"""
if (vector[2] + 1) ** 2 > 10 ** (-9):
return -math.sqrt(1 / (2 * (1 + vector[2]))) * complex(vector[0], vector[1])
else:
return 1j | 75aae84228478115cf9065e781a083ec48c170dd | 670,962 |
import struct
import binascii
def hex2double(s):
"""Convert Ephemeris Time hex string into double."""
return struct.unpack('d', binascii.unhexlify(s))[0] | 2320ba8352cf880ec61e8d867ac7d648f818ae45 | 670,963 |
def decode_edges(edges):
"""
Decodes the specified integer representing edges in Cortex graph. Returns
a tuple (forward, reverse) which contain the list of nucleotides that we
append to a kmer and its reverse complement to obtain other kmers in the
Cortex graph.
"""
bases = ["A", "C", "G", "... | 3ac84f466a059302d58e0e6204587c715c381016 | 670,964 |
def query_default(param, args):
"""
Allow for a parameter to be queried, and return defaults for those not provided.
Parameters
----------
param : str
The parameter being queried
args : object
Namespace object
Returns
-------
Queried value or default
"""
va... | a4bc265f0f0ebe6dd2e3d9bd511243718bc122a8 | 670,965 |
def markAvgMean(marks):
"""
markAvgMean (marks) - returns the average mean of the top 6 marks in the list of marks given
"""
top6 = []
for x in marks:
if len(top6) >= 6:
if x > min(top6):
top6.pop(top6.index(min(top6)))
top6.append(x)
else:... | e63636f39ea65d98f8dc3908d8f50c0e7954f997 | 670,966 |
def get_PDBid(ref):
"""
Obtains PDB id from ref by splitting its path and searching for alpha numerical (alnum) strings with length 4.
Args:
ref (str, universe, atomgrp): reference structure
Returns:
PDBid (str)
if ref path contains one unique alnum string with length 4
... | 6d4f15f407a8fc9d6059867b08f27f3952e3fb7c | 670,967 |
def lookup(name, namespaces=None, modules=None):
"""
Look up the given name and return its binding. Return `None` if not
found.
namespaces:
Iterable of namespaces / dictionaries to search.
modules:
Iterable of modules / objects to search.
"""
if namespaces is not None:
... | 0f2342d31ec1500599b666afccdcf4f8a228d4ee | 670,968 |
from typing import List
from typing import Dict
from typing import Any
def get_entire_collection(mongodb_collection) -> List[Dict[str, Any]]: # type: ignore
"""Returns the entire collection passed in parameter as a list"""
return list(mongodb_collection.find({}, {"_id": False})) | dddf218f3c59ec60cdc5476c72cf2fddd0e854a1 | 670,970 |
def pfm_to_pwm(pfm, pseudo=0.001):
"""Used form the Gimmemotifs tool """
return [[(x + pseudo)/(float(sum(row)) + pseudo * 4) for x in row] for row in pfm] | 8284a206f2f016904e3f30d6713fecd81398dc43 | 670,971 |
def euclideanAlgorithm1(a, b):
"""
Finds the greatest common divisor and the two integers that can find it
gcd(a, b) = r = uv + vb
:param a:
:param b:
:return:
"""
up, vp, rp = 1, 0, a
uc, vc, rc = 0, 1, b
while rc != 0:
q = rp // rc
rp, rc = rc, rp - q * rc
... | 6e2c6b793a682b688b6206d0ebea9a5aa4ba71e7 | 670,973 |
def metadata_to_dict(metadata):
"""
Takes metadata as specified in seperate_metadata_and_content() documentation and\
converts it to a dictionary.
Note that white space on either side of the metadata tags and values will be stripped; \
also, if there are any duplicate metadata key names, the value o... | 9fe4eb2fc1a99fcb206af84fb64cd729c9f64ae9 | 670,974 |
def max_sequence_length_from_log(log):
"""
Returns length of the longest sequence in the event log.
:param log: event log.
:return: max_seq_length.
"""
max_seq_length = 0
for sequence in log:
max_seq_length_temp = 0
for activity_ in sequence:
max_seq_length_temp... | 626a045a344e37e3e99f864665e9990fb12d87a2 | 670,975 |
import re
def remove_duplicate_spacing(text):
"""Replace multiple spaces by one space"""
pattern = r'[\s]+'
return re.sub(pattern, " ", text)
pass | bd3960825bddcc784808ed52fbf85d7882973608 | 670,976 |
def point_in_box(bbox, point):
"""check if a point falls with in a bounding box, bbox"""
LB = bbox[0]
RU = bbox[1]
x = point[0]
y = point[1]
if x < LB[0] or x > RU[0]:
return False
elif y < LB[1] or y > RU[1]:
return False
else:
return True | c6b44b55609136aa728d35c0cc2966f94d415bd9 | 670,977 |
def find_node_by_op_input_output_name(self, op, input_name, output_name, input_pos=0, output_pos=0):
"""
Finds the first node in the graph with the given operation name.
:param self: The gs.Graph object being extended.
:param op: The operation name to search for.
:param input_pos: Which input to con... | 2514ea8b2c2614b0179b2d01158893c24f9a64fe | 670,978 |
def count_vowels(string):
"""
#### returns amount of vowels in given string
#### Example:
x = count_vowels("The meaning of life, 42 to proof this, is this text"*3)
### print(x)
### 42
"""
vowels,counter = ("aeiou"),0
for i in string:
if i.lower() in vowels : counter+=1
... | ea2f0e91e16f4effd8a3172c44823dde18bddb43 | 670,979 |
def unescape(string_lit):
"""Convert the source bytes of a string literal to a string value.
>>> unescape('"foo\\n"')
'foo\n'
"""
string_lit = string_lit.strip('"')
res = ""
i = 0
while i < len(string_lit):
c = string_lit[i]
if c == "\\":
assert i < len(str... | 81283156262ebd24bafc014af1a6e6c74f245b66 | 670,980 |
from typing import Tuple
def manhattan(coord_1: Tuple[int, int], coord_2: Tuple[int, int]) -> int:
"""
Returns the manhattan distance between 2 coordinates.
"""
return abs(coord_1[0] - coord_2[0]) + abs(coord_1[1] - coord_2[1]) | cfee64a68b1f2aaace9b27c73899d42a0ab3f5c4 | 670,981 |
import binascii
import os
def generate_256bit_key():
"""Generate a pseudo-random secure ready-for-crypto-use key.
Generate it straight using urandom. Proving randomness is impossible, and a good source
is a hotly debated subject. As always, opinions are welcome but please inform
yourself first and be... | 4b2cb24daf531e8582dfc083fcea74a1359bd437 | 670,982 |
def str_to_lower(data: str) -> str:
"""
将数据中的字符换成小写
:param data: 字符串
:return: 结果
"""
return data.lower() | 1f4b1433d5efac6b674bc2db729dd7b21af7ff19 | 670,983 |
import math
def cosine(T, prop):
""" Returns a point on a goniometric function. """
return math.cos(T) | 225d1d201c4e40d2973f71cc9f623dbd035357d9 | 670,984 |
def parse_lines(s):
"""
parser for line-separated string fields
:s: the input string to parse, which should be of the format
string 1
string 2
string 3
:returns: tuple('string 1', ...)
"""
return tuple(map(lambda ss: ss.strip... | 1b406d4efd0afa92188efb221299b1ac64d95e2e | 670,985 |
import requests
import webbrowser
def playonyt(topic):
"""Will play video on following topic, takes about 10 to 15 seconds to load"""
url = 'https://www.youtube.com/results?q=' + topic
count = 0
cont = requests.get(url)
data = cont.content
data = str(data)
lst = data.split('"')
for i i... | 8fc01be259bd1ecf9de7d836c35f531daaa4f515 | 670,986 |
def split_agents(agents, max_networks_on_agent):
"""Divide list of agents into groups: overloaded, full and free
Overloaded agent means that it hosts more networks than
max_networks_on_agent,
Full agent means that it hosts exactly max_networks_on_agent of networks,
Free agent means that it host... | 50f31dbdac1419d47bfe3964a60162ab907c8dd2 | 670,987 |
import os
def get_env_vars():
"""Get map of all Cytokit environment variables"""
return {k: v for k, v in os.environ.items() if k.startswith('CYTOKIT_')} | 8aa672b38379e65722df1cdc098846417b7c0b17 | 670,989 |
def gen_namespace(dbname, collname):
""" Generate namespace.
"""
return '%s.%s' % (dbname, collname) | 96cbd4f7874eb87584fdb00d87ee5f062805f173 | 670,990 |
def calculate_score(given_answers: dict, correct_answers: dict) -> int:
"""Returns the number of correct answers.
given_answers: {"question1": "X",
"question2": "Y",
...
"questionN": "Z"}
correct_answers: {"question1": "A",
"... | adcd2df940af9d3937c097d1d4e2144657b3e5de | 670,991 |
import numpy
def azel_to_hadec(az, el, latitude):
"""Converting Az El to HA Dec
TMS Appendix 4.1
sindec = sinlat sinel + coslat cosel cosaz
cosdec cosha = coslat sinel - sinlat cosel cosaz
cosdec sinha = -cosel sinaz
:param az:
:param el:
:param latitude:
:return: ha... | edfa7127160f8dbf0a2597d2091044c702f51834 | 670,992 |
def multiply(a, b):
"""Function to multiply two numbers.
Parameters
----------
a: float
First number of the multiplication.
b: float
Second number of the multiplication.
Returns
-------
float
The product of a and b, a*b.
"""
return a * b | 7f74478bfae2a5512cb15c8b1b3a6f1a7e6aedcf | 670,993 |
def merge_array(arr1, arr2, n):
"""
arr1的长度等于两个列表中数据的总和
ex: arr1 = [1, 3, 4, 0, 0, 0]
arr2 = [2, 3, 6]
return [1, 2, 3, 3, 4, 6]
:param arr1: list
:param arr2: list
:param n: number arr1中有效数据的个数
:return: arr1
"""
if len(arr2) == 0:
return arr1
if len(arr2)... | 5471b6ccd76a40d7aff79dc096eaac035095c242 | 670,994 |
import torch
def available_device() -> torch.device:
"""return torch cuda device if available"""
return torch.device("cuda:0") if torch.cuda.device_count() else torch.device("cpu") | bdd059f40d3febc8b3dbf635f258b74b405e962a | 670,995 |
def get_mnsp_period_collection_attribute(data, attribute, func) -> dict:
"""
Get MNSP period collection attribute
Parameters
----------
data : dict
NEMDE case file dictionary
attribute : str
Name of attribute to extract
func : function
Function used to parse extrac... | 5670969badd5d881257692e4e63ea706ad64ddbc | 670,996 |
def mk_callable(call_func):
"""A class decorator that adds a __call__ method. Specialized for sklearn models.
>>> import numpy as np
>>> from sklearn.decomposition import PCA
>>>
>>> CallablePCA = mk_callable('single_transform')(PCA)
>>> pca = CallablePCA(n_components=3).fit(np.random.rand(100,... | aebb76c435b0eae4291e6648f043a39266a440de | 670,997 |
def box(keyword):
"""Validation for the ``<box>`` type used in ``background-clip``
and ``background-origin``."""
return keyword in ('border-box', 'padding-box', 'content-box') | 31af2163ee6592f96fd32277ce3ff7697171eba0 | 670,998 |
def getgrams(text, tokendict):
""" Generate first one, two words from the token list
:type text: list of int
:param text: indices of words with the text span
:type tokendict: dict of Token (data structure)
:param tokendict: all tokens in the doc, indexing by the
document-leve... | 2fcc4dddc9295b92e57d2e95eae7b5a89e26fd0c | 670,999 |
import random
import time
def make_Card_valid_date(IDCard):
"""生成身份证有效期数据,1965年以后出生的身份证有效期,在今年的基础上随机增加/减少年数,80年之前的,有效期长期"""
if int(IDCard[6:10]) > 1965:
date = random.choice(["-2", "-1", "0", "1", "3", "5", "10", "15", "20"])
year = time.strftime("%Y", time.localtime())
born_month_day ... | 235d481c56bdbb9b7a54c1c9453d6b97538a7ebf | 671,000 |
def _match_attrs(ds_a, ds_b, match_attrs):
"""returns the number of matched attrs between two datasets"""
return sum([ds_a.attrs[i] == ds_b.attrs[i] for i in match_attrs]) | 9305f7328175a22f3d2071635763279825cd650a | 671,002 |
def sort_keypoints_by_response_and_get_n_best(keypoint_list, n=500):
"""
Sorts keypoint list by "response" field and returns the first n best keypoints.
If the length of the list is smaller than n, than return the whole list.
input: keypoint_list - list of keypoints
n - no of keypoints to be... | 34bc3116ed6acecd652bfdd7176624bd02948ff0 | 671,003 |
def Fill_missing_value(df,column):
"""Fill missing value with Mean"""
for c in column:
if df[c].isnull().sum() >0:
df[c] = df[c].fillna(df[c].mean())
print('Check Missing value:',df.isnull().sum().sum())
return df | af8a9d9a1db3cb3af2f3cf490f39f4559d6a8f1e | 671,004 |
def dirac_measure(a,b):
"""
Returns 1 iff a=b and 0 otherwise.
"""
if a==[] or b==[]:
return 0.0
return float(a==b) | 37d8215d30c962441ef3b09d7e077de62da89f7e | 671,005 |
def anchor(post):
"""Return anchor string for posts that arepage sections."""
if post.section:
return '#' + post.section
else:
return '' | a48dba92060aaac6f7322469669a9becc83bd847 | 671,007 |
import re
def _ParseFixed(fixed_or_percent_str):
"""Retrieves int value from string."""
if re.match(r'^\d+$', fixed_or_percent_str):
return int(fixed_or_percent_str)
return None | 7d0cc19f22f7d6c174d41f3d76916972ccb49a17 | 671,008 |
import math
def __calculateGridAxis(length, local):
"""
Calculates the grid axis.
Parameters
----------
length : int.
Global length.
local : int.
Local size.
Returns
-------
grid : int
Calculated grid size.
"""
return int(math.ceil(float(length) ... | 35ccbec9395f82e2152c9142b5607705c7de2a39 | 671,009 |
def load_mjio_counts(filename):
"""
Load a file of counts from MJIO format.
"""
counts = {}
with open(filename, 'r') as fhandle:
preterminal_rules = []
unary_rules = {}
binary_rules = []
for line in fhandle:
tokens = line.split()
if len(tokens) == 4:
# Various cases
p = float(tokens[0])
l... | b951912a0d3b429d903d5be972577cf0d5e3a850 | 671,010 |
import csv
def check_duplicate_creators():
"""Check if in the creators.csv file there
are some duplicate profiles.
"""
print("[-] Checking duplicates in creators file...")
with open("creators.csv", encoding="utf8") as csv_file:
csv_reader = csv.reader(csv_file, delimiter=",")
line_... | 6318315c338a11e377a2b8293a474629a8bb7c59 | 671,011 |
def get_stds(da):
"""get standard deviations, annual and monthly
"""
monthly_std = da.groupby('time.month').std(dim='time').copy()
annual_std = da.std(dim='time').copy()
return monthly_std, annual_std | c9026d3c65ab3441bb3bcb2e677a301c92fe0405 | 671,012 |
import os
def read_key():
"""
Read API key from /data/credential.txt
:return: API key
"""
path = os.path.join(os.path.dirname(__file__), 'data')
f = open(os.path.join(path, 'credential.txt'), 'r')
key = f.read()
f.close()
return key | 85d8d744d88a8b11dabf5d3ce725a8e795e6793b | 671,013 |
def _unpack_parameters(parameters, key):
"""Unpacks the values from a dictionary containing various parameters for
pymaws
Parameters
----------
parameters : dict
planetary parameters dict with keys:
angular_frequency: float, (rad/sec)
gravitational_acceleration: floa... | f3f6444cba0937177a808eef366a28f88878f8b7 | 671,014 |
def _has_property(requirements, prop, rel_type):
""" Check if a requirement has the correct properties and type """
for requirement_dict in requirements:
for requirement in requirement_dict.values():
if isinstance(requirement, str):
return True
relation = requirem... | 3725a0b4741e017ad2c4ffce7f75891f3f27bea5 | 671,015 |
import copy
import logging
def MergeConfigs(default_config, override_config, warn_new_key=False):
"""Merges the override config into the default config.
This function will recursively merge two nested dicts.
The override_config represents overrides to the default_config dict, so any
leaf key/value pairs whic... | dcd6a758cbbd1f8bc3d0a1d59a080731608521d7 | 671,016 |
import os
def __get_apk_version(apk_name):
"""Attempt to find the dtfClient version"""
try:
return os.path.basename(apk_name).strip('.apk').split('-', 1)[1]
except IndexError:
return "N/A" | cb7fd13ba2c7867d3275189cc7e94b8e08ac3947 | 671,017 |
import re
def get_tables_from_sql(sql):
""" 从 sql 语句中拿到所有引用的表名字 """
m = re.search(r'FROM (.*?)($| WHERE| GROUP| HAVING| ORDER)', sql, flags=re.M)
return [t.strip() for t in m.group(1).strip().split(',')] if m else [] | 90ff7b989904716a5c4508120e18d4bbf06bc640 | 671,018 |
def largest_odd_times(L):
""" Assumes L is a non-empty list of ints
Returns the largest element of L that occurs an odd number
of times in L. If no such element exists, returns None """
# Set frequency dictionary
freqDict = {}
for item in L:
if item in freqDict:
fre... | 1656737082553353e3826e7bd6477469479284c9 | 671,019 |
def SampleZipped(sample_file, input_api):
"""Return True if the zipfile that should contain |sample_file| is in
this change.
"""
sample_path = sample_file.LocalPath()
for af in input_api.AffectedFiles():
root, ext = input_api.os_path.splitext(af.LocalPath())
if ext == '.zip' and sample_path.startswith... | 27ceca5086843920dd2e8594728b722f450e9de9 | 671,020 |
def ellipse_to_rect(ellipse):
"""
将椭圆框转换为水平竖直的矩形框
:param ellipse: list, [major_axis_radius minor_axis_radius angle center_x center_y, score]
:return rect: list, [leftx, topy, width, height, score]
"""
major_axis_radius, minor_axis_radius, angle, center_x, center_y, score = ellipse
leftx = ce... | 92519cd0b1e82edb538971102fa0556bbcb226e3 | 671,021 |
def _find_traces(traces, trace_type, item_id):
"""Find traces for a script or automation."""
return [
trace
for trace in traces
if trace["domain"] == trace_type and trace["item_id"] == item_id
] | 973b6460a86e793e54a914d799c4c0d2ee1c8fcd | 671,022 |
import requests
import json
def findSmartAccountProperties(auth_code, sa_domain, property='name'):
"""This proc will find the smart account <property> associated with <sa domain>"""
url = "https://apx.cisco.com/services/api/smart-accounts-and-licensing/v1/accounts/search?"
logm = ""
account_property ... | 2b58d3dacf7639d33e513597e29d8d07d852e97e | 671,023 |
def GenerateTableHtml(items, keys_to_print, display_index=True):
"""Given a list of object values and keys to print, make an HTML table.
Args:
items: Items to print an array of dicts.
keys_to_print: (key, display_fn). `key` is a key in the object. i.e.
items[0][key] should exist. display_fn is the ma... | 351959b5d5e2ecfdc00070cf6b6c0e6ca8f42edf | 671,024 |
def move(moon, vel):
"""
apply velocity to related moon
"""
for i in range(len(moon)):
moon[i] += vel[i]
return moon | 929f496474b6b2a061f8828c06bc88eb32702e43 | 671,025 |
import subprocess
def execute(command, location, check_result=False):
"""Runs a shell command in the specified directory location.
Args:
command: The command as a list to be run.
location: The directory the command is run in.
check_result: Should an exception be thrown on failed command.
Returns:
... | 68925d671199ec1758f9e8bbe4746c7f7382f051 | 671,026 |
def _determine_derived_mode_name_db(ModeParsedDb):
"""RETURNS: 'derived_db'
mode_name ---> list of all names of derived mode
"""
derived_db = dict((name, set([name])) for name in ModeParsedDb)
for name in ModeParsedDb:
base_mode_list = ModeParsedDb[name].direct_base_mode_name_list
... | 28b52893fd6db809fc923991a08c795ee4aec1dd | 671,027 |
import requests
import base64
import mimetypes
def _create_data_uri(url, filename):
"""Create a data url that contains the file in question."""
response = requests.get(url, verify=False)
if response.status_code != 200:
# couldn't access the file
return url
data = base64.b64encode(respo... | 02c5e7128938b4270ebe8567a0d1a0fda1a8be5e | 671,028 |
import os
def _inspect_environment():
"""Return relevant information from the cgi environment.
This is mostly split out to simplify testing.
Returns:
A tuple: (app_version, conf_version, development)
app_version: the major version of the current application.
conf_version: the current configuration... | f749a0c1cae6cb6364137932fe29f2ae2c583b3f | 671,030 |
def find_prep_chunk(doc):
"""
Returns a dictionary representing a simple verb chunk
with a subject, verb, object.
"""
# “I learn quickly in stress and pain.”
for noun_chunk in doc.noun_chunks:
subj = noun_chunk.root # stress
subj_full = noun_chunk
if subj.head.dep_ == 'prep': # head = in
prep = subj.he... | 7fc2a9a04da29281599c2f6708109f57bf29e04c | 671,031 |
def polyToBox(poly:list):
""" Converts a polygon in COCO lists of lists format to a bounding box in [x, y, w, h]. """
xmin = 1e10
xmax = -1e10
ymin = 1e10
ymax = -1e10
for poly_comp in poly:
for i in range(len(poly_comp) // 2):
x = poly_comp[2*i + 0]
y = poly_comp[2*i + 1]
xmin = min(x, xmin)
xma... | 95858b53790f5de922d3fe4e4d4d8587fa190c34 | 671,032 |
def parse_func_list(func_lst, identify_lst, ignore_keywords=[]):
"""
Reads through a list of available methods and retrieves the methods that have
matching words in the identify list, then it removes those key words and Returns
a dictionary of simplified method names with values as their corresponding
... | e0be30a3f6154dc147bb8571e3b88c6b7355a0b8 | 671,033 |
import re
def char_tokenizer(sentence):
"""Cut the sentence into the format we want:
- continuous letters and symbols like back-slash and parenthese
- single Chinese character
- other symbols
"""
regex = []
# English and number part for type name.
regex += [r'[0-9a-zA-Z\\+()\-<>]+']
... | 8845cf677671af3a270a9e6bc0f2860df5c763b1 | 671,034 |
import re
def match_pattern(file, pattern):
""" Continue reading file line by line and look for regular expression pattern.
Returns True if the pattern was found, False if not. """
for line in file:
if re.search(pattern, line):
return True
return False | 4fb3fb2dbb242e03577af0eff5532561f9ef8e0a | 671,035 |
def rearrange_data(data, warning):
"""Put all books where the current main sorting field is empty
in a separate array (data_temp)
"""
data_temp = None
for row in data:
if row['_id'] == '' or row['_id'] == None:
data_temp = row
row['_id'] = warning
row['emp... | 051fa0b669fd29c3613637f51655f09e4e93d0df | 671,036 |
def mystery_3b(c1: int, c2: int, c3: int) -> int:
"""Function for question 3b."""
if c1 >= c2:
if c2 >= c3:
return 1
else:
return 2
else:
if c2 <= c3:
return 3
else:
return 4 | 92c15f718c002a240709179f65b410b818493025 | 671,037 |
def GetTimestampEventName(process):
""" Returns the name of the events used to count frame timestamps. """
event_name = 'BenchmarkInstrumentation::DisplayRenderingStats'
for event in process.IterAllSlicesOfName(event_name):
if 'data' in event.args and event.args['data']['frame_count'] == 1:
return event... | 7cda78cd87f4f75ab84e3b412a229fb248b9f48b | 671,038 |
def _check_column(col, df, default):
"""Check that a column exists in the dataframe."""
if col is None:
try:
return [c for c in df.columns if c.lower() == default][0]
except IndexError:
return None
if col not in df.columns:
raise ValueError(f"The '{col}' colu... | af128e3a31a4baf1709e05ee4ed972f94bdb22c8 | 671,039 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.