content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def data_storage_account_settings(conf):
# type: (dict) -> str
"""Retrieve input data storage account settings link
:param dict conf: configuration object
:rtype: str
:return: storage account link
"""
return conf['storage_account_settings'] | 91ff0d940daf60f6a6880eba31db12828f6af058 | 658,935 |
def sumOfDiagonal(n):
"""Sum the diagonals of a n x n spiral (1 in the middle then spiralling out)"""
sum1 = (n * (n + 1) * (2 * n + 1)) // 3
sum2 = ((n - 1) * (n - 1)) //2
return sum1 - sum2 - 1 | 3abe6186c4d5437cf685ce0d4c14baa5a2c50e25 | 658,936 |
def from_datastore(entity):
"""Translates Datastore results into the format expected by the
application.
Datastore typically returns:
[Entity{key: (kind, id), prop: val, ...}]
This returns:
{id: id, prop: val, ...}
"""
if not entity:
return None
if isinstance(entity... | d2db543cfd918488f6da795a7858f96e5cd061c8 | 658,937 |
from pathlib import Path
import os
import shutil
def get_path_rename_gsv(folder_dwl_name):
"""
Args:
folder_dwl_name (str): Folder name where are stored GSV images
"""
path_images = list(Path(folder_dwl_name).glob('*'))
cwd = os.getcwd()
Path(f'{cwd}/metadata').... | 640f346403ebe75d3f71b21232ba5db336a86919 | 658,938 |
def calc_gsd_cross(altitude,
focal_length,
pixel_dim_cross):
"""
ground sample distance (gsd) is the distance between pixel centers measured
on the ground.
https://en.wikipedia.org/wiki/Ground_sample_distance
Returns
-------
double : meters per pixel
... | 97dbb18341684d4727e31378343896a2c6e6e47b | 658,939 |
def set_lat_lon_attrs(ds):
""" Set CF latitude and longitude attributes"""
ds["lon"] = ds.lon.assign_attrs({
'axis' : 'X',
'long_name' : 'longitude',
'standard_name' : 'longitude',
'stored_direction' : 'increasing',
'type' : 'double',
'units' : 'degrees_east',
... | fe95bbd7bd698b7cc0d5d1a60713477ab36e909a | 658,940 |
import time
import os
def _get_print_file_name(file_name):
"""Add timestamp suffix to file name. Rename the file name: file_name + "." + time(seconds)."""
time_second = str(int(time.time()))
file_name = file_name + "." + time_second
if os.path.exists(file_name):
ValueError("This file {} alrea... | 63f5301a365f9ee61110f946cb2497d1e3d83a00 | 658,941 |
def afill(start, end, ntries):
"""A function that fill evenly spaced values between two numbers"""
step = (end-start)/float(ntries+1) if ntries > 0 else 0
final_list = [float(start) + (i+1)*step for i in range(ntries)]
return(final_list) | 32d66e2fa01dd8750ffefc52d82c86696f4336dd | 658,942 |
def utf8ize(x):
"""
Converts to utf8 if non-empty
:param x:
:return:
"""
if x is None:
return None
return x.encode('utf-8') | 1b20ca9525bffd7285e386de2b21483d47b467d8 | 658,943 |
def overwrite_tags_with_parameters(tagged_lines,parameter_strings):
"""
Takes tagged lines and the respective options and creates a
valid Python source file.
---Inputs---
tagged_lines : {list}
list of all lines making up the tagged source code of the
user's solver (all lines included... | b22b8d2de1f10e70e9ac2758b31b75f0e11a8e6a | 658,944 |
def get_state_labels(clusterings, k):
"""
Get state labels from clusterings.
:param clusterings: DataFrame;
:param k: int;
:return: Series;
"""
return clusterings.ix[k, :].tolist() | cc2967f32ede512daab9ec07b25fd1cd7e6fcea5 | 658,945 |
from datetime import datetime
def to_epoch(ogtime):
"""Convert formatted time to Unix/epoch time."""
fstr = '%Y-%m-%dT%H:%M:%S.%fZ'
epoch = datetime(1970, 1, 1)
finaltime = (datetime.strptime(ogtime, fstr) - epoch).total_seconds()
return finaltime | 0d4714dd15296d677f60f5f24b077d6991597f72 | 658,946 |
def restructure_output(_doc):
"""Restructure the API output"""
field_mapping = {'chembl.inchi': 'inchi',
'chembl.inchi_key': 'inchikey',
'aeolus.drug_rxcui': 'rxcui',
'chembl.smiles': 'smiles',
'pubchem.cid': 'pubchem',
... | ff7ac4a45373f3534af7cb77b24358b0dd476583 | 658,947 |
def readOS(seqTitle):
"""Extract OS tag from sequence description
Get the microorganism name from sequence title
Args:
seqTitle: SequenceObject.description
Return
Microorganism species name
"""
i = 0
x = seqTitle.find("=", i) + 1
i = x + 1
y = seqTitle.find("=", i... | a8a1b6bfb96e297a6a1d9220fb7efb102ea0e0a6 | 658,948 |
def _plane_to_iy(plane):
"""gets the index fo the mirror plane"""
plane = plane.strip().lower()
if plane == 'yz':
iy = 0
if plane == 'xz':
iy = 1
elif plane == 'xy':
iy = 2
else: # pragma: no cover
raise NotImplementedError("plane=%r and must be 'yz', 'xz', or 'x... | a55fdf132ff1f2200ff31653cd5b2cecc31eb245 | 658,949 |
import torch
def prepare_cross_attention_masks_test(batch_golden_chunks, batch_refs, config):
"""
in each instance golden_chunks[0] is the first chunk (C1*)
# [cls] Sent1 Sent2 [sep]
# C1* C1* C2 NA
"""
bsz = len(batch_refs)
max_num = max([len(golden_chunks) for gold... | 76ff4ad4fbe58b50df66c64517cd0a3dd2f6f232 | 658,951 |
def typemap(dbt):
"""translate sqlite3 types to myria types. Not complete!!"""
if "VAR" in dbt:
return "STRING_TYPE"
elif "int" in dbt or "long" in dbt:
return "LONG_TYPE"
elif "real" in dbt or "double" in dbt:
return "DOUBLE_TYPE"
else:
return dbt | 0073768524951a3f7dd43f2705d3049f9fe7578f | 658,952 |
def u2u1(u2):
"""
inch to mm, all strings
"""
u2 = float(u2)
u1 = int(round(u2 * 25.4, 0))
return str(u1) | dd3643192cbfb68bc76c9624b64e23824b7ccbd9 | 658,953 |
def fetch(field, *source_records, **kwds):
"""Return the value from the first record in the arguments that
contains the specified field. If no record in the chain contains
that field, return the default value. The default value is specified
by the "default" keyword argument or None. If keyword argument
... | e177e703462e4c67d78bc524a23cccd767140b3f | 658,954 |
def mock_monitoring_request_object():
""" Fixture for monitoring_request object created with sample data """
class MockMonitoringRequest:
service_choice = 'citizenship_application'
office_choice = 'helsinki'
to_email = 'test@example.com'
@staticmethod
def get_office_choi... | 23cbb86c22b0bb0412278b7ceff6b34a0141355a | 658,955 |
def center_crop(img, output_size, center=None, scale=None):
"""
Args
- img: np.ndarray. img.shape=[height,width,3].
- output_size: tuple or list. output_size=[height, width].
- center: tuple or list. center=[x,y].
If cenetr is None, use input image center.
- scale: float.
... | d8863f4328d99cf76cc764f9e7bb8ec37fa4b08b | 658,956 |
import re
def truncate_html_words(s, num, end_text='...'):
"""Truncates HTML to a certain number of words.
(not counting tags and comments). Closes opened tags if they were correctly
closed in the given html. Takes an optional argument of what should be used
to notify that the string has been truncat... | 6995b4bce78670884508e08521da78d2d88fd5bc | 658,957 |
def Square(x, a, b, c):
"""Second order polynomial
Inputs:
-------
``x``: independent variable
``a``: coefficient of the second-order term
``b``: coefficient of the first-order term
``c``: additive constant
Formula:
--------
``a*x^2 + b*x + c``
"""
r... | 5180bc3769d331c04b384bf5c5cb1bf65bf71b0a | 658,958 |
def base_add():
"""Fixture for base function to decorate"""
def _add(a, b):
"""Adding a and b"""
return a + b
return _add | 0a62cbc29be17b4c4a41a122b49ce99380159f0b | 658,959 |
def shuffle_product(x, y):
"""
Calculates shuffle product of two elements.
"""
if '.' not in x:
if '.' not in y:
return x + '.' + y + '|' + y + '.' + x
else:
y_split = y.split('.')
res_1 = x + '.' + y
res_2 = '|'.join(map(lambda z: y_split[... | e2cce5e1b7688b057dc70e64d05e3bbccbbc153f | 658,960 |
def insert_row(table_name, values):
"""Inserts a row in 'table_name' with values as 'values'"""
query = f'INSERT INTO {table_name} VALUES ('
no_attrs = len(values)
# Add values to query
for i in range(0, no_attrs - 1):
query += f'{values[i]}, '
# Add semicolon for last value
query... | 9f0bde3aeddbbe0bbd33ac04a9dedfab7faae17d | 658,961 |
def rank_models(ckpt_path2dfs, metric, maximize_metric):
"""Rank models according to the specified metric.
Args:
ckpt_path2dfs (dict): mapping from ckpt_path (str) to (pred_df, gt_df)
metric (function): metric to be optimized, computed over two
DataFrames, namely the predictions and... | ca5857685c382e10de1a0781d82baf76bc468457 | 658,962 |
import six
def convert_to_unicode(text):
"""Converts `text` to Unicode (if it's not already), assuming utf-8 input."""
if six.PY3:
if isinstance(text, str):
return text
elif isinstance(text, bytes):
return text.decode("utf-8", "ignore")
else:
raise V... | 8e587d7e28e17c3883fe9077bcf9984dbc17e8d4 | 658,963 |
def define_engine(engine_option_value):
"""
Define engine files, and options.
"""
optdict = {}
engineinfo = {'cmd': None, 'opt': optdict}
for eng_opt_val in engine_option_value:
for value in eng_opt_val:
if 'cmd=' in value:
engineinfo.update({'cmd': value.spl... | 3c0b76a3c2f9d330d86ee9cabccfa4656d5412c0 | 658,965 |
def assemble_replace_dict(command, use_gpu, additions, queue, time, ngpu):
"""Create dictionary to update BASH submission script for torque.
Parameters
----------
command : type
Command to executer through torque.
use_gpu : type
GPUs needed?
additions : type
Additional c... | 63665247b592210fe15f027cbb171475278094cd | 658,966 |
def u_init(x, y, xmin, xmax, ymin, ymax):
"""
initial condition
"""
center = (
.75*xmin + .25*xmax,
.50*ymin + .50*ymax
)
radius = 0.1
height = 0.5
return 1 + height * ((x-center[0])**2+(y-center[1])**2 < radius**2) | b6743f3695480edad9366263592af8aaf7d24d82 | 658,967 |
def _annotate_table(data_table, keyword_dict, num_sources, product="tdp"):
"""Add state metadata to the output source catalog
Parameters
----------
data_table : QTable
Table of source properties
keyword_dict : dict
Dictionary containing FITS keyword values pertaining to the data pr... | 3b9221a24d83e9e9c3473e05a7db20f96c84c4f0 | 658,968 |
import torch
def ex_loss_logits(logits, target):
"""Modified from: https://github.com/PengtaoJiang/OAA-
PyTorch/blob/master/scripts/train_iam.py.
Paper: http://openaccess.thecvf.com/content_ICCV_2019/papers/Jiang_Integral_Object_Mining_via_Online_Attention_Accumulation_ICCV_2019_paper.pdf.
"""
as... | 3db06fab918c65592bb72be9cc44693548e4cb87 | 658,969 |
import itertools
def cycle(collection):
""":yaql:cycle
Makes an iterator returning elements from the collection as if it cycled.
:signature: collection.cycle()
:receiverArg collection: value to be cycled
:argType collection: iterable
:returnType: iterator
.. code::
yaql> [1, 2]... | b2e7b60d2e6bef14a42c675fa59ce692d4d75ab7 | 658,970 |
import typing
import subprocess
def get_graph(filename: str, protocol: str, role: str) -> typing.Tuple[int, str]:
"""Get dot representation of EFSM from Scribble-Java.
Return exit code and command line output."""
_role_protocol = f"--fsm={role}@{protocol}"
command = ('dune','exec','nuscr','--', _role_... | 66197dfa4a480ac1c8dc3f95f0eaf472af8e3832 | 658,972 |
def boolean_content_matcher(string_array: str, substring: str):
"""Returns a list of tuples containing True/False if the substring is found in each element in the array.
Examples:
>>> text_list = ['lambda functions are anonymous functions.',
... 'anonymous functions dont have a name.',
... | 1de5e5d81f5b88f0283ff2931de464b10df4c009 | 658,974 |
import random
def file_flag():
"""Either -f or --file"""
return "-f" if random.randint(0, 1) else "--file" | 2e54d3063fe896088be12fef512bb4bd75825192 | 658,975 |
import requests
def perform_post_request(session, url, data=None, headers=None, encoding=None):
"""
Performs post request.
:param session: `Request` session
:param url: URL for `Request` object
:param data: (optional) Dictionary, list of tuples, bytes, or
file-like object to send in the bod... | db5d934cdf7930cd66b90ce161ce4ad4b9344256 | 658,977 |
def brand_profitsharing_return_query(self, sub_mchid, out_return_no, order_id=None, out_order_no=None):
"""查询连锁品牌分账回退结果
:param sub_mchid: 子商户的商户号,由微信支付生成并下发。示例值:'1900000109'
:param out_return_no: 商户回退单号,商户在自己后台生成的一个新的回退单号,在商户后台唯一,示例值:'R20190516001'
:param order_id: 微信分账单号,与out_order_no参数二选一,示例值:'3008450... | 4d3806b928fc08fa7907f2e7d4a1645434662a3f | 658,979 |
def apply_first(seq):
"""Call the first item in a sequence with the remaining
sequence as positional arguments."""
f, *args = seq
return f(*args) | 0f7353b66ea677e4b4090dc2824556952daaa7c9 | 658,980 |
def get_P_fan_mid_H(V_fan_mid_H):
"""(14)
Args:
V_fan_rtd_H: 中間暖房能力運転時の送風機の風量(m3/h)
V_fan_mid_H: returns: 中間暖房能力運転時の送風機の消費電力(W)
Returns:
中間暖房能力運転時の送風機の消費電力(W)
"""
return 8.0 * (V_fan_mid_H / 60) + 20.7 | 5b8192665a54a0b650c5a76dc663f4af4cf74b4b | 658,981 |
import warnings
def multichain(self, *others):
"""Makes self inherit from multiple prototypes.
Any relationship with previous parent prototypes will be removed.
When the parent prototypes share attributes with the same name, the
parent prototype that is first in the list of prototypes will
provid... | 6cb784493677d8603d52a0d2cb96b31795b6ebb9 | 658,982 |
from typing import List
def _transform_body_for_vscode(body: str) -> List[str]:
"""snippetのbodyをvscode用に変換する.
改行区切りのlist, space4つをtabに変換.
:param body: string of a snippet body
:return body_for_vscode: vscode-snippet形式のbody
"""
body_list = body.split('\n')
body_for_vscode = [b.replace(' ... | 1261efcedb87848fdfd9fee3ebed36c956db0019 | 658,983 |
import re
def rights_are_open(ro):
""" returns True if the given right object is open, i.e. its usage
not restricted in a way that necessitates interation with the rights
holder. False otherwise (also if rights object is unknown).
"""
if ro.spdx is not None and re.match(r"CC-(0|BY-\d\.\d|B... | 0f579bd1fe7c3bced95ab40dd85cd392454f0ede | 658,984 |
def name_eq(name):
"""add a 'name' attribute (a string most likely) to a function"""
def wrapper(f):
f.name = name
return f
return wrapper | a95fe0f0c3c8fb2dd097086af216e3c27e1a473c | 658,985 |
def get_voc_abb(vocation: str) -> str:
"""Given a vocation name, it returns an abbreviated string"""
vocation = str(vocation)
abbrev = {'none': 'N', 'druid': 'D', 'sorcerer': 'S', 'paladin': 'P', 'knight': 'K', 'elder druid': 'ED',
'master sorcerer': 'MS', 'royal paladin': 'RP', 'elite knight'... | 5ef42ed160fc8b1ba39e2ee47fe9bb52d46acb8a | 658,986 |
import socket
import os
def get_data_folder():
"""
return server-dependent path to store the data
"""
hostname = socket.gethostname()
if hostname.startswith('visiongpu'):
data_folder = '/data/vision/phillipi/rep-learn/datasets'
elif hostname.startswith('yonglong-home'):
data_fo... | c4612d78e23d535e606aca9c5e41d2f26858c08b | 658,987 |
def _get_required_value(key, value):
"""Return the requested value."""
if '/' in value:
# we need to split the value
split_value = value.split('/')
eval_string = 'key'
for value in split_value:
eval_string = "%s['%s']" % (eval_string, value)
return eval(eval_s... | 0307b55a9b2fae379a5dde85c56023c7db834766 | 658,988 |
def isWikiTable(tag):
"""Filter for determining if a given element is a WikiMedia table entry
"""
return tag.name == 'table' and 'class' in tag.attrs and 'wikitable' in tag.attrs['class'] | ee89111fed9423f5faf8948de25fa8cb23e70484 | 658,989 |
def get_file_contents(filename):
""" Given a filename,
return the contents of that file
"""
try:
with open(filename, 'r') as f:
# It's assumed our file contains a single line,
# with our API key
return f.read().strip()
except FileNotFoundError:
... | 9c09c0d705f3fb36e5c687a5dc0a0dbaad9ad8d8 | 658,990 |
def getCpFilesFromIps(ipsConf):
"""
This goes through all of the components and gets the input and data files in order to
decide what to copy over.
"""
allCpFiles=[]
for component in ipsConf['PORTS']['NAMES'].split():
compimp=ipsConf['PORTS'][component]['IMPLEMENTATION']
if ipsCo... | 6bfbc179235a9594157f5667d1b51a9990e64ab7 | 658,991 |
def order_ids(ids):
"""
This returned the ids sorted
:param ids: array, tuple, iterator. The list of ids
:return: A sorted tuple of the ids
"""
return tuple(set(ids)) | f70072a09b824a875f19374dc1b3d9aa0a202cd7 | 658,992 |
import torch
def load_model(local_pth, model):
"""Load model."""
checkpoint = torch.load(local_pth)
model.load_state_dict(checkpoint, False)
return model | e50290f2f613137752799d96154549ccc48f5652 | 658,993 |
def clean_root(string):
"""
Remove unexpected character in root.
"""
return string | c01eaf6648af8a43fdb05c8d15a0b7780f0392c2 | 658,994 |
def repr_method():
"""repr: Basic representation of an item."""
class _Representable:
def __repr__(self):
return "<- deep soul ->"
return repr(_Representable()) | 1b72008693665144e95162bebf13dc364eb8122b | 658,995 |
def pickfirst(files):
"""Return first file from a list of files
Parameters
----------
files : list of filenames
Returns
-------
file : returns the filename corresponding to the middle run
"""
if isinstance(files, list):
return files[0]
else:
return files | fc91800cc1657be7f2e475d328f3f6d7e40e4e97 | 658,996 |
def ensure_slice(s=None):
"""Ensures a valide slice is returned."""
if isinstance(s, str):
s = s.split(':')
if len(s) == 1:
s = int(s[0])
s = slice(s, s + 1)
else:
s = [x or 'None' for x in s]
s = eval('slice({0})'.format(', '.join(s)))
... | 5116e620bc1d38083c3121687f6c174ccb53cec5 | 658,998 |
def close_ring(coordinates):
"""
Makes sure the ring is closed; if it is not, then closes the ring.
:param coordinates: a collection of coordinates representing a polygon
:return: a closed ring
"""
if coordinates[0] != coordinates[-1]:
coordinates.append(coordinates[0])
return coord... | 8197a1c70b566d69746c2f6ffd2fa756cbf601e5 | 658,999 |
from typing import Tuple
def substitute(txt: str, span: Tuple[int, int], new: str) -> str:
"""Substitute a span with a single or empty character 'new'."""
return txt[: span[0]] + new + txt[span[1] :] | f585e86580ac7be70f42abc944137a8f8b4e8583 | 659,000 |
def get_all_labels(html_string, label):
"""get_all_labels: This function get all label with their content from a HTML's content
Args:
html_string (str): It's the HTML content where we want to get all labels
label (str): It's the type of label that we specified to get all labels from html's cont... | 53bf8aa7253713dbab09d0217b1a111226e59ee7 | 659,003 |
def _without_process_wrapper_transition_impl(_settings, _attr):
"""This transition allows rust_* rules to invoke rustc without process_wrapper."""
return {
"//rust/settings:use_process_wrapper": False,
} | 198408e16b9184607bec655e4f04e454a7e2899e | 659,004 |
def xor(data, key):
"""
XOR a byte-stream with a single key value (int)
@zc00l
"""
if type(key) is not int:
return None
output = ""
for char in data:
index = data.index(char)
output += chr(ord(data[index]) ^ key)
return output | 914aac6fb81b19d5ae93a395cfc6258e6ddda0d0 | 659,005 |
def encode(request):
"""Encode request (command, *args) to redis bulk bytes.
Note that command is a string defined by redis.
All elements in args should be a string.
"""
assert isinstance(request, tuple)
data = '*%d\r\n' % len(request) + ''.join(['$%d\r\n%s\r\n' % (len(str(x)), x) for x in requ... | f14de735f7f6311e4bc46575a98a0e3ee25dce1e | 659,006 |
def fracval(frac):
"""Return floating point value from rational."""
if frac.find("/") == -1:
return float(frac)
else:
x = frac.split("/")
return float(x[0]) / float(x[1]) | 4a6161479cd06cc6ebef64a7255d8974fea05ac7 | 659,008 |
import os
import re
def get_templates(tpldir, themedir, outputdir, template_vars):
"""
Get those templates that need processing.
"""
templates = []
seen = set()
searchdirs = [tpldir]
if themedir and os.path.exists(os.path.join(themedir, 'templates')):
searchdirs.append(os.path.join... | 7a7f5329550a45cab4daf115119d9648d915663c | 659,009 |
import socket
import os
def get_worker_name():
"""This is the get worker name function.
It returns worker name hostname.pid .
"""
return '{0}.{1}'.format(socket.gethostname().partition('.')[0], os.getppid()) | b6d35829b2d732a4817a6c0e5c6ab90e1a1248fa | 659,010 |
def is_record(path: str) -> bool:
"""
Is filename a record file?
:param (str) path: User-supplied filename.
:return: True if filename is valid record file; otherwise False.
:rtype: bool
"""
return path.find("..") == -1 | be4779214518bc22fda8bb304f4b2bcbda56d53d | 659,011 |
import random
def _generate_cart_id():
""" function for generating random cart ID values """
cart_id = ''
characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890!@#$%^&*()'
cart_id_length = 50
for y in range(cart_id_length):
cart_id += characters[random.randint(0, len(... | e8c13a8f66bfeccdffa11e1c0a33c11214b64a1b | 659,012 |
def starstararg_func(**kwargs):
"""
>>> starstararg_func(a=1)
1
"""
return kwargs['a'] | e76e92b30dff8797a878058b38cbdb6c895dd6fb | 659,013 |
import torch
def get_all_error_instance_indices(h1, h2, batch_ids, batched_evaluation_data, batched_evaluation_target,
get_instance_metadata=None,
device="cpu"):
"""
Return the list of indices of instances from batched_evaluation_data on wh... | da160b3ef15bd185e37e581b77b2319b06fdd69f | 659,014 |
import os
def get_root_path():
"""
Gets the root directory for the drive.
NOTE: On Windows, it returns 'C:\' or the path to the root dir for the drive.
On Linux, it returns '/'.
:return: Path to the root directory for the drive.
:rtype: str
"""
return os.path.realpath(os.sep) | c5f964c9fcc24d3300df4180df172b4bc4ac2bda | 659,017 |
def _read_creds(
filename: str
) -> tuple:
"""Read credentials and home latlong from login.conf file."""
creds_dict = {}
with open(filename) as f:
for line in f:
(key, val) = line.split()
creds_dict[key] = val
return (
creds_dict['email'], creds_dict['password... | b58d31cfa79d91c294540d26ef29c52ea05c203e | 659,018 |
import os
import re
def output_file(input_path: str, input_dir: str, output_path: str) -> str:
"""
Converts an input path to an output DSDLC path
>>> output_file('foo/uavcan_data_types/cvra/20001.Reboot.uavcan', 'foo/uavcan_data_types/cvra', 'dsdlc_generated')
'dsdlc_generated/cvra/Reboot.hpp'
""... | df22f9ebd34a8e58b80e7ca4187ecf80e7d41202 | 659,019 |
def count_neighbors_wrap_around(grid2count, posInRow, posInCol, row_Count, col_Count):
"""returns number of ALIVE neighbors from a given position on a given grid using wrap around approach"""
count = 0
for x in range(-1, 2):
for y in range(-1, 2):
if grid2count[(posInRow + x) % row_Coun... | 524947c49cdbb56bbf7067057afa81a00099f765 | 659,020 |
def process_isis(isis):
"""Process data in isis object."""
# format string for isis sr label table
isis_header = ("\nIS-IS {instance} IS Label Table:\n"
"Label Prefix/Interface\n"
"---------- ----------------")
# format string for isis neighbor row
... | fe38741ba173485baf2c850a959f4b38dd6955f7 | 659,021 |
def align_dataframe(main, converter):
"""Align index / column for dot calculation.
Align B/A for convert A/Sample into B/Sample.
While pandas ok with unsorted, the dimension has to be compatible.
"""
# Make sure that they are at least compatible, at least 1 intersection
MAINIDX = set(main.inde... | a39da866632cc0f5518a3de29ea0fc97f368e4b7 | 659,022 |
from typing import Sequence
from typing import Optional
from typing import List
def build_tree(
tree_structure: Sequence,
multiline_pad: int = 1,
pad_depth: Optional[List[int]] = None,
_indent_data: Optional[list] = None,
) -> str:
"""
Build a tree graph from a nested list.
Each item in t... | 381ab26c517aa49e18e3e1b7de989ce98453924f | 659,023 |
import shutil
def is_rg():
"""Returns the path to rg."""
return shutil.which("rg") | cbec4233ca9baee38be9864324f0d4fa2cc91cc3 | 659,024 |
def calcula_d(e, n):
"""
calcula_d: int x int --> int
calcula_d(e, n) devolve o menor inteiro d em que se verifica a igualdade
d * e = 1 + k * n, sendo k um numero inteiro.
"""
d, k = 0, 0.5 #numero decimal arbitrario para k
while int(k) != k:
d = d + 1
k = (d * e - 1)/n
... | f76ad7664131fa4f73fd9fba81c66b6ee499464b | 659,025 |
def foreign_key_gen(table_name, related_name, del_type='CASCADE'):
"""
del_type: CASCADE SET_NULL DO_NOTHING
"""
return "models.ForeignKey(to=" + table_name + ", db_constraint=False, on_delete=models."+del_type+", blank=True, null=True, related_name='" + related_name + "')" | 5df24b3a855761703c45900c309825cc0a922a23 | 659,026 |
import re
def add_pre_main_init(startup: str) -> str:
"""Add pw_stm32cube_Init call to startup file
The stm32cube startup files directly call main(), while pigweed expects to
do some setup before main is called. This could include sys_io or system
clock initialization.
This adds a call to `pw_st... | 489272ae676a2edcb80e6e08246c5b25a4952b79 | 659,027 |
from typing import List
def open_uniform_knot_vector(count: int, order: int, normalize=False) -> List[
float]:
"""
Returns an open (clamped) uniform knot vector for a B-spline of `order` and `count` control points.
`order` = degree + 1
Args:
count: count of control points
order: ... | 4dba197dfd9714d9354fcd40469b92200f99b3b5 | 659,028 |
def getsymbol(tree):
"""Get symbol name from valid ``symbol`` in ``tree``
This assumes that ``tree`` is already examined by ``isvalidsymbol``.
"""
return tree[1] | 36b4d038370bac45b89934ae1b80418da48384a0 | 659,029 |
def __reconstruct_spectrum(theta, sig_matrix):
"""
Reconstruct the spectrum using the estimated mixture proportions of the reference signatures and the signature matrix.
:param theta: estimated mixture proportions (numpy.array)
:param sig_matrix: The matrix containing the weights of each mutational ty... | c3f40ac2a80e135ffba93800d5d420a7a05b1662 | 659,030 |
def unlock(server_id, **kwargs):
"""Unlock server."""
url = '/servers/{server_id}/action'.format(server_id=server_id)
req = {"unlock": None}
return url, {"json": req} | e98dde30943c12ca390e4f7a099e24d6e4a0a66f | 659,031 |
import re
def mk_rule_fn(rule, name):
"""Test helper for converting camelCase names to
underscore_function_names and returning a callable rule fn."""
parts = re.sub('(?!^)([A-Z][a-z]+)', r' \1', name).split()
parts.insert(0, 'with')
fn_name = '_'.join(map(lambda x: x.lower(), parts))
retur... | e6ba5e1c409077911e2b67878dba078dc2890c38 | 659,032 |
def __dumpbin_parse_exports(input):
"""Parse thr output from dumpbin as a list of symbols"""
ret = []
lines = input.split('\n')
for line in lines:
arr1 = line.split()
if len(arr1) == 4 and arr1[1] != 'number' and arr1[1] != 'hint':
ret.append(arr1[3])
return ret | 7f5722adefe88a8ab9a124a94c0d0707c2235c39 | 659,033 |
def _ParseTaskId(task_id):
"""Parses a command ID from a task ID.
Args:
task_id: a task ID.
Returns:
(request_id, command_id)
"""
if task_id is None:
raise ValueError("task_id cannot be None")
ids = task_id.split("-", 2)
if len(ids) == 3:
return ids[0], ids[1]
return None, ids[0] | 7de34c957ffcbb6e549ea7a301aee66f1241fa3a | 659,034 |
import re
def remove_single_quotes(text):
"""
Simple helper function that replaces single quotes with double quotes
at the beginnig of the key and value fields.
"""
# pattern = re.compile("(?<!\\\\)\'")
pattern_1 = re.compile(r"(?<=[\{|,|, |:])\'")
pattern_2 = re.compile(r"\'(?=:|,|\})")
... | f1892747c14cc958bbddb0a8913ba457201cb143 | 659,035 |
def get_contacts(filename):
"""
Return list of the contacts
Args:
filename: (str): write your description
"""
names = []
emails = []
with open(filename, mode='r', encoding='utf-8') as contacts_file:
for a_contact in contacts_file:
names.append(a_contact.split()[0... | fc610c8380e4e2ab02e7d19a764610ecdc83796b | 659,036 |
def convert_da(data_line, delex=False):
"""Convert DA into Alex format (and possibly delexicalize)."""
da = data_line.da
if ';' in da:
da = da.split('; ')
else:
da = [data_line.dat + ': ' + da]
ret = []
for da_part in da:
dat, slots = da_part.split(': ')
# conver... | d1b6bc133948e377bc7038f355a1bf091c4e9853 | 659,037 |
def recovery_clifford(state: str):
"""
Returns the required clifford to return to the ground state based on the position on the bloch sphere
:param state: The current position on the Bloch sphere
:return: A string representing the recovery clifford
"""
# operations = {'x': ['I'], '-x': ['Y'], 'y... | ebff361c7a5fa09b6b0d59e6d8c78efad962f148 | 659,038 |
import os
import glob
def post_crash_report(project_path, current_iteration):
"""
Detect crashes after the phase has finished by looking through the slurm files in slurm_out_files
"""
# Check if we have created the slurm file directory
if not os.path.exists("slurm_out_files"):
print("Cras... | 5b18b86ef63f536028a5ee11286006a3616c2722 | 659,039 |
from bs4 import BeautifulSoup
def get_wiki_from_spotlight_by_name(spotlight, name):
"""Given the spotlight output, and a name string, e.g. 'hong kong'
returns the wikipedia tag assigned by spotlight, if it exists, else '-'."""
actual_found = 0
parsed_spotlight = BeautifulSoup(spotlight.text, 'lxml')
... | 911538367813fa6e80cd73c35f744d1055390248 | 659,040 |
def pipfile_text():
"""Pipfile as would be returned by f.open().read()"""
return """
[[source]]
name = "pypi"
url = "https://pypi.org/simple"
verify_ssl = true
[packages]
matplotlib = ">=3.1.1, <=3.1.2"
pyhive = {extras = ["hive", "presto"], version = "==0.6.1"}
pandas = {extras = ["fake_extra"], version = "==... | a285935249fb1d4f39c4fcf98f43789d3628f418 | 659,042 |
def twos_complement(n: int, w: int = 16) -> int:
"""Two's complement integer conversion."""
# Adapted from: https://stackoverflow.com/a/33716541.
if n & (1 << (w - 1)):
n = n - (1 << w)
return n | 859c925fbaf642d9365680230bd7b297f64d4c7a | 659,043 |
def getuser():
"""Get instagram username."""
instauser = input('What instagram user to get information about? ["q" for quit]: ')
return instauser | f6955c77fa2b30183ea49db35e7207cff23cdcd6 | 659,044 |
import requests
import json
def wechat_enterprise_push(corp_id, corp_secret, agent_id, to_user, msg):
"""
:param corp_id: 企业 ID
:param corp_secret: 自建应用 Secret
:param agent_id: 应用 ID
:param to_user: 接收者用户,多用户用|分割,所有用户填写 @all
:param msg: 推送消息
:return:
"""
# 获取 access_token
... | 09b0aa2946ff30ee7953dc10ccd16a295bcb588b | 659,045 |
def base2int(arr, base):
""" convert array from given base to base-10 --> return integer"""
res = 0
for i in range(len(arr)):
res+=(base**i)*arr[i]
return res | cd53d0839316929df80e0e956dd65aae3a7488fc | 659,046 |
def request(context):
"""Retrieves the request from the controller.
Deprecated: Just use 'request'
Example:
.. code-block:: python
{{ request() }}
"""
return context['context']['request'] | 8a4f848dfdb591cffa463bc884820ac5ad909754 | 659,047 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.