content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def merge_dictionnary(dic1, dic2):
"""
Merge two dictionaries by appending on the keys of the other
"""
res = {}
if not dic1:
for key in dic2.keys():
res[key] = [dic2[key]]
else:
for key in dic1.keys():
dic1[key].append(dic2[key])
res = dic1
re... | ad9df2619666ec2cd527b3e5a4c9e3c3a7c1fb74 | 636,515 |
import sys
import os
import subprocess
def cpu_count():
"""Return the number of hardware thread contexts (cores or SMT
threads) in the system.
"""
# Adapted from the soundconverter project:
# https://github.com/kassoulet/soundconverter
if sys.platform == 'win32':
try:
num =... | 95f28a78b54a4d470fc865c355bd1455e5955c88 | 636,516 |
def check_for_negatives(arr):
"""Check if array contains negative number.
Numba optimized function to check if a numpy array containes a negative
value. Returns, whenever the first negative function is found.
Args:
arr: Numpy array
Returns:
True, if the array contains ... | cbe9748322957029a06975e2bdf5a0e989db27ed | 636,517 |
def DD_in_DMS(d):
""" Градусы => градусы/минуты/секкунды """
deg = int(d)
mn = int((d-deg)*60)
sec = ((d-deg)*60-mn)*60
return (deg,mn,round(sec,2)) | 5f61fb0f098e996f636f4a2c59cbc0ae16b5dab0 | 636,518 |
import os
import sys
import subprocess
def _run_mlflow_run_cmd(mlflow_run_arr, env_map):
"""
Invoke ``mlflow run`` in a subprocess, which in turn runs the entry point in a child process.
Returns a handle to the subprocess. Popen launched to invoke ``mlflow run``.
"""
final_env = os.environ.copy()
... | a760d6564038ef002f213f1c20c0a96a1ce436e0 | 636,519 |
def preprocess(Y, D, X):
"""Verfies shape of Y, D, X
D is the treatment vector (Boolean vector)
It is a column vector with shape N, 1 (N rows, 1 column)
i.e.
0
1
0
1
1
X is the intput vector (numeric)
It is a matrix with shape N, K
"""
if Y.shape[0] == D.shape[0] == X.shape[0]:
N = Y.shape[0]
else:
... | 4855c862ec4076e5b3241fd27149ca4e491b8fbb | 636,520 |
def aruba_banner(config):
"""Hier config removes the ! from the end of the Aruba banner, this function adds it back.
Args:
config: hier config object
Returns:
corrected banner
"""
banner = config.get_child("contains", "banner")
if banner is None:
return
else:
... | c9fcf07db015dc9c6c97e5ecb24447962f126c43 | 636,521 |
import numpy as np
def sphericalDistance(x0,y0,x,y):
"""
dr = sphericalDistance(x0,y0,x,y)
compute distance between coordinate pair (x0,y0)
and pairs (x,y) on the sphere assuming that
both (x0,y0) and (x,y) are given in spherical polar coordinates
returns radial distance in radians
"""
... | 9166495d304b724b6b5760463ee2a4a8103b3924 | 636,522 |
def gf_sub_ground(f, a, p, K):
"""
Compute ``f - a`` where ``f`` in ``GF(p)[x]`` and ``a`` in ``GF(p)``.
**Examples**
>>> from sympy.polys.domains import ZZ
>>> from sympy.polys.galoistools import gf_sub_ground
>>> gf_sub_ground([3, 2, 4], 2, 5, ZZ)
[3, 2, 2]
"""
if not f:
... | 998db6ebd121936012eaa2f9421f11b216e99482 | 636,523 |
def isFunction(f):
"""
判断是否为函数
:param f:
:return:
"""
return hasattr(f, '__call__') | c6b78d008333761553a6bd74614b9778369f2129 | 636,524 |
def double_scale(*, target):
"""Divide target elementwise by two."""
return 2*target | a14960a058c9e0ee08c85c601ff7f2a1ee65d7ab | 636,525 |
def get_atari_filter(shape):
"""Get default model set for atari environments."""
shape = list(shape)
# (out_size, kernel, stride)
filters_84x84 = [
[16, 8, 4],
[32, 4, 2],
[256, 11, 1],
]
filters_42x42 = [
[16, 4, 2],
[32, 4, 2],
[256, 11, 1],
... | d22870fdd6df44fa2e02907dfbc1a7df878f42fe | 636,526 |
import torch
def interpolate_bilinear(grid,
query_points,
name='interpolate_bilinear',
indexing='ij'):
"""Similar to Matlab's interp2 function.
Finds values for query points on a grid using bilinear interpolation.
Args:
grid: a... | 5c3293b30bcc87ccc0ba4041001c9d5404295b79 | 636,528 |
def get_labeled_spans(prop):
"""
:param prop: 1D: n_words; elem=bracket label
:return: 1D: n_words; elem=BIO label
"""
def _concat_c_spans(_spans):
labels = [_span[0] for _span in _spans]
c_indices = [i for i, _span in enumerate(_spans) if _span[0].startswith('C')]
non_ant_c_... | 5a213ad6d13109971c30a488b10bfffbd5e13399 | 636,529 |
from unittest.mock import call
def get_items(service,
function,
items='items',
throw_reasons=None,
retry_reasons=None,
**kwargs):
"""Gets a single page of items from a Google service function that is paged.
Args:
service: A Google servic... | a0788cccfba9ffb12f3ee8f52396ff16a912fdc0 | 636,530 |
import socket
def get_hostname_by_addr(addr):
"""return hostname for host at address"""
try:
(hostname, aliaslist, ipaddrlist) = socket.gethostbyaddr(
socket.gethostbyname(addr)
)
return hostname
except:
return addr | f71d8221faf757f22065dac1c33480c6a09447fa | 636,531 |
import numpy as np
def calculateSigma(voxel, input):
"""
Spocita novou hodnotu sigma pro gaussovo filtr.
"""
voxel = np.asarray(voxel)
sigma = input / voxel
return sigma
# voxelV = voxel[0] * voxel[1] * voxel[2]
#
# if (voxel[0] == voxel[1] == voxel[2]):
#
# return (... | 8df6658abf3fc8a57eabdf3031e906ac27363a18 | 636,532 |
def img_normalize(img, val_range=None):
""" Normalize the tensor into (0, 1).
Args:
tensor (torch.Tensor): input tensor.
val_range (tuple): range in the form (min_val, max_val).
Returns:
torch.Tensor: normalized tensor
"""
t = img.clone()
if val_range:
mm, mx = v... | 199e22c7b2b0c1316205febd3238046a9f452bfb | 636,533 |
def vectorize(function):
"""
:param function: Function to be vectorized
:return: Vectorized function
Create new function y= vf(x), such that:
y = f(x)
/ map(f, x) if x is list
vf =
\ f(x) if x is not list
Example:
>>> import math
>>>
>>> sqrt... | 551daccbb1264da1bae31f0477a65d76d2d29035 | 636,534 |
import base64
def encode_password(shortcode, passkey, timestamp):
"""Generate and return a base64 encoded password for online access.
"""
return base64.b64encode(shortcode + passkey + timestamp) | 068df7fdefb63fe8f037dc1a99fdd55c4fb1f557 | 636,535 |
import torch
def shuffler(data, assignments):
"""
shuffle the GMM datasets by both permuting the order of GMM instances (w.r.t. DIM1) and permuting the order of data points in each instance (w.r.t. DIM2)
"""
concat_var = torch.cat((data, assignments), dim=-1)
DIM1, DIM2, DIM3 = concat_var.shape
... | e0727e9edf60a664ff4637a2de83857ae017f93a | 636,536 |
def convert_words_to_indices(sent_array, word_to_idx):
"""Converting each word to its index value"""
for i, sentence in enumerate(sent_array):
for j, word in enumerate(sentence):
if word in word_to_idx:
sent_array[i][j] = word_to_idx[word]
else:
se... | 557d868385fba046c71b62028a2a740832b08add | 636,537 |
from typing import List
def generate_pairs(number: int) -> List[List[int]]:
"""Generate all pairs of number sequence.
Args:
number: <int> the number
Returns: <list> a sequence
Examples:
>>> assert generate_pairs(1) == [[0, 0], [0, 1], [1, 1]]
"""
return [
[top, inner... | 1f711fca8774ce06dc291d45aff1d4ac3b1388e1 | 636,538 |
def galcenrect_to_XYZ(X,Y,Z,Xsun=1.,Ysun=0.,Zsun=0.):
"""
NAME:
galcenrect_to_XYZ
PURPOSE:
transform rectangular Galactocentric to XYZ coordinates (wrt Sun) coordinates
INPUT:
X, Y, Z - Galactocentric rectangular coordinates
OUTPUT:
(X, Y, Z)
HISTORY:
... | 993913e713e7b5dc577911e41ecffdae64f92c8d | 636,539 |
def deserialize_text(value):
"""
Deserialize a text value,
"""
return value | 560c1858710bcd2f2cdda5a12383a70b3f8e8296 | 636,540 |
def coq_param(name, type):
"""Coq parameter
Arguments:
- `name`: name of the variable
- `type`: type of the variable
"""
return "Parameter {0!s} : {1!s}.\n".format(name, type) | e674f2d93b2cb3b85b5ec7d487917b1035b464f4 | 636,542 |
def test_1_filtered_signal_data():
"""Normal signal, with noise."""
properties = {'low_pass_cutoff': 30, 'fs': 333.3333333333207, 'high_pass_cutoff': 1, 'period': 100}
return properties | 37b069f53a4ca41f227d55b395fb213ccb4213d8 | 636,543 |
def matrix_vector_multiply(mat, vec):
"""Multiplies a matrix by a vector.
Multiplies an m x n matrix by an n x 1 vector (represented
as a list).
Args:
mat (2-D list): Matrix to multiply.
vec (list): Vector to multiply.
Returns:
Product of mat and vec (an m x 1 vector) as a... | afe6c0fdbed125034c27145a2d31b043e834f305 | 636,544 |
def convert_point_input(string, sep=' '):
"""converts separated coordinate points, e.g. (1,2) to a list of tuples
sep: character separating each set of points"""
lst = string.split(sep)
for i in range(len(lst)):
tup = tuple(lst[i].split(','))
res = float(tup[0][1:]), float(tup[1][:-1])
... | f8910c6fccefeecee10f6faaed3afe7e685ee3f0 | 636,545 |
from typing import Optional
import base64
def webex_id_to_uuid(webex_id: Optional[str]) -> Optional[str]:
"""
Convert a webex id as used by the public APIs to a UUID
:param webex_id: base 64 encoded id as used by public APIs
:type webex_id: str
:return: ID in uuid format
"""
return webex_... | d2fb6f5aa8c28d84d0f91a2713dfae4b8a507642 | 636,546 |
import itertools
def create_pairs(df, column_entity_list):
"""
df: Pandas dataframe
Find all pairs of entities in any list of entities
Returns list of paired tuples of the for [(A,B), (B,C)]
"""
# Join as lists
l = [''.join(row) for row in df[column_entity_list]]
# Tokenize string... | cb604aacee8dc70d07b70731b7ab169cb645c874 | 636,547 |
import base64
def to_base64(utf: str) -> str:
""" Convert a string to its base 64 encoded string. """
bs: bytes = base64.b64encode(utf.encode())
return bs.decode() | d3224aaecc87c07c9b2fe0ac0605eaa37a11a7dd | 636,548 |
import torch
def get_optimizer(config, model):
"""[summary]
Args:
config ([type]): [description]
model ([type]): [description]
Raises:
ValueError: [description]
Returns:
[type]: [description]
"""
optimizer_name = config.SOLVER.OPTIMIZER
if optimizer_name ... | fd9b02d439b274cd0303153e4e8ce83b150bb55e | 636,549 |
def evaluate(params, weights, refs):
"""Calculates RGB mapping.
Functions that gets all measured parameters as stored in the
csv file including weights and refs. This function is calld for
each sample. Can be replaced.
Parameters
----------
params : ndarray
An array containing ... | 00213f0380c78193d06b187f05de96a6de0fbe21 | 636,550 |
import os
def get_data_mtime(base_dir, data_dir, fallback_value=0):
"""Get last modification time of data set in
<base_dir>/<data_dir>. If the directory appears invalid, return
fallback_value."""
for f in ["tabular_data.dat", "tabular_data.dat.gz"]:
try: return os.path.getmtime( os.path.join(base_di... | 69e04721e9834bc720de8789460173fe803971e0 | 636,551 |
import sys
import os
def get_base_application_path():
"""Dynamically fetches the application's root project directory
path based on if the application is running as a script or as
a frozen exe.
This does not return the path of the main Python executable,
server.py, located in /backend/dist/serve... | e2e0e56c84efe3c4ee78506196b534e284274776 | 636,552 |
import re
def replaceCaseInsensitive(a_string, to_replace, replacement):
"""assumes a_string is a string
assumes to_replace is a string
assumes replacement is a string
returns a new string, a_string with any instances of to_replace replased
with replacement. case insinsitive."""
pattern = re.c... | 75b7035ded2c6840e41817e0ad6b13ae896ed970 | 636,553 |
def _cplus_include_paths(repository_ctx):
"""Use ${CPLUS_INCLUDE_PATH} to compute the list of flags for cxxflag."""
if "CPLUS_INCLUDE_PATH" in repository_ctx.os.environ:
result = []
for p in repository_ctx.os.environ["CPLUS_INCLUDE_PATH"].split(":"):
p = str(repository_ctx.path(p)) # Normalize the pa... | d4909000abd05f719ddc9793df35f371d426c334 | 636,555 |
import hashlib
def gen_sha256_hash(msg):
"""Generate SHA 256 Hash of the message."""
hash_object = hashlib.sha256(msg.encode('utf-8'))
return hash_object.hexdigest() | 4de420ab6fa9878f8c03a17b78b5508a1fecde63 | 636,556 |
import argparse
def init_argparser():
"""Initialize the SLAM argparser."""
argparser = argparse.ArgumentParser(
description= "SLAM command-line interface")
argparser.add_argument("-a", "--action", action="append", required=True,
choices=["list", "create", "get", "delete", "modify", "setpro... | b724c39567a1c7a75ea78a2ff4387bdf71abd1bb | 636,557 |
def getNeighFeat(data_rna, G, neighbors, norm = False):
"""
Function for getting neighbourhood features. Calculates the sum of logFC
across the different neighbours of the gene.
To normalize for number of neighbours with change in fold change (FC), the
norm parameter need to be True.
... | 9ee1df8c32c71f3431fdb93968a83812cbe5a47f | 636,558 |
def timestamp(pkt_hdr):
""" Returns the timestamp of the packet in epoch milliseconds. """
(epoch_secs, delta_micros) = pkt_hdr.getts()
epoch_micros = (epoch_secs * 1000000.0) + delta_micros
return epoch_micros | ff4e8acac6cc8b65f72db8740bd3e5b91a062013 | 636,559 |
def bumped_version(bump, current_version):
"""Returns bumped version.
Parameters
----------
bump : str
Which component of version should be incremented (major, minor, patch).
current_version : tuple
A tuple (major, minor, patch)
Returns
-------
boolean
True on success, False otherwise
""... | 1590a0f1aac759c0fb732e53ce775eea275500f0 | 636,560 |
def _qualname(obj):
"""
Return the (non-fully-)qualified name of the given object.
"""
return obj.__qualname__ | ceb8c09309822c633f9dcfd0e9d1f741633071c2 | 636,561 |
def parse_args_from_config(config):
"""Parses available arguments from a configuration class.
Args:
config: The configuration class to parse arguments from, which is
defined in `configs/`. This class is supposed to derive from
`BaseConfig` defined in `configs/base_config.py`.
... | 42ad3c86a9d3c3ddf298701e1cdcc26bf608d511 | 636,562 |
def delete_vertices(graph, dverts):
"""Delete the vertices indexed by dverts from graph; return the resulting graph."""
vertices, edges = graph
remverts = list(filter(lambda x: x not in dverts, range(len(vertices))))
vmap = {v: n for (n, v) in enumerate(remverts)}
nvertices = list(map(vertices.__get... | beed1a7e4c59fe842cd3a568c1bd3e75654f59cd | 636,563 |
def HasPackedMethodOrdinals(interface):
"""Returns whether all method ordinals are packed such that indexing into a
table would be efficient."""
max_ordinal = len(interface.methods) * 2
return all(method.ordinal < max_ordinal for method in interface.methods) | 6c52e6ca065664480f3f32ac79906f9a9906b57e | 636,564 |
def b14toInt(b):
"""Convert 14bit integers from bytes
Arguments:
b {bytearray} -- bytes
Returns:
int32 -- b14 decoded int[summary]
"""
if len(b) < 2:
return 0
b1 = ord(b[0]) << 1
b2 = ord(b[1]) << 8
bc = b2 + b1
bc = bc >> 1
return bc | cb8b3997abe35e89492741b2632a9b42dc28ec4e | 636,566 |
import textwrap
def _format_doc(docstring, prefix):
"""Use textwrap to format a docstring for markdown."""
initial_indent = prefix
# subsequent_indent = " " * len(prefix)
subsequent_indent = " " * 2
block = docstring.split("\n")
fmt_block = []
for line in block:
line = textwrap.f... | 1bf2bf0ee35f9b6e345eb8c70355d0a86bf74290 | 636,567 |
import json
def PrepareGroupORM(r, obj, mapping, objname, request, mappingattr='mapping'):
"""Prepare data assign to orm
Examples::
try:
r = PrepareGroupORM(r, obj, mapping, obj__heads__, self.args.items())
except Exception as error:
return omitError(ErrorMsg=repr(erro... | 6a202d295771e6034011953d476cd1432d671f0b | 636,569 |
def oc_to_vlan_range(value):
"""
Converts an industry standard vlan range into a list that can be
interpreted by openconfig. For example:
["1", "2", "3..10"] -> "1, 2, 3-10"
"""
return ",".join(["{}".format(s).replace("..", "-") for s in value]) | 2556b41ae83a31e2e66466a157d208c09efec7d6 | 636,570 |
def normalize_groupby(group, column):
"""
Normalize all the sum of column to 1 for a given groupy object.
:param group: group to normalize by. E.g. #_HOW#
:param column: coulumn to sum within.
"""
fold = group[column]
group[column] = fold / sum(fold)
return group | e666a6f794fb0269624868eab62cac177dd22f47 | 636,571 |
def get_inputs( filename ):
"""
The input notes consists of two lines.
Line 1 - estimate of earliest timestamp of departure
Line 2 - bus IDs in service, where 'x' = out of service
This function returns a dict with the time, buses in service and their offsets
"""
with open( filename, 'r' ) a... | e2991b7f454a89d3076c72362416e82526ef214f | 636,572 |
import math
def distance(x, y):
""" (number, number) -> float
Return distance of a point with coordinates x
and y from the origin.
>>> distace(3, 4)
5.0
"""
# formula: d = sqrt((x ** 2) + (y **2))
return math.sqrt((x ** 2) + (y **2)) | 93e377fbc5287c25f36fa4289087ec5ff0fcd91e | 636,573 |
def imag(img):
"""
返回图像虚部
:param img: 输入图像
:return: 返回虚部
"""
return img[:, :, 1] | 592b1e6b33a5f16fbe6f3e25198af617ab4d074b | 636,574 |
def F2K(T_F):
"""
Convert temperature in Fahrenheit to Kelvin
"""
return 5/9*(T_F+459.67) | dd7ed4866debef819ddc8cf3f298abfb23908c6c | 636,575 |
import os
import csv
def write_details_to_csv(filename,
cropped_coords,
bboxes,
imagepath,
sizes):
"""
Write detail to ongoing CSV FILENAME
CROPPED_COORDS: coordinates fo cropped image
BBOXES: bounding ... | 45da330bc3e58a38ea2c92aed3262db180a757f8 | 636,576 |
def convert_to_demisto_class(was_classified: str) -> int:
"""
Convert was_classified to demisto classification
:param was_classified:
:return:
"""
if was_classified == 'Yes':
demisto_class = 1
else:
demisto_class = 0
return demisto_class | 9c5f43224dae1f732bee779e5fee1093d6051273 | 636,577 |
def list_provincie_adapter(obj, request):
"""
Adapter for rendering a list of
:class:`crabpy.gateway.crab.Provincie` to json.
"""
return {
'niscode': obj.niscode,
'naam': obj.naam,
'gewest': {
'id': obj.gewest.id,
'naam': obj.gewest.naam
}
... | ad91ae983a259c77da2fecf4589785c50167744c | 636,578 |
import sys
import os
def IsRunningOnCrosDevice():
"""Returns True if we're on a ChromeOS device."""
lsb_release = '/etc/lsb-release'
if sys.platform.startswith('linux') and os.path.exists(lsb_release):
with open(lsb_release, 'r') as f:
res = f.read()
if res.count('CHROMEOS_RELEASE_NAME'):
... | fc478ba47b150c546f62cb6607d502c1537f0d64 | 636,580 |
def _get_long_description():
"""Helper to populate long_description for pypi releases"""
return open("README.rst").read() | a93fe351d9ad0550b25423f05156ef147e194506 | 636,581 |
def repo_path_from_uri(uri):
"""
Given a valid and complete URI, return just the path portion. Does no validation as to whether this is a
valid path.
:param uri:
The valid and complete URI.
:return:
A uri path.
"""
return uri.split(":/")[1].split("#")[0] | 9d1b849f51e013ef8d1687dda19110c10a279b3e | 636,582 |
def get_months_in_range(startdate, enddate):
"""Enumerates all months from startdate to enddate
Args:
startdate: start of the list of dates
enddate: end of the list of dates, likely today
Returns:
list of months in iso8601 format: yyyymm
"""
result = []
startmonth = [int... | 9805fb4848ee6395d9dd5db27022ab68de1b06cb | 636,584 |
def __rred(r_1, r_2):
"""
Calculate the reduced (effective) radius of two radii according to Hertzian
contact theory.
Parameters
----------
r_1: scalar
The first radius.
r_2: scalar
The second radius.
Returns
-------
r_red: scalar
The reduced (effective... | bdde676ddc3ec23693db98aee060e1894939226c | 636,585 |
import random
import json
def create_fake_community(faker):
"""Create fake communities for demo purposes."""
data_to_use = {
"access": {
"visibility": random.choice(["public", "restricted"]),
"member_policy": random.choice(["open", "closed"]),
"record_policy": rando... | 218657164f5acb7866bec8f3680be7df73151ea1 | 636,586 |
def negative_predictive_value(y_real, y_pred):
"""
Computes negative predictive value of a binary classification model: NPV = TN/(TN+FN).
Args:
y_real (np.array): Array of ground truth values
y_pred (np.array): Array of predicted values
Returns:
(float): The negative predictiv... | 2a0ca0feab7c53195e21eff0090b025b001d29af | 636,587 |
import torch
def mask_independent_loss(mask_x, device='cuda'):
"""mask_x: [n, k, h, w]
"""
n, k, h, w = mask_x.shape
mask_x = mask_x.view(n, k, -1)
mask_x_TT = torch.matmul(mask_x, torch.transpose(mask_x, 1, 2)) # n, k, k
diag_mask = torch.eye(k).to(device) # k, k
positive_term = mask_x_T... | be322daad9f6c4b6f0379ba59e47631d4ffe5740 | 636,588 |
from functools import reduce
def dtype_element_count( dtype, name = None ):
"""Returns the number of values that compose a dtype.
If you need the number of elements of a specifically named
column, pass the root dtype in with the name.
Ie::
>>> a = numpy.dtype([
... ('position... | a5a7a8a2d0a5de04f38e3f6efe3361f59778e0b6 | 636,590 |
def kwargs_to_string(kwargs):
"""
Given a set of kwargs, turns them into a string which can then be passed to a command.
:param kwargs: kwargs from a function call.
:return: outstr: A string, which is '' if no kwargs were given, and the kwargs in string format otherwise.
"""
outstr = ''
for ... | cb0496e0695b84de3922c03d0a542cb5ad091334 | 636,591 |
def parse_strong(soup):
""" Replace strong tags with text:span with automatic style """
strong_tags = soup.find_all("strong")
for s_tag in strong_tags:
s_tag.name = 'text:span'
s_tag.attrs['text:style-name'] = "BOLD"
return soup | 8e6f9f9d7d2d5d63d07fa4bcd06be8bdb7693e29 | 636,592 |
import requests
import os
import logging
def get_metar(base_url, station):
"""
Hit up https://w1.weather.gov/data/METAR/XXXX.1.txt
and pull down the latest current conditions METAR data.
"""
metar = requests.get(os.path.join(base_url, station),
verify=False, timeout=10)
if metar.sta... | 7cb572591786b8d16089cca16f11387515e37f30 | 636,593 |
def append_collection_links(request, response, link_dict):
"""
Convenience method to append to a response object document-level links.
"""
data = response.data
if not 'collection_links' in data:
data['collection_links'] = {}
for (link_relation_name, url) in link_dict.items():
... | 8f25910c182f68c46172354f1a3bf9b336154126 | 636,594 |
def sol_format(values, n):
"""
Formats the size of the n biggest SCCs using the format "A,B,C".
If the number of values is less than n, then the value 0 is used.
"""
res = [0]*n
# Get first n values
for i in range(min(len(values), n)):
res[i] = values[i][1]
# Format to string
... | 0cd5b89105b9acf52e26d76aea128b8fb0d252dc | 636,595 |
def histogram(
es_client, sketch_id, query_string, query_filter, query_dsl, indices):
"""Aggregate query results into number of events per time interval.
Args:
es_client: Elasticsearch client (instance of ElasticSearchDatastore)
sketch_id: Integer of sketch primary key
query_str... | 9dc951f248f5df3bcadf08382cc7bc896e5ba4e1 | 636,596 |
def fatorial(num = 1, show = False):
"""
-> Cálculo do fatorial de um número
:param num: O número a ser calculado
:param show: (Opcional) mostra o calculo se True
:return: Retorna o valor do fatorial do num.
"""
cal = 1
for c in range(num, 0, -1):
cal *= c
if show == True... | 975fd49631ea5b16f4a80102c9d9670d19f56c53 | 636,599 |
def rowswap(matlist, index1, index2, K):
"""
Returns the matrix with index1 row and index2 row swapped
"""
matlist[index1], matlist[index2] = matlist[index2], matlist[index1]
return matlist | e525d3a29345b7a47d080f431ff51a0fc0914ce3 | 636,600 |
import sys
def usage():
"""
Return agent usage message
"""
s = "\n"
s += ("usage: {0} [-verbose] [-force] [-help] "
"-configuration-path:<path to configuration file>"
"-deprovision[+user]|-register-service|-version|-daemon|-start|"
"-run-exthandlers|-show-configur... | 6e5f8735ff6f2f6f969b4da4227d62587a2bbeca | 636,601 |
def check_joystick_compatibility(pg_joystick):
"""
Check if passed joystick is compatible for this application.
Buttons, axes and hats number are checked to consider joystick as compatible or not.
:param pygame.joystick.Joystick pg_joystick: joystick
:return: True if :var pg_joystick: is compatible with current ... | ae1af75b06e85d56e4fc2de130358578df927518 | 636,602 |
def get_xzprime(beam):
"""Used for retrieving data for x-, y- or c-axis of a plot."""
return (beam.a**2 + beam.c**2)**0.5 / beam.b | 2e771913aa1189131910514e98e809af1f21e05a | 636,603 |
import logging
def get_logger(name):
"""Gets logger for module by it's name.
:param str name: name of the module.
:rtype: logging.Logger
"""
name = name.split(".")[-1]
return logging.getLogger(name) | 8d39d901d403f2dcdb3d6fdce96cc3e10a8de921 | 636,604 |
def data_to_psychomotor(dic):
"""
Returns a dictionary of psychomotor details of each student
{name:{details}}
"""
final_dic = {} #will return to psychomotor
dic_psymo = dic["psychomotor"][0] #the relevant sheet
for key, value in dic_psymo.items():
del value["AGE"]
final_d... | a544b0ec8c8e3639ed9e5f82c5b0853c3e283a7e | 636,605 |
def horizontal_overlaps(rect, others, sorted=False):
"""Get rects that overlap horizontally with the
given rect."""
overlaps = []
for other in others:
# Note: can optimise to prevent
# going through the rest of the
# array when we hit a non match
if rect.overlaps_y(other)... | 856499aeb2507c5425de63fe95a129058193438f | 636,607 |
def perm2cycles_without_fixed(perm):
"""
Convert permutation in one-line notation to permutation in cycle notation without fixed points
:param perm: Permutation in one-line notation
:type perm: list
:return: Returns permutation in cycle notation without fixed points
:rtype: list
"""
cy... | 7e513b5a36f10dcadf3994996910ad9008ead2c5 | 636,608 |
def update_behavior_validator(value):
"""
Property: SchemaChangePolicy.UpdateBehavior
"""
valid_values = [
"LOG",
"UPDATE_IN_DATABASE",
]
if value not in valid_values:
raise ValueError("% is not a valid value for UpdateBehavior" % value)
return value | 2f05303562b802b8c3fc3d91994d61acfbbe4ad4 | 636,609 |
def meth_n_step(y0, t0, N, h, f, meth):
""" Compute n values """
for i in range(0, N):
y0 = meth(y0, t0, h, f)
t0 = t0 + h
return y0 | 87ff71d74065c0f791aeb3c25cf56775deddcf20 | 636,610 |
import os
def file_name(path):
"""get file name without extension from a path"""
return os.path.splitext(os.path.basename(path))[0] | 23a07696a9e6b073740903092f0f3794bf3558cd | 636,611 |
def merge(line):
"""
Helper function that merges a single row or column in 2048.
"""
n_elements = len(line)
# Remove 0 entries and slide to the left
line = [value for value in line if value != 0]
index = 0
# Iterate while there are possible pairs
while index < len(line)-1:
# ... | 574d525461d1b0982ad5838db444d742d4d93f7e | 636,612 |
def gcd (a, b):
"""
:param a: int
:param b: int
at least one of the two integers is not 0
:return: largest positive integer gcd that divides the numbers a and b without remainder
"""
# handling of negative integers
if a < 0 and b < 0:
a = abs(a)
b = abs(b)
elif a ... | 6c6dfb45d63baaf914c44caa27225328ce5bbf80 | 636,613 |
def makeseed(a=None):
"""Turn a hashable value into three seed values for whrandom.seed().
None or no argument returns (0, 0, 0), to seed from current time.
"""
if a is None:
return (0, 0, 0)
a = hash(a)
a, x = divmod(a, 256)
a, y = divmod(a, 256)
a, z = divmod(a, 256)
x = (x + a) % 256 or 1
y = (y + a) %... | 256baf066b12da64243f918ee32d87826d144f8f | 636,614 |
import math
def idog_conv(sc):
"""
Conversion of iDoG spatial constants to extents.
"""
return math.sqrt(sc*2) | b409902e5e9ed8a7503c380c4d75c374aaa8c817 | 636,615 |
def get_medi_mapping_umls(mapping_file):
"""
RXCUI_IN,STR,CUI,ATC,NDDF,CODE,HSP
44,mesna,C0000294,R05CB05,2678,595,1
"""
name_to_icd_and_confidences = {}
f = open(mapping_file)
header = f.readline()
for line in f:
words = line.strip().split(",")
name = words[1]
i... | ecf3332dfda1d31d2d74bc072b9f787fa707bac5 | 636,616 |
import random
def gen_client_id():
"""
Generates random client ID
:return:
"""
gen_id = 'hbmqtt/'
for i in range(7, 23):
gen_id += chr(random.randint(0, 74) + 48)
return gen_id | 916b44510eb3455cbeb60995910a887f34f4c947 | 636,617 |
def get_length(df, pdbid, cdr):
"""
Get the length from the dataframe for native or experimental data
:param df: dataframe.DataFrame
:rtype: int
"""
d = df[(df['input_tag'].str.contains(pdbid)) & (df['CDR'] == cdr)]
#print d
return d.iloc[0]['length'] | fca8f453e232a33dc1b29fd4db9f013793982f03 | 636,618 |
def try_cast_float(f):
"""Cast i to float, else return None if ValueError"""
try:
return float(f)
except ValueError:
return None | 8e2159174c4d67f83e20fb0b94661d33dec06291 | 636,619 |
def matrix_indices(vector_idx, matrix_size):
"""
Convert from vector index to matrix indices.
Args:
vector_idx (int): Vector index.
matrix_size (int): Size along one axis of the square matrix to output indices for.
Returns:
(int, int): Row index, column index.
"""
asse... | 0d088bdc52bc6dc9dc43966d5ec8a20f80716c8e | 636,620 |
def check_node_on_pos(graph, position, resolution=1e-4):
"""
Function checks, if at least one node of graph has position 'position'
Returns boolean value. 'position' attribute must be shapely Point object.
Parameters
----------
graph : nx.Graph
networkx graph object (nodes should have a... | eae92a44dad70c0b7ef7cbd8ea29ee7561e17802 | 636,621 |
import pickle
def load_pickle_file(path_to_file):
"""
Loads the data from a pickle file and returns that object
"""
## Look up: https://docs.python.org/3/library/pickle.html
## The code should look something like this:
# with open(path_to_file, 'rb') as f:
# obj = pickle....
## We wi... | 9c23ffeb74189d659b60cbdd4812fb6a573f2037 | 636,622 |
import requests
def get_group_list(ip_address, headers):
""" Get list of groups from OME """
group_list = None
group_list_url = 'https://%s/api/GroupService/Groups' % ip_address
group_response = requests.get(group_list_url, headers=headers, verify=False)
if group_response.status_code == 200:
... | be2ad422ae3993b762b642b94bcece13dbc0e03e | 636,623 |
from datetime import datetime
def parsed_json_to_new_dict(parsed):
"""
Convert parsed dict into dict with python built-in type used by update
function
params:
parsed: parsed dict by json decode
"""
new_anime = {}
new_anime['name'] = parsed['name']
for key in parsed:
if... | f3180abe3cd8fd6a2997944962ecffd98edc2925 | 636,624 |
def expand_unknown_vocab(line, vocab):
"""
Treat the words that are in the "line" but not in the "vocab" as unknows,
and expand the characters in those words as individual words.
For example, the word "Spoon" is in "line" but not in "vocab", it will be
expanded as "<S> <p> <o> <o> <n>".
"""
... | 9c20267e7bf6a31f7f21411ec1db701e088268a1 | 636,625 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.