content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def locations():
"""Fetches and displays the locations in Delhi"""
status, body = api.locations(city='Delhi')
return str(body['results']) | 17a02bad20b0c4ab3d86f5b726f0bc800c7897fe | 63,068 |
import numpy
import scipy
def _golbub_welsch(orders, coeff1, coeff2):
"""Recurrence coefficients to abscisas and weights."""
abscisas, weights = [], []
for dim, order in enumerate(orders):
if order:
bands = numpy.empty((2, order))
bands[0] = coeff1[dim, :order]
... | 7edd7918c33482b3d33b49e9c90dfeab4f73fc6d | 63,069 |
import array
def solve(self):
"""Compute the parameters dict for the equivalent electrical circuit
cf "Advanced Electrical Drives, analysis, modeling, control"
Rik de doncker, Duco W.J. Pulle, Andre Veltman, Springer edition
<--- --->
-----R-----wsLqIq-... | c24cb121508e0ef1b079d59192c2876712c4b11a | 63,070 |
def register(request):
"""A view that manages the registration form"""
if request.method == 'POST':
user_form = UserRegistrationForm(request.POST)
if user_form.is_valid():
user_form.save()
user = auth.authenticate(email=request.POST.get('email'),
... | 44f61c8ff8b55e11a544eec098ad93fcbea6a2b2 | 63,071 |
from typing import Union
def reference(context: RuntimeContext, x: Union[ObjectRow, str]):
"""YAML-embeddable function to Reference another object."""
if hasattr(x, "id"): # reference to an object with an id
target = x
elif isinstance(x, str): # name of an object
obj = context.field_vars... | fc5dd50caf998cf351f89627db9551dff444d64c | 63,072 |
def merge_coordinate_molecular(coor, lattice, wyckoffs, w_symm_all, tol, orientations, PBC=[1,2,3]):
"""
Given a list of fractional coordinates, merges them within a given
tolerance, and checks if the merged coordinates satisfy a Wyckoff
position. Used for merging general Wyckoff positions into special ... | 1c21fd7f2dbe1ddc6acb0d70790cf67d1d4fce53 | 63,073 |
def _validate_perf_config(config_contents, required_parameters):
"""Validates the perf config file contents.
This is used when we're doing a perf try job, the config file is called
run-perf-test.cfg by default.
The parameters checked are the required parameters; any additional optional
parameters won't be c... | 052244699de20ea18453efccb0c4ae01080d7678 | 63,074 |
def insert(root: Node, value: int) -> Node:
"""
Insert element
Split current tree with a value into left, right,
Insert new node into the middle
Merge left, node, right into root
"""
node = Node(value)
left, right = split(root, value)
return merge(merge(left, node), right) | 529ffce8f107a40cd161f10b6a77a65c0ed363ba | 63,075 |
def get_thickness_stats_for_both_hemispheres(subjects_dir, subject_id, mask_file):
"""
This function..
:param subject_id:
:param subjects_dir:
:param mask_file:
:return:
"""
stats = dict()
lh_thickness, rh_thickness = get_thickness_files_for_both_hemispheres(
subjects_dir, s... | d82c9bb9af3e9a505097e652ff95598998d17cbb | 63,076 |
from typing import Iterable
from typing import Callable
from typing import Tuple
from typing import List
def segment(iterable: Iterable[P], filter: Callable[[P], bool]) -> Tuple[List[P], List[P]]:
"""
:param iterable An iterable bunch of data to be split into two
:param filter A filter to run over each el... | 89daed0cdf3577f10afd12b740bd37cdd271bf12 | 63,077 |
def uridefrag(uristring):
"""Remove an existing fragment component from a URI string."""
parts = uristring.partition('#')
return DefragResult(parts[0], parts[2] if parts[1] else None) | dd211bac44834a481a3f8bbc018992df36fd8e8b | 63,078 |
from re import L
def _miso_op(data_list, func, *args, **kwargs):
"""Create multi input and single output Caffe op"""
n = caffe.NetSpec()
if not isinstance(data_list, (tuple, list)):
raise TypeError("Need tuple or list but get {}".format(type(data_list)))
input_list = list()
for idx, data i... | 02cdd3c38c3ff027a5ef748eeb5fddd55f735fff | 63,081 |
def autodl_auc(solution, prediction, valid_columns_only=True):
"""Compute normarlized Area under ROC curve (AUC).
Return Gini index = 2*AUC-1 for binary classification problems.
Should work for a vector of binary 0/1 (or -1/1)"solution" and any discriminant values
for the predictions. If solution and predict... | f1a810fd5bce751bfdcea4021444a55a2eb7618c | 63,082 |
def dectobin(x):
"""Convert Decimal to Binary. Input is a positive integer and output is a string."""
ans = ''
while x > 1:
tmp = x % 2
ans = str(tmp) + ans
x = x // 2
ans = str(x) + ans
return ans | 21a6c0c161088f1e73afe87707503667b4651c87 | 63,083 |
def normalize_signals(signals) -> np.ndarray:
"""
Normalizes the data based on the variance
Args:
signals: (U x T) data streams
Returns:
Normalized (U x T) data streams
"""
signals = signals - np.min(signals, axis=1).reshape(signals.shape[0], 1)
return signals / (3 * np.std(s... | 412d3213e5d84d227f949f3d04fd7c9915784c6c | 63,085 |
def muscovite():
"""
Elastic constants of muscovite mineral (GPa) from
Vaughan and Guggenheim (1986), in Voigt notation
- Abbreviation: ``'ms'``
Returns:
(tuple): tuple containing:
* C (np.ndarray): Elastic stiffness matrix (shape ``(6, 6)``)
* rho (float): Density ... | c16439359688042114460e6fb70b64c4fc740f1b | 63,086 |
def fftshift(x, axes=None):
"""
Shift the zero-frequency component to the center of the spectrum.
This function swaps half-spaces for all axes listed (defaults to all).
Note that ``y[0]`` is the Nyquist component only if ``len(x)`` is even.
Parameters
----------
x : array_like, Tensor
... | 1fc2d602ef282ed9897967904a37098b018049e1 | 63,087 |
import hmac
import base64
import hashlib
def gen_signature(url: str, signed_nonce: str, nonce: str, data: str) -> str:
"""Request signature based on url, signed_nonce, nonce and data."""
sign = '&'.join([url, signed_nonce, nonce, 'data=' + data])
signature = hmac.new(key=base64.b64decode(signed_nonce),
... | e5ae94aa83711bec555eb4adec5b8d9e4985c3bc | 63,088 |
def get_comment_url_xml(content_object, parent=None):
"""
Wraps ``get_comment_url_ajax`` with ``ajax_type='xml'``
"""
try:
return get_comment_url_ajax(content_object, parent, ajax_type="xml")
except template.TemplateSyntaxError:
raise template.TemplateSyntaxError, "get_comment_url_xm... | 2810edb8f2f94c4acad2b8d5da901ea34f81762f | 63,089 |
def create_connection_from_config():
""" Returns Google API client for Compute. It detects credentials for Service accounts and User accounts.
"""
credentials = ServiceAccountCredentials.get_application_default()
return googleapiclient.discovery.build(
'compute', 'v1', credentials=credentials) | 90228f9214952db05e7bfb09826fd7bb56b14f12 | 63,090 |
def getrevstofix(ui, repo, opts):
"""Returns the set of revision numbers that should be fixed"""
if opts[b'all']:
revs = repo.revs(b'(not public() and not obsolete()) or wdir()')
elif opts[b'source']:
source_revs = scmutil.revrange(repo, opts[b'source'])
revs = set(repo.revs(b'(%ld::... | 5cad3f34b2665eb12f01cce824589ad33af1963e | 63,091 |
def mpin_server_1(mpin_id, date):
"""Calculate HID and HTOD."""
HID = mpin.ffi.new("octet*")
HIDval = mpin.ffi.new("char []", mpin.G1)
HID[0].val = HIDval
HID[0].max = mpin.G1
HID[0].len = mpin.G1
# H(T|H(ID))
HTID = mpin.ffi.new("octet*")
HTIDval = mpin.ffi.new("char []", mpin.G1)
... | a7be876896683f397bf1e002cdb06a2adbcf99d9 | 63,092 |
def plot_curve_metric(x, y, auc, curve_type, title=None, labels=None):
"""
Plot ROC or PRC curves per output channel.
Args:
- x (dict) - Dict of numpy arrays for values to plot on x axis.
- y (dict) - Dict of numpy arrays for values to plot on x axis.
- auc (dict) - Dict of numpy arrays for... | 587cfe2d7298e0e726fd02078a8ec1416e2f82e3 | 63,093 |
def get_coordinate_dimensions(geometry):
"""Returns the dimensionality of the coordinates in a geometry (2 or 3).
Returns -1 for not-a-geometry values.
Parameters
----------
geometry : Geometry or array_like
Examples
--------
>>> get_coordinate_dimensions(Geometry("POINT (0 0)"))
... | 12daf75dd668f57c332349ba7b19d15e0f6c4f95 | 63,094 |
def task_name(task):
"""
Compute the task name for an Eliot task.
If we can't find a ``message_type`` or an ``action_type`` field to use to
derive the name, then return ``None``.
"""
if task is None:
raise ValueError('Cannot compute task name', task)
level = u','.join(map(unicode, t... | 9183e91dd898ae71c66a7d2c3bd44d8c7ef5f775 | 63,095 |
def getTestSuite(select="unit"):
"""
Get test suite
select is one of the following:
"unit" return suite of unit tests only
"component" return suite of unit and component tests
"all" return suite of unit, component and integration tests
"pending" ... | 5bf4561d16a50965fc32fe19df71e7072f24e551 | 63,096 |
def get_backend(project_type = None,
project = None,
logger = None):
"""
project_type is a string, like 'svn'
project is a Project
"""
if project_type is None:
project_type = project.project_type
pass
klass = backend_registry.get(proj... | 18a2c2f5843616a50523706fff1f6e57a0d844ac | 63,097 |
def create_entity(entity_name):
"""Add an entry to an array-type entity
.. :quickref: Model; Add an entry to an array-type entity
:param entity_name: Name of the entity
"""
model = read_model()
new_entity = request.get_json()
key_field = get_key_field(new_entity)
entities = model['inp... | 56695fd0996f5a2c8ea09d7b52376211bbabff0e | 63,098 |
def abbreviate(s):
"""
Given a sentence replace middle of long words with a char count of the omitted
:param s: String
:return: String
"""
r = s
for word in split_words(s):
r = r.replace(word, abbreviate_word(word))
return r | 3e0c94d4cf593dbc717a5140f45eb9f3b4e6ebf6 | 63,100 |
import json
def block_hash(PARAMETER=None):
"""
Returns the block hash at a specific height.
[PARAMETER] is optional, should be a block hash or height.
[DEFAULT] equals to last block.
"""
if not PARAMETER:
d = urllib2.urlopen(blockexplorer('block'))
return json.loads(d.read())
else:
d = urllib2.urlopen(... | 271922dec0a1f62fc0dc705f5e047b8d2a7ba211 | 63,101 |
def get_mate_unmate_factor(n_cycles: float) -> float:
"""Retrieve the mating/unmating factor (piK).
:param n_cycles: the average number of mate/unmate cycles expected
per hour of operation.
:return: _pi_k; the mate_unmate_factor.
:rtype: float
"""
if n_cycles <= 0.05:
return PI_... | e5229dd3a89846e633837d1bfe8c100e6c1a1322 | 63,102 |
import io
def xml_marshal_bucket_constraint(region):
"""
Marshal's bucket constraint based on *region*.
:param region: Region name of a given bucket.
:return: Marshalled XML data.
"""
root = s3_xml.Element('CreateBucketConfiguration', {'xmlns': _S3_NAMESPACE})
location_constraint = s3_xml... | 3fead9ea92ed8062ae43390e5aa25b2295b3aec6 | 63,104 |
def create_user( email, **fields ):
"""
Create a user:
* must be given user_cert_bin as a keyword, which must be an ms_user_cert
* the cert must be signed by the admin it identifies
* the user must not exist
* an existing admin must have signed the user cert
* said admin has to have been the one t... | 9766d053e0c5fe885a0253476a3a19e641f24b31 | 63,105 |
def drop_field(expr, field, *fields):
"""Drop a field or fields from a tabular expression.
Parameters
----------
expr : Expr
A tabular expression to drop columns from.
*fields
The names of the fields to drop.
Returns
-------
dropped : Expr
The new tabular expressi... | 3007a46d3a0a44f47e10ead1eb0ab3a0ff5be44c | 63,106 |
def async_get_pickup_type_names(
entry: ConfigEntry, pickup_types: list[PickupType]
) -> list[str]:
"""Return proper pickup type names from their associated objects."""
return [
t.friendly_name
if entry.options.get(CONF_FRIENDLY_NAME) and t.friendly_name
else t.name
for t in ... | 94f804dd3507612a1632bd300ebb3deada0109ff | 63,107 |
from typing import Sequence
from typing import Any
def parse_beta(elems: Sequence[Any]) -> dist.Beta:
""" Parse a list definition as a beta distribution.
Examples:
>>> u = parse_beta([2.31, 0.627])
>>> u.a
FloatConst(2.31)
>>> u.b
FloatConst(0.627)
>>> parse_beta(["one", 2])
Tr... | 81fb83d0d52db9aaa29780b57207979069b32926 | 63,108 |
def BRepApprox_SurfaceTool_Value(*args):
"""
:param S:
:type S: BRepAdaptor_Surface &
:param u:
:type u: float
:param v:
:type v: float
:rtype: gp_Pnt
"""
return _BRepApprox.BRepApprox_SurfaceTool_Value(*args) | 0a965be94ff7b789a7dc0c35f1debb95bae92b02 | 63,109 |
from typing import Counter
def calc_mode(nums):
"""Calculate the number of number list."""
c = Counter(nums)
nums_freq = c.most_common()
max_count = nums_freq[0][1]
modes = []
for num in nums_freq:
if num[1] == max_count:
modes.append(num[0])
return modes | dc35c0b792473f00f5e3eb841409959a0bf4ed18 | 63,111 |
def get_random_abstract(random_button_n_clicks):
"""
Get a random abstract for the random button.
Args:
random_button_n_clicks (int): The number of clicks of the random button.
Returns:
(str): The text of a random abstract.
"""
return el.get_random_abstract(random_button_n_clic... | 04cbd05c690bf61630606cc43392c45e93b7503d | 63,112 |
def wikilink_simple_url_formatter(text):
"""
A wikilink function that uses the simple URL formatter.
:param str text: the text to format.
"""
return wikilink(text, simple_url_formatter) | c9a0f1b8f1920bca14ac26170b7084b5849c1b90 | 63,113 |
def getProperties(Id,propertyName):
"""
Get the properties for the associated group/contract combination
"""
property_parameters = { "contractId":Id['contract'], "groupId":Id['group'] }
property_result = getResult('/papi/v0/properties', property_parameters)
property_items = property_result['properties']['items']
... | c538ac876c88da02c0f4bdc8fa61d8e884f3a85c | 63,114 |
def chains_tot_proxy1_rule(M, w, t, k, i, j):
"""
Coordinate shift and tour type day shift variables.
:param M: Model
:param w: week
:param t: tour type
:param k: shift length
:param i: window
:param j: day
:return: Constraint rule
"""
return M.Shift[i, j, w, k, t] == M.Tou... | ab80506304e2fc9a5b48ebde9a155e4a0028c830 | 63,116 |
def __pickle_method__(m):
"""
Pickling override for using pickle with instance methods.
"""
if m.im_self is None:
return getattr, (m.im_class, m.im_func.func_name)
else:
return getattr, (m.im_self, m.im_func.func_name) | 89e8da97d0c0c8efaef05a4531903ed43c66f62a | 63,117 |
def keepCanvas() :
"""Keep the current canvas
>>> with keepCanvas() :
... do something here
"""
return KeepCanvas() | 702c719d9c25ba8df3cbb5747b76070076630b57 | 63,118 |
def conv_temperature_unit(value, unit):
"""
"""
if type(value) is str and value.upper() in ["C", "F"]:
raise TypeError("the type of paramter unit must be string.")
if unit.upper() == "C":
pass
elif unit.upper() == "F":
value = value * 1.8 + 32
else:
raise ValueError("not supported temperatu... | af81cc1da519c76fab7679cec3e6f81dbb7e4beb | 63,119 |
def colorize_label_map(label):
"""Colorizes a label map.
Args:
label: A 2D array with integer type, storing the segmentation label.
Returns:
result: A 2D array with floating type. The element of the array
is the color indexed by the corresponding element in the input label
to the color map.
... | 420addaaf514c65532acbcb1e2b54eecfaa4b881 | 63,120 |
def get_table1(data_cwhsa, data_cwhsb):
"""
Create Table 1 of the paper.
Parameters
----------
data_cwhsa : pd.DataFrame
CWHS data until 1978.
data_cwhsb : pd.DataFrame
CWHS data from 1978 on.
Returns
-------
table_1 : dictionairy
The dict holds the keys "wh... | bd3556a5736486e81e08a677b6a0d05d4e653b7f | 63,122 |
import torch
def collate_fn_lm(samples):
""" Creates a batch out of samples """
x = torch.LongTensor(samples)
return x[:, :-1], x[:, 1:].contiguous(), None | fbaa043dca5898f2df5a9f7367b654c1eedd6c0f | 63,123 |
def AdvRebaseStream(filehandle):
"""Class for iteration over entries in a Rebase bairoch format file"""
return EntryStream(filehandle, 'TY', 'ER') | 6b487c23c05c2af62002d707f57e5b627934f45c | 63,124 |
def deletions_number(s):
"""
:type s: str
:rtype: int
"""
char_list = list(s)
c, del_count = char_list[0], 0
for next_c in char_list[1:]:
if next_c == c:
del_count += 1
else:
c = next_c
return del_count | b63b304510e58ad2191829138c5050e0e661adc5 | 63,126 |
def get_omero_dataset_id(conn, openbis_project_id, openbis_sample_id):
"""
Prints all IDs of the data objects(Projects, Datasets, Images) associated with the logged in user on the OMERO server
Args:
conn: Established Connection to the OMERO Server via a BlitzGateway
... | ce96afe5c7a6825b2c1b258b9335e0edb145e491 | 63,127 |
import glob
import torch
def model_pos_preparation(args, device):
# def model_pos_preparation(args, device):
"""
return a posenet Model: with Bx16x2 --> posenet --> Bx16x3
"""
# Create model
num_joints = 16
# num_joints = 16
print('create model: {}'.format(args.posenet_name))
if args.... | 73b0e4f94d5c37bec7765178db51a68df21a34e7 | 63,128 |
from typing import Any
from typing import Type
def get_object_type_as_json_exportable(object: Any) -> Type:
"""Get object type to be json exportable.
It appends to_json method to an object type dynamically.
"""
object_type = object if isinstance(object, type) else type(object)
if not getattr(obje... | 41af74797b19fa76cef58ebbfa00487e359b6e69 | 63,129 |
def _construct_tensor_list(types, shapes, batch_expand_num=1):
"""
Construct list of tensors with types and shapes, used to initialize the network.
Args:
types: List or Tuple. The output types of element in dataset.
shapes: List or Tuple. The output shapes of element in dataset.
bat... | d37d8e2aa188e223aa4c90526f2e8c28a7f0c21d | 63,130 |
def _process_exp(data_dir, exp_accession, metadata, assembly, criteria):
"""Process one experiment from the metadata table.
Parameters
----------
data_dir : str
path to the directory with bedfiles
exp_accession : str
ENCODE Experiment Accession ID from the metadata table
metadat... | 6b0bcae187f217cfdbda30cc18fe73fc8a2b3eed | 63,131 |
def rem_member_from_db(member_id):
"""Remove member from database.
Used for removing members from database in certain cases
(Ignoring in shipping and etc.)
**Noteworthy:** This makes sense until the bot reboots. In future there are plans
for adding ignore list for shipping and other commands
... | c6757ce28fd9a87af5d18b5b64ba5bc5119ee379 | 63,132 |
from typing import List
def all_grams_from_tokens(tokens: List[Token]) -> List[NGram]:
"""make all the 1, 2, 3, and skip-3 grams from some tokens"""
return (ngrams(1, tokens) +
ngrams(2, tokens) +
ngrams(3, tokens) +
ngrams(3, tokens, skip=True)) | dfaf9abe27c8d2a5773c239a3b018061d065958b | 63,133 |
def linear_interpolation_spherical(y_initial, y_final, n, pins=None):
"""
This function returns a (n, len(y_initial)) array, where every row is
an interpolation of the coordinates in y_initial to y_final. The
interpolation is made in spherical coordinates
ARGUMENTS:
y_initial, y_final ::... | 75dbf5804397d388d0f561e8df95c6b7cfad3435 | 63,134 |
def calc_depreciation(scenario, lights, avg_photoperiod, years):
"""Calculate Depreciation Function to Compute Total Farm Depreciation each Year
Typically accounts for 21 production costs
Args:
scenario (object): The farm scenario
lights (object): The lights used on the farm
avg_ph... | ee4d8c4c5612d6cd95bdd2da257351c994984405 | 63,135 |
def diff_dictionaries(old_dict, new_dict):
"""Calculate the diff two single dimension dictionaries.
Args:
old_dict(Dict[Any, Any]): Old dictionary.
new_dict(Dict[Any, Any]): New dictionary.
Returns:
Tuple[int, List[:class:`DictValue`]]: Number of changed records and
the :cl... | e7d9156bf82bdf27f2692417c3a054b31726aa21 | 63,137 |
def is_anagram(word1, word2):
"""Checks whether two words are anagrams
word1: string or list
word2: string or list
returns: boolean
"""
return sorted(word1) == sorted(word2) | 7a7184f3e9cbe5d1232f0c2750eebde2b9679dc7 | 63,138 |
from typing import Optional
def sql(code: str, *, class_: Optional[str] = None, **kwargs: PropertyValue) -> pre:
"""
Highlighter method for SQL code.
Keyword arguments not listed in the arguments section are turned into element
attributes on the created `pre` element.
Arguments:
code: Th... | 27c79def1dde2aa170719d48b380a8f2518f9518 | 63,140 |
def aggregate_mean_std_matrix(mu, sigma, n):
"""Given a matrix of mu, sigma, n
return the aggregated array mu, sigma, n (remove the first matrix axis)
"""
mu = np.array(mu)
sigma = np.array(sigma)
n = np.array(n)
nrow, ncol = mu.shape
mu_agg_all = []
sigma_agg_all = []
n_... | 810e189d1e93054d011a9cb2af763c6cb10ffa15 | 63,141 |
import six
from six import StringIO
def config_from_str(input_str):
"""Return a ConfigObj from a string. Values will be in Unicode."""
# This is a bit of a hack. We want to return a ConfigObj with unicode values. Under Python 2,
# ConfigObj v5 requires a unicode input string, but earlier versions require ... | 52c82e6ff42fc910695afd249f3d5f618ffc2882 | 63,142 |
def PyTuple_GetSlice(space, w_obj, low, high):
"""Take a slice of the tuple pointed to by p from low to high and return it
as a new tuple.
"""
return space.getslice(w_obj, space.newint(low), space.newint(high)) | d42ffc16a55deaa858648f2c23b7be14694402ce | 63,143 |
def build_url_dict(sports=SPORTS):
"""
returns dictionary of {
sport (str) : url (str)
}
"""
urls = {}
for sport in sports:
urls[sport] = [BOV_URL + sport + suffix for suffix in SUFFIXES]
return urls | 792301e9d556257a457c30310497b51cf856f351 | 63,144 |
def check_index_in_list(name_list, index):
"""
Returns whether or not given index exists in a list of names
For example:
name_list: ['a', 'b']
0 exists, 'a', so we return True
1 exists, 'b', so we return True
-1 exists, 'b', so we return True
2 does not exists, we ... | efedd7511377e29cc28ea4212271a4b6b59cb3b2 | 63,145 |
def electron_distribution_width_old(gamma, **params):
"""
Calculate the energy-dependent width of the electron distribution
Parameters
----------
gamma: array-like
gamma values
params: dict
dict with parameters
Returns
-------
Width of electron distribution as a fu... | e9892a7151e5333c0b0dae589d68fe45983f1e10 | 63,146 |
def pade6(vec, h):
"""
6th Order compact finite difference scheme (non-periodic BC).
Lele, S. K. - Compact finite difference schemes with spectral-like
resolution. Journal of Computational Physics 103 (1992) 16-42
"""
n = len(vec)
rhs = np.zeros(n)
a = 14.0 / 18.0
b = 1.0 / 36.0
... | 0eed51b808370e453598019965da8596fda887dd | 63,147 |
def tile_pil_image(
image: Image.Image, tile_factor: int = 0, shade: bool = True
) -> Image.Image:
"""
Tile PIL Image.
:param image: PIL Image object
:param tile_factor: number of tiles, if tile_factor=0, this
function returns a copy of the input image
:param shade: make non-central til... | 936ea55aaf70a66d74c79e1d55189aa47cb0a707 | 63,148 |
def get_cell_area_ha(raster_file):
"""Get grid cell area (ha) of raster file, without loading it into memory"""
units = get_prj_units(raster_file)
if units == 'm':
x_res, y_res = get_xy_res(raster_file)
area_ha = x_res * y_res * 1e-4
return area_ha
else:
print('Error: CRS units are {} (must be meters).'.for... | 214fafa7f211c6b0a9eb8600c8e407d3e56d8bda | 63,149 |
def _normalize_sexpr(text):
""" Normalize s-expr by making sure each toplevel expr is on a new line,
and sub-expressions are always indented. Starts of block comments are
also alwats indented. As a result, the text can now be split on "\n(" to
get all expressions.
"""
# You probably dont wa... | 4e3b35f5021ad7cdb857ac8516876b88bf7281c3 | 63,150 |
from typing import Dict
def parse_teams(elem, known_teams: Dict[str, Team]) -> Dict[str, Team]:
"""Returns the teams involved in the match"""
cell = elem.select('tr')[1:2][0]
away_name: str = cell.contents[1].select('font')[0].contents[0].contents[0].strip()
try:
away: Team = known_teams[away_... | f17f7b1aa9e57e1600a73a95972c346013fc9df7 | 63,152 |
def delconj(lam, ur, ur_inv, dups):
"""
Delete one eigenvalue/eigenvector from of each pair of complex
conjugates.
Parameters
----------
lam : 1d ndarray
The vector of complex eigenvalues
ur : 2d ndarray
Normalized complex right eigenvectors
ur_inv : 2d ndarray
I... | 7adc71774a30a640c2baddd64f726ab4b3456e48 | 63,153 |
import random
import json
def generate_random_password(field, **kwargs):
"""
Generate a random string password or a random encryption method.
Args:
field: The field object.
Keyword Arguments:
only_required: The argument to generate only required fields.
fulldate: A boolen to d... | 16424ed90753508bdc2824d49b859c098756e3d3 | 63,154 |
def put_something():
"""
Put something
---
responses:
200:
description: Success
"""
return "I put something", 200 | e5464c86acc852d68c8a78bde3558b0673656636 | 63,155 |
from typing import Optional
from typing import Sequence
def cell_co_occurrence(
data: AnnData,
groupby: Optional[Array] = None,
agg: str = "sum",
selected_types: Optional[Sequence] = None,
use: str = "dot", # dot, heatmap
key: Optional[str] = None,
**kwargs,
):
"""Visualization for ce... | 37a999fde747ea39c472bfd03f5026b1c97d959c | 63,156 |
def is_link_array(value):
"""Checks if value is an array of links.
:param value: any object.
:return: Boolean
:rtype: bool
Usage:
>>> is_link_array('foo')
False
>>> is_link_array([1, 2, 3])
False
>>> is_link([{'sys': {'type': 'Link', 'id': 'foobar'}}])
... | 00140bd454c0c10578664da7ae3ba507386a4fe7 | 63,157 |
def robust_topological_sort(graph):
"""
First identify strongly connected components,
then perform a topological sort on these components.
@param graph graph to be ordered
"""
components = strongly_connected_components(graph)
node_component = { }
for component in components:
f... | 64791a530f70d31dbb2df878aa4d2f8d7652a098 | 63,158 |
import shlex
def execute(cmd, args):
"""
Just a simple wrapper for executing commands. args is expected to be a
sequence or a basestring, a basestring will be executed with shell=True.
"""
if isinstance(args, basestring):
args = smart_str(args)
args = shlex.split(args)
else:
... | 8cf7e54c88c41ce6e7a27dfe3465078e79070d5e | 63,160 |
def sql_get_columns_for_table(table_schema: str, table_name: str) -> list:
"""Generate an SQL command that returns the list of column of a specific
table. Compatible with MySQL/ MariaDB/ Postgres and Snowflake
table_schema and table_name can be lowercase and uppercase strings.
It's using the IN clause ... | 8c5fb78a6a1ff242b333d750cb659b67eb15c52d | 63,161 |
from typing import Tuple
from typing import List
def override_module_args(args: Namespace) -> Tuple[List[str], List[str]]:
"""use the field in args to overrides those in cfg"""
overrides = []
deletes = []
if args is not None:
assert (
hasattr(args, "task")
and hasattr(... | 9501338b4649cf020f4b99f70649e92bbb31fc1f | 63,163 |
import enum
def pascal_case(value):
"""Convert strings or enums to PascalCase"""
if isinstance(value, enum.Enum):
value = value.name
return value.title().replace('_', '') | 6e994650755968a3f73b345e1f3e040f0f211aa9 | 63,164 |
import math
def computeSNQ(DW2,N):
""" Takes the exponent for the Debye Waller factor `DW2` = 2W, and an
integer N indicating a term in the phonon expansion and returns the
intensity of the N-phonon incoherent scattering S_N(Q)
Parameters
----------
N:integer
a term in the phonon e... | 6f48baaffb647a97f9662b44f0916443f3338003 | 63,165 |
def format_timedelta(td):
"""
Format a timedelta object with the format {hours}h {minutes}m.
"""
if td is None:
return '0h 0m'
seconds = td.total_seconds()
hours, seconds = divmod(seconds, 3600)
minutes = seconds / 60
return f'{int(hours)}h {int(minutes)}m' | e0b30250eef25db9b905e9e6d6c82a41b742112b | 63,166 |
def get_file_mode_for_reading(context_tar):
"""Get file mode for reading from tar['format'].
This should return r:*, r:gz, r:bz2 or r:xz. If user specified something
wacky in tar.Format, that's their business.
In theory r:* will auto-deduce the correct format.
"""
format = context_tar.get('for... | 05908234027070c1479e5159fc16eda267228042 | 63,167 |
def apply_broadening(ipres, x_seg, y_seg, type="gauss", sme=None):
"""
Broaden a spectrum by instrument resolution, with a given broadening type
Parameters
----------
ipres : float
instrument resolution
x_seg : array (npoints,)
x values (wavelength) of the spectrum to broaden
... | 3b3d09ef0c995efb87c75a6e79b00a1969dea57d | 63,168 |
def iterate_ranges(range_tuples, nums):
"""
Yields all points of N-dimensional regular rectangular grid.
:param range_tuples:
List of :math:`(a_i, b_i)` tuples, where :math`i` is
the number of grid dimensions.
:param nums:
List of number of points for grid's :math:`i`-th dimens... | 4d2d3affaa286f56926cdba815b1376d24effe48 | 63,169 |
def touch_files(path):
"""
This function creates all necessary files for to
be used with Arbiter or FFTB.
"""
touch = ['parse',
'edge',
'run',
'analysis',
'decision',
'fold',
'item-phenomenon',
'item-set',
... | 5a6fe27eecfeee834aa0de8977c3f1acb1558623 | 63,170 |
def GaussBeam(w0, Fin, n=0, m=0, xshift=0, yshift=0, tx=0, ty=0, doughnut=False, LG=False):
"""
Fout=GaussBeam(w0, Fin, n=0, m=0, xshift=0, yshift=0, tx=0, ty=0, doughnut=False, LG=False):
Creates a Gaussian beam in its waist.
Args::
required:
w0: size of the Gauss waist
... | 125ca4f0edc71f6badfac46fc7fd9696cf2c34dc | 63,171 |
def checkKey(key):
"""Return True if key is valid. Otherwise return False."""
keyList = list(key)
lettersList = list(LETTERS)
keyList.sort()
lettersList.sort()
if keyList != lettersList:
print('There is an error in the key or symbol set.')
return False
return True | c3a58eb2716dad8415b78123eaeee1e3a39abd7b | 63,172 |
def _to_seq_array(x):
"""
Converts a list of sequences from a generator to a DataFrame of sequences
"""
seq_series = pd.Series({s.metadata['id']: str(s) for s in x})
return seq_series.apply(lambda x: pd.Series(list(x))) | ab04c36fefd7775c9a62e0850a8b6d77e5c2fa41 | 63,173 |
def update(isamAppliance, name, uuid, aclEventsAllocation, ipsEventsAllocation, sysEventsAllocation, objType='logdb',
comment='', check_mode=False, force=False):
"""
Update a specific logdb object
"""
if force is True or (
_exists(isamAppliance, uuid) is True and _check(isamApplia... | 3d9624041c69af4cfb1872c2e76081c7bf9e243e | 63,174 |
def handle_429(e):
"""捕获abort(429)频率限制错误"""
rsp = {
'msg': 'Too Many Requests',
'err': 30
}
err_info = {
'msg': 'Too many requests',
'ip': request.remote_addr,
'url': request.url,
'method': request.method,
}
logger.api_logger.error(err_info)
re... | 3716438b2c81e78da4138a3dabea81677eec6f69 | 63,175 |
def default_smooth_aperpar_bkg(newx_lst, ypara, fitmask, group_lst, npoints):
"""Smooth *bkg* of the four 2D profile parameters (*A*, *k*, *c*, *bkg*) of
the fiber flat-fielding.
Args:
newx_lst (:class:`numpy.ndarray`): Sampling pixels of the 2D profile.
ypara (:class:`numpy.ndarray`): Arra... | 48a737d4e3f4e10f6ec88c236687902dece87736 | 63,176 |
from typing import Union
from typing import Optional
from typing import List
def format_helper(
df: Union[pd.DataFrame, Styler],
int_cols: Optional[List[str]] = None,
pct_cols: Optional[List[str]] = None,
delta_cols: Optional[List[str]] = None,
monospace: bool = True,
hide_index: bool = True,
... | 8f41410b7e735fa7c618718cefc7790a6be39cb3 | 63,177 |
def buildFeatureTableSubstitutionRecord(featureIndex, lookupListIndices):
"""Build a FeatureTableSubstitutionRecord."""
ftsr = ot.FeatureTableSubstitutionRecord()
ftsr.FeatureIndex = featureIndex
ftsr.Feature = ot.Feature()
ftsr.Feature.LookupListIndex = lookupListIndices
return ftsr | 22a64da7f9192b3117ec002bff997f4e6c3976db | 63,178 |
from typing import Union
from typing import List
from typing import Tuple
def get_go_interface_instance(background: Union[List[int], List[Tuple[int, float]]] = ()) -> \
GeneOntologyInterface:
"""
Generates a Matrix_Knowledge_DB interface for the use in the spawner. If
:return: a GO_interface obje... | 107036f160d5e9c5e885bc205a883a8eb80e44b5 | 63,179 |
import re
def StripComments(line):
"""Strips comments from a line and return None if the line is empty
or else the contents of line with leading and trailing spaces removed
and all other whitespace collapsed"""
commentIndex = line.find('//')
if commentIndex is -1:
commentIndex = len(line)
line = re.... | 06a01a01889d7f6c169acb3090eadf2c6e07d219 | 63,180 |
import itertools
def final_vowel_substitution_transducer(add_meta_arc=True):
"""Substitute final vowels (optionally)."""
t = pt.Transducer()
for l in pt.abc.ALL_SYMS:
t.add_arc(0, 0, l, l)
t.add_arc(0, 1, l, l)
max_node = 1
for s_ar, s_sw, subst_cost in pt.abc.AR_SW_FINAL_VOWELS:
prev_node = 0
... | a19e1ffc306e77788b0df7dfc4e60af2654d2727 | 63,181 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.