content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import math
import tqdm
def SurfacePlot(Fields,save_plot,as_video=False, Freq=None, W=None, L=None, h=None, Er=None):
"""Plots 3D surface plot over given theta/phi range in Fields by calculating cartesian coordinate equivalent of spherical form."""
print("Processing SurfacePlot...")
fig = plt.figure()
... | 23b0c3f8f569d480f3818ed970ea41adce51dacc | 29,800 |
def resource_method_wrapper(method):
"""
Wrap a 0-ary resource method as a generic renderer backend.
>>> @resource_method_wrapper
... def func(resource):
... print repr(resource)
>>> action = "abc"
>>> resource = "def"
>>> func(action, resource)
'd... | e07bd139586a7b80d48c246ea831b39c3183224e | 29,801 |
def rotation_matrix(axis_vector, angle, degrees = True):
"""
Return the rotation matrix corresponding to a rotation axis and angle
For more information, see:
https://en.wikipedia.org/wiki/Rotation_matrix#Rotation_matrix_from_axis_and_angle
Parameters
----------
axis_vector : 3 x 1 numpy ar... | c48711d2b4d2bb8ca5ac01ee2c51778f4a9525fd | 29,802 |
def select_int(sql, *args):
"""
执行一个sql, 返回一个数值
:param sql:
:param args:
:return:
"""
d = _select(sql, True, *args)
if d == None:
raise StandardError('Result is None')
if len(d) != 1:
raise MultiColumnsError('Expect only one column.')
return d.values()[0] | 72826727a45cfa902e710371c8bf4bc9fcd07528 | 29,803 |
import os
import json
import logging
def create_workflow_from_json(
name,
access_token,
workflow_json=None,
workflow_file=None,
parameters=None,
workflow_engine="yadage",
outputs=None,
):
"""Create a workflow from json specification.
:param name: name or UUID of the workflow to be... | a7dd6825fcb7e2b3a7ffa91cedc9ea8b1bb9d933 | 29,804 |
import logging
import torch
def compute_nas_score(any_plain_net, random_structure_str, gpu, args):
""" compute net score
:param any_plain_net: model class
:param random_structure_str (str): model string
:param gpu (int): gpu index
:param args (list): sys.argv
:return score... | 6188c88151ca501c22a85cccd65bbc01d99c721f | 29,805 |
def _dict_values_match(*args, **kwargs):
"""
Matcher that matches a dict where each of they keys match the matcher
passed in. Similar to ``MatchesStructure``, but for dictionaries rather
than python objects.
"""
matchers = dict(*args, **kwargs)
def extract_val(key):
def extract_val... | b463eb1f24117fb1c37793656632931af05f3a7c | 29,806 |
def fib_lista(n):
"""
Função que retorna uma lista contendo os números da sequência de Fibonacci
até o número n.
"""
lista = []
i, j = 0, 1
while i < n:
lista.append(i)
i, j = j, i + j
return lista | ec307ce80ae70e5fba81d2e26b140f1b86c95619 | 29,807 |
import os
import re
import time
import sys
def migrate(db_file=None, migrations_dir=None, verbose=False):
"""Run the migrations.
Read all the migrations in the migrations directory, and add them to
the migrations table if they are not already there. They are first inserted
with the status 'down'.
... | be03cea508c447050c87819b191d8ad64a425574 | 29,808 |
import os
def _get_json_file(module_path):
"""
Returns the path of the JSON file for a module, empty if doesn't exitst.
"""
json_file = '%s.json' % module_path.rsplit('.', 1)[0]
if os.path.isfile(module_path) and os.path.isfile(json_file):
return json_file
else:
return '' | 4a98fc9358d88817311fc0a09c44b8ea54529d74 | 29,809 |
def make_item_accessor(idx):
"""
Returns a property that mirrors access to the idx-th value of an object.
"""
@property
def attr(self):
return self[idx]
@attr.setter
def attr(self, value):
self[idx] = value
return attr | 7cd1248b3f9402fc9be10d277dee849dc47840c0 | 29,810 |
def calc_correlation(data, data2):
"""
Calculate the correlations between 2 DataFrames().
Parameters:
- data: The first dataframe.
- data2: The second dataframe.
Returns:
A Series() object.
"""
return (
data.corrwith(data2).
loc[lambda x: x.notnull()]
... | 7f47592a4525efa9db2fba317d095448d5288399 | 29,811 |
def boschloo_swap(c1r1: int, c2r1: int, c1r2: int, c2r2: int) -> (int, int, int, int):
"""
Four contingency tables always give the same pvalue: ['abcd', 'badc', 'cdab', 'dcba']
Compute and save only one version.
"""
if c1r1 + c1r2 > c2r1 + c2r2: # left > right
c1r1, c1r2, c2r1, c2r2 = c2r1... | 4da7cccd892dcf03412509c4df79132f8ebd5ad1 | 29,812 |
def get_unit_scale(scale60, val30=1):
"""
Returns a function to be used in the UNIT_SCALE of a descriptor that
will change the scale depending on if the 60fps flag is set or not.
"""
assert 0 not in (val30, scale60), ("60fps scale and default 30fps " +
"value m... | 36463d8e7d0cf46bce527cf9cefccdcf730b4414 | 29,813 |
def sample_ingredient(user,name = 'cinnoan'):
"""create and return a sample ingredient"""
return Ingredient.objects.create(user=user,name=name) | 3ccf096e68ed25dc4c35cf2abf68e9139c34b82c | 29,814 |
import six
def before(action):
"""Decorator to execute the given action function *before* the responder.
Args:
action: A function with a similar signature to a resource responder
method, taking (req, resp, params), where params includes values for
URI template field names, if any. Hoo... | d385f6b9ab45546cd2c07612528ad487ae5363d9 | 29,815 |
def commandLine(Argv):
"""
Method converting a list of arguments/parameter in a command line format (to include in the execution of a program for exemple).
list --> str
"""
assert type(Argv) is list, "The argument of this method are the arguments to convert in the command line format. (type Lis... | 4b27e73fd43ec914f75c22f2482271aafd0848ac | 29,816 |
import sys
def select_diff_from_dic(dic, spacegroup_tuples, sample_key='Mat', drop_nan=None):
""" Get data frame of selected spacegroup_tuples from dictionary of dictionaries.
Creating a pandas data frame with columns of samples and selected space group tuples (energy differnces).
Parameters:
... | 909acfe66b50202a7853c81a52f41891df5bf616 | 29,817 |
def prob(n: int, p: float) -> float:
"""
Parameters:
- n (int): số lần thực hiện phép thử
- p (float): xác suất phép thử thành công
Returns:
- float: xác suất hình học
"""
pr = p * (1 - p) ** (n - 1)
return pr | fca3fab45ec852c8910619889ac19b0753f5b498 | 29,818 |
from typing import Mapping
import pandas
import numpy
def to_overall_gpu_process_df(gpu_stats: Mapping) -> DataFrame:
""" """
resulta = []
columns = []
for k2, v2 in gpu_stats.items():
device_info = v2["devices"]
for device_i in device_info:
processes = device_i["processes"... | 7fd260b1a0d232f42958d3c073300ad6e7098c2c | 29,819 |
from teospy import liq5_f03
def genliq5():
"""Generate liq5_f03 Testers.
"""
funs = liq5_f03.liq_g
args1 = (300.,1e5)
fargs = [(der+args1) for der in _DERS2]
refs = [-5265.05056073,-393.062597709,0.100345554745e-2,-13.9354762020,
0.275754520492e-6,-0.452067557155e-12]
fnames = 'liq... | 4051aaa831bcfb74a5e871e1619b982ad06cc859 | 29,820 |
import os
import logging
def retrieve_image(image_dir, message):
"""Actually change the content of message from video bytes to image bytes"""
message_id = get_message_id(message.timestamp, message.topic)
message_path = os.path.join(image_dir, message_id)
if not os.path.exists(message_path):
lo... | b258f7412172bf5a567bdb6142bd0bb711327e4a | 29,821 |
def tridiagonalize_by_lanczos(P, m, k):
"""
Tridiagonalize matrix by lanczos method
Parameters
----------
P : numpy array
Target matrix
q : numpy array
Initial vector
k : int
Size of the tridiagonal matrix
Returns
-------
T : numpy array
tridiagon... | 0becf3801e7e486fd0a59fac95223e4d9ca68957 | 29,822 |
def Polygon(xpoints, ypoints, name="", visible=True, strfmt="{:.5f}"):
"""
Polygon defined by point verticies.
Returns
---------
:class:`lxml.etree.Element`
"""
polygon = Element("Polygon", name=str(name), visible=str(visible).lower())
polygon.extend(
[
Element("Poin... | f2cd966a0dd536b8134ccaab4a85607e8511c60c | 29,823 |
def fake_index_by_name(name, pattern, timezone='+08:00'):
"""
generate a fake index name for index template matching
ATTENTION:
- rollover postfix is not supported in index template pattern
- timezone is not supported cause tz is not well supported in python 2.x
"""
if patter... | b8754ce0086409c75edba8d6bc14b7ca313d56ae | 29,824 |
def map_code(func):
"""
Map v to an Ontology code
"""
def mapper(v):
if v is None:
return v
else:
return func(str(v))
return mapper | 76eb3c6756c983fd73c180b57c1c998a348d32eb | 29,825 |
def install_dvwa(instance, verbose: bool=True):
""" Install and configure DVWA web server
instance (object): This argmument define the lxc instance.
verbose (bool, optional): This argument define if the function prompt some informations during his execution. Default to True.
"""
if update(instance,... | 299bddddc06364abfe34c482fa12932f893a224c | 29,826 |
import json
def card_update(handler, delete=False, review=False):
"""Update or Delete an exisiting Card."""
user_data = get_current_user(handler)
if not user_data:
return
path = handler.request.path
route_root = '/api/card/'
err_response = '{}'
if not path.startswith(route_root) ... | d21ea5d80112459ad75374559bd061d38a12a697 | 29,827 |
def get(role_arn, principal_arn, assertion, duration):
"""Use the assertion to get an AWS STS token using Assume Role with SAML"""
# We must use a session with a govcloud region for govcloud accounts
if role_arn.split(':')[1] == 'aws-us-gov':
session = boto3.session.Session(region_name='us-gov-west-... | f1012c71eff41bffdad6390b9353745b0e07ab0c | 29,828 |
import time
def put_keyless():
"""
Handle PUT requests for key-less database insertions
"""
# Check if the PUT request actually carries any data in its body to avoid
# storing empty blocks under a key.
start = time.clock()
data = request.body.getvalue()
if not data:
return abor... | 2270eee778603966536d9fe4c395aaef00b4cd83 | 29,829 |
def find_nth(s, x, n):
"""
find the nth occurence in a string
takes string where to search, substring, nth-occurence
"""
i = -1
for _ in range(n):
i = s.find(x, i + len(x))
if i == -1:
break
return i | b54998db817272ec534e022a9f04ec8d350b08fb | 29,830 |
from typing import Union
from typing import Dict
from typing import Any
def parse_buffer(value: Union[Dict[str, Any], str]) -> str:
"""Parse value from a buffer data type."""
if isinstance(value, dict):
return parse_buffer_from_dict(value)
if is_json_string(value):
return parse_buffer_fro... | e98cad3020fffdaef5ad71d1f59b89db83e05d03 | 29,831 |
def cancel_job(request): # pylint: disable=unused-argument
"""Handler for `cancel_job/` request."""
if not job_ids:
print('No jobs are running, nothing to cancel!')
else:
job_id = job_ids.popleft()
print('CANCELING JOB:', job_id)
long_job.cancel(job_id)
return django.htt... | 365b305b88329cf394f3b7d36c6cd3e02121b5a1 | 29,832 |
def LO_solver_multiprocessing(H,N,dis, args,pipe):
"""
Allows to solve the Hamiltonian using several CPUs.
Parameters
----------
H: arr
Discretized Lutchyn-Oreg Hamiltonian built with Lutchyn_builder.
N: int or arr
Number of sites. If it is an ar... | b4738ababdd47a9dc633760dbc3ee7f29744e1e3 | 29,833 |
def _clip_grad(clip_type, clip_value, grad):
"""
Clip gradients.
Inputs:
clip_type(int): The way to clip, 0 for 'value', 1 for 'norm'.
clip_value(float): Specifies how much to clip.
grad (tuple[Tensor]): Gradients.
Outputs:
tuple[Tensor], clipped gradients.
"""
... | 998003fa6ef24e917af55cdd831034cafceeed74 | 29,834 |
def lightness_correlate(A, A_w, c, z):
"""
Returns the *Lightness* correlate :math:`J`.
Parameters
----------
A : numeric or array_like
Achromatic response :math:`A` for the stimulus.
A_w : numeric or array_like
Achromatic response :math:`A_w` for the whitepoint.
c : numeric... | 2692225728d9621ac427cedafcb18c9fe014d4ac | 29,835 |
import requests
def get(url, body=None, cookies=None, auth_data=None):
""" This function sends REST API GET request and prints some
useful information for debugging.
"""
result = requests.get(url, cookies=cookies, params=body, auth=auth_data)
print('GET request to {0}'.format(url))
prin... | 5095857dfa68c08b135abccab7357cc2662a6588 | 29,836 |
def fetch_file_from_guest(module, content, vm, username, password, src, dest):
""" Use VMWare's filemanager api to fetch a file over http """
result = {'failed': False}
tools_status = vm.guest.toolsStatus
if tools_status == 'toolsNotInstalled' or tools_status == 'toolsNotRunning':
result['fail... | 6906573831b9889f82a7015c3a6ba9e82ca1cdea | 29,837 |
def method_wrapper(m):
"""Generates a method from a `GrpcMethod` definition."""
if m.is_simple:
def simple_method(self):
"""TODO: no docstring!"""
return apply_transform(
self.__service__, m.output_transform,
grpc_call(self.__service__, m, unwrap(... | 28fbb9a112e5dcb61be7af9878eb2732b6adf2a6 | 29,838 |
def ReadFile(filename):
"""
description: Read program from file
param {*} filename
return {*} file
"""
input_file = open(filename, "r")
result = []
while True:
line = input_file.readline()
if not line:
break
result.append(line)
for line_index in ra... | fd7d7faab401f335579719f6e015bf7b9d82c2e2 | 29,839 |
def item_url(item):
"""Return a Markdown URL for the WCAG item."""
fragment = item["id"].split(":")[1]
return url(item["handle"], f"https://www.w3.org/TR/WCAG21/#{fragment}") | d670da65ef794116ae5ccd650f3618e7c6a5dc45 | 29,840 |
def gen_nested_prop_getter(val_name, throws, klass):
"""
generates a nested property getter, it
actually returns an _Internal object
"""
def _internal(self):
try:
getattr(self, val_name)
except AttributeError:
setattr(self, val_name, klass())
... | 54f766ae1dfcbc0e491355a4c741ccbadff6d26f | 29,841 |
import numpy
import scipy
def quad_genz_keister(order, dist, rule=24):
"""
Genz-Keister quadrature rule.
Examples:
>>> abscissas, weights = quad_genz_keister(
... order=1, dist=chaospy.Iid(chaospy.Uniform(0, 1), 2))
>>> abscissas.round(2)
array([[0.04, 0.04, 0.04, ... | f4d4590f2910ea82e5e824a47be196f82bdd5da3 | 29,842 |
def get_maf(variant):
"""
Gets the MAF (minor allele frequency) tag from the info field for the
variant.
Args:
variant (cyvcf2.Variant)
Returns:
maf (float): Minor allele frequency
"""
return variant.INFO.get("MAF") | 1d25f577a3cec14b8d05095d320fad6584484718 | 29,843 |
import glob
def check_channels(file_path_address: str, image_type: str):
"""Manual verifier to determine which images to further clean or remove.
This checks to see if there is a consistent third dimension in each of the images.
Paramters:
---------
file_path_address: str
Address of where... | 6d7307dbc103fd74a21e6fbb5193c4aaebc1fd35 | 29,844 |
import heapq
def break_large_contigs(contigs, break_t, verbose=False):
"""Break large contigs in half until all contigs are under
the size threshold."""
# initialize a heapq of contigs and lengths
contig_heapq = []
for ctg in contigs:
ctg_len = ctg.end - ctg.start
heapq.heappush(contig_heapq, (-... | 82b039abd675303def8360acf9814426af50e503 | 29,845 |
def create_content(address, owner, content):
"""
Create a new page with some content.
Args:
address (str): the new page's absolute address.
owner (Account): the owner of the page to be created.
content (str): the Markdown content of the first revision.
Returns:
page (Pa... | 229df67cc230d39d7b6d0a129ee91d9a2f0246dd | 29,846 |
def update_op_dims_mapping_by_default_dist_impl(op_dist_attr):
"""Each operator has a default distributed operator, only allowed to be sharded in batch dimension."""
changed = False
op_desc = op_dist_attr.get_owner_op().desc
# The following statement will be replaced by a more elegent way
if op_desc... | 75f226ff4902cd935abadd60b16874929d35883c | 29,847 |
import random
import torch
def perturb_box(box, min_iou=0.5, sigma_factor=0.1):
""" Perturb the input box by adding gaussian noise to the co-ordinates
args:
box - input box
min_iou - minimum IoU overlap between input box and the perturbed box
sigma_factor - amount of perturbation, re... | 1b1e7cb831d52be0b96b69d68817c678865447d2 | 29,848 |
import statistics
def coverageCalc(coverageList,minCov):
"""Function parsing coverageList for
:param coverageList: List of pacbam coverage information
:param minCov: Int of minimum passing coverage
:return:
covCount: Int of bases with coverage
minCovC... | e20dc1e1f0b6f7e328501afe9921455a705f196a | 29,849 |
def truncate_top_k_2(x, k):
"""Keep top_k highest values elements for each row of a numpy array
Args:
x (np.Array): numpy array
k (int): number of elements to keep for each row
Returns:
np.Array: processed array
"""
s = x.shape
# ind = np.argsort(x)[:, : s[1] - k]
i... | 1e84987b01d4cbab9c97174886c87d88e541f380 | 29,850 |
import glob
import os
import collections
def run():
"""
read pipeline and do infer
"""
args = parse_args()
# input_ids file list, every file content a tensor[1,128]
file_list = glob.glob(os.path.join(os.path.realpath(args.data_dir), "10_data", "*.txt"))
cwq_lists = []
for i in range(le... | 960aef6f532ace6e77d4c5e2a553bdb5847221b8 | 29,851 |
def permute_dimensions(x, pattern):
"""Permutes axes in a tensor.
# Arguments
pattern: should be a tuple of
dimension indices, e.g. (0, 2, 1).
# Returns
A tensor.
"""
return KerasSymbol(mx.sym.transpose(x.symbol, axes=pattern)) | 3665221ec55a01dcf2eaa3f51d716d08f09eed60 | 29,852 |
import copy
def relaxStructure(s, operation):
"""
Performs a gulp relaxation (either relaxation of unit cell parameters only, or both unit cell and atomic positions.
s: structure_class
operation: string
Specifies the gulp calculation to execute.
Returns
-------
s : structure_... | ccc8a2fe75d11693030fea6771bb127e3fc9ebcd | 29,853 |
import time
def dos_gaussian_shift(energies, dos_total, projections, nGridpoints, smearing):
"""
Produces a single gaussian function then shifts the gaussian around the grid
Advantages:
+ Very fast compared to other methods
Disadvantages:
- Produces an edge effect, energy range should be larger than required
-... | ff1ea14a96c217083eba01a5cde7deb668e1267d | 29,854 |
def temp_h5_file(tmpdir_factory):
""" a fixture that fetches a temporary output dir/file for a test
file that we want to read or write (so it doesn't clutter up the test
directory when the automated tests are run)"""
return str(tmpdir_factory.mktemp('data').join('test.h5')) | 23ca5e58aa7afadcd18394bfa7ea6aa3a48c412e | 29,855 |
def get_day_name(date):
"""
returns the day name for a give date
@param date datatime
@return month name
.. faqref::
:tag: python
:title: Récupérer le nom du jour à partir d'une date
.. runpython::
:showcode:
import date... | 1e6b67d5b853156d5e6a8624c9644a08ebb4ee20 | 29,856 |
def get_samples(n_samples, data, labels=None, use_random_transpose=False):
"""Return some random samples of the training data."""
indices = np.random.choice(len(data), n_samples, False)
if np.issubdtype(data.dtype, np.bool_):
sample_data = data[indices] * 2. - 1.
else:
sample_data = data... | 7a9fc5256b438619af8e366802fc54db196536d7 | 29,857 |
from typing import Union
import torch
import collections
from typing import Callable
def apply_to_tensor(
x: Union[torch.Tensor, collections.Sequence, collections.Mapping, str, bytes], func: Callable
) -> Union[torch.Tensor, collections.Sequence, collections.Mapping, str, bytes]:
"""Apply a function on a ... | 53f966bfbd6b68efa2bfeb72b8c34e38be008196 | 29,858 |
def status():
""" Returns a page showing the number of unprocessed certficate-requests. """
result = db.session.query(Request).filter(Request.generation_date == None).count()
return render_template('status.html', requests=result) | 9e04e870a4d3d707da078e5681c145726ba563c2 | 29,859 |
def weak_connect(sender, signal, connector, attr, idle=False, after=False):
"""
Function to connect some GObject with weak callback
"""
wc = WeakCallback(connector, attr, idle)
if after:
wc.gobject_token = sender.connect_after(signal, wc)
else:
wc.gobject_token = sender.conn... | e18ba634c039cfb2d03649c76d1aad02f216c653 | 29,860 |
def load_user(id):
"""
Provides login_manager with a method to load a user
"""
return User.get_by_id(int(id)) | 3aca05c0bf6ad62401c442ba813a8a8a646dabe4 | 29,861 |
def _compute_min_dfc(fnrs, fprs, thresholds, p_target, c_miss, c_fa):
"""
Computes the minimum of the detection cost function. The comments refer to
equations in Section 3 of the NIST 2016 Speaker Recognition Evaluation Plan.
:param fnrs: the list of false negative rates
:param fprs: the list of fa... | 23931070ad23f2dc8b1fdc63d0e4635f9fede535 | 29,862 |
def parse_rsync_url(location):
"""Parse a rsync-style URL."""
if ':' in location and '@' not in location:
# SSH with no user@, zero or one leading slash.
(host, path) = location.split(':', 1)
user = None
elif ':' in location:
# SSH with user@host:foo.
user_host, path ... | fc315c1a6b376cbb83b047246fee51ae936b68ef | 29,863 |
def ThetaE(tempk, pres, e):
"""Calculate Equivalent Potential Temperature
for lowest model level (or surface)
INPUTS:
tempk: Temperature [K]
pres: Pressure [Pa]
e: Water vapour partial pressure [Pa]
OUTPUTS:
theta_e: equivalent potential temperature
Refe... | 9b1876e930d7f2ca093d6f894791045f226c3b98 | 29,864 |
import random
def generate_address_street():
"""Concatenate number, street, and street sufix."""
number = random.randint(1, 9999)
street = last_names[random.randint(0, len(last_names) - 1)]
suffix = address_street_suffix[random.randint(0, len(address_street_suffix) - 1)]
return "{0} {1} {2}".forma... | a7dafb282d1d0abb25ad6cb44ba6f2e0a9e190dd | 29,865 |
def try_all_eliza_transformations(doc):
"""
Try to do eliza transformation for all the functions and add the transformed string to the
responses list
"""
responses = []
question = ask_do_you_like_to(doc)
if question:
responses.append(question)
question = rephrase_question(doc)
... | 3a76b9a1fc422e8db1e02f41dd286ce385d09213 | 29,866 |
def get_jwt_subject():
"""Returns a the subject from a valid access tokekn"""
token = get_token_auth_header()
payload = verify_decode_jwt(token)
if "sub" not in payload:
abort(401)
return payload["sub"] | a7f8bf3989dbdc1a0894d63d6fdc58e5c07356f4 | 29,867 |
import functools
def api(function):
"""
Decorator of API functions that protects user code from
unknown exceptions raised by gRPC or internal API errors.
It will catch all exceptions and throw InternalError.
:param function: function to be decorated
:return: decorated function
"""
@f... | 1e023eed5986224967c6057962576afc4c84adb2 | 29,868 |
def mock_signal_receiver(signal, wraps=None, **kwargs):
"""
Taken from mock_django as importing mock_django created issues with Django
1.9+
Temporarily attaches a receiver to the provided ``signal`` within the scope
of the context manager.
The mocked receiver is returned as the ``as`` target o... | d3f0a481609bf9491b159a7331e1fffc3a5bf92e | 29,869 |
import urllib
def is_valid_cover(cover_metadata):
"""Fetch all sizes of cover from url and evaluate if they are valid."""
syndetics_urls = build_syndetic_cover_urls(cover_metadata)
if syndetics_urls is None:
return False
try:
for size in ["small", "medium", "large"]:
resp ... | b41aa1f558d1080fc1a3a2d03180417b38b92931 | 29,870 |
def setup_go_func(func, arg_types=None, res_type=None):
"""
Set up Go function, so it know what types it should take and return.
:param func: Specify Go function from library.
:param arg_types: List containing file types that function is taking. Default: None.
:param res_type: File type that functio... | 05f48f4dfecdf0133613f76f235b1e82f14bc5a9 | 29,871 |
import itertools
def compress_cubic(G):
"""Calculate the matricized cubic operator that operates on the compact
cubic Kronecker product.
Parameters
----------
G : (r,r**3) ndarray
The matricized cubic tensor that operates on the full cubic Kronecker
product. This should be a symme... | 2058cf169695a3fbef41e78bc521577b191e6d08 | 29,872 |
import ctypes
def xonly_pubkey_tweak_add(
xonly_pubkey: Secp256k1XonlyPubkey, tweak32: bytes
) -> Secp256k1Pubkey:
"""
Tweak an x-only public key by adding the generator multiplied with tweak32
to it.
Note that the resulting point can not in general be represented by an x-only
pubkey because ... | 727b84ec239bb19d83fa9fe4e72b08ea17972e31 | 29,873 |
from typing import Optional
def get_organisms_df(url: Optional[str] = None) -> pd.DataFrame:
"""Convert tab separated txt files to pandas Dataframe.
:param url: url from KEGG tab separated file
:return: dataframe of the file
:rtype: pandas.DataFrame
"""
df = pd.read_csv(
url or ensure... | 4b28571848076a785ae773410c70102e5a83d096 | 29,874 |
import argparse
def positive_int(val):
"""
ArgumentParse positive int check
"""
try:
ival = int(val)
assert ival > 0
return ival
except (ValueError, AssertionError):
raise argparse.ArgumentTypeError("'%s' is not a valid positive int" % val) | cf98daeeb9876bc768e9c3ad0d227ce39386e8b4 | 29,875 |
import random
def split(dataset: Dataset, count: int, shuffle=False):
"""Datasetを指定個数に分割する。"""
dataset_size = len(dataset)
sub_size = dataset_size // count
assert sub_size > 0
indices = np.arange(dataset_size)
if shuffle:
random.shuffle(indices)
return [
dataset.slice(indic... | d4f50f617fb65499190c7c5e014178d548a7dccb | 29,876 |
import pathlib
def load_fixture(filename):
"""Load a fixture."""
return (
pathlib.Path(__file__)
.parent.joinpath("fixtures", filename)
.read_text(encoding="utf8")
) | f1382161ad6226cd585a2ecbbe08dc486b3a5f2d | 29,877 |
import re
def natural_sort(l):
"""
From
http://stackoverflow.com/a/4836734
"""
def convert(text):
return int(text) if text.isdigit() else text.lower()
def alphanum_key(key):
return [convert(c) for c in re.split('([0-9]+)', key)]
return sorted(l, key=alphanum_key) | c1cd34aa4c9ea2323cb311d9af6f141aa85abef2 | 29,878 |
import inspect
def is_verifier(cls):
"""Determine if a class is a Verifier that can be instantiated"""
return inspect.isclass(cls) and issubclass(cls, Verifier) and \
not inspect.isabstract(cls) | 83cd18155f23631f2e1dac1ec1eac07a5017809d | 29,879 |
import os
def get_config():
"""Parse the aliases and configuration."""
if pyversion("3"): import configparser
else: import ConfigParser as configparser
config = configparser.ConfigParser()
rcfiles = [
"/etc/weatherrc",
"/etc/weather/weatherrc",
os.path.expanduser("~/.weathe... | dfabba5cc501a9d3998ecb9e219e4762e321fe30 | 29,880 |
import os
def get_framework_sample(project_id: str, framework: str, sample: str):
"""
Route for getting sample code for an ML framework
for optimization of the projects model
:param project_id: the project_id to get the available frameworks for
:param framework: the ML framework to get available ... | c9a2e8f868c7586de9b99bcb0eeaa4299a9ced19 | 29,881 |
def get_bleu_score(references, hypothesis):
"""
Args:
references: list(list(list(str)))
# examples: list(examples)
hypothesis: list(list(list(str)))
# hypotheses: list(list(str))
"""
hypothesis = [hyp[0][0] for hyp in hypothesis]
return 100.0 * bleu_score.corpus_ble... | a2a17186555564a02acedf5540aedce0b1a14cd1 | 29,882 |
import os
import tempfile
import re
def GetLicenseTypesFromEbuild(ebuild_path):
"""Returns a list of license types from the ebuild file.
This function does not always return the correct list, but it is
faster than using portageq for not having to access chroot. It is
intended to be used for tasks such as pre... | 99e2296edc370fd1d275b368b2d5027fab695c58 | 29,883 |
def load_json_link_index(out_dir, link):
"""check for an existing link archive in the given directory,
and load+merge it into the given link dict
"""
link = {
**parse_json_link_index(out_dir),
**link,
}
link.update({
'history': link.get('history') or {},
})
c... | 58c034daa7305e06407af9cf226ff939544ee961 | 29,884 |
def relative_phase(input_phase: float, output_phase: float) -> float:
"""
Calculates the relative phase between two phases.
:param input_phase: the input phase.
:param output_phase: the output phase.
:return: the relative phase.
"""
phi = output_phase - input_phase
if phi < -np.pi:
... | d912754fe060582e5ffe9dc3aad0286b80ee945a | 29,885 |
def get_process_state(*args):
"""
get_process_state() -> int
Return the state of the currently debugged process. \sq{Type,
Synchronous function, Notification, none (synchronous function)}
@return: one of Debugged process states
"""
return _ida_dbg.get_process_state(*args) | 338efc688fe4c3631b965ac2f2e64b5ea0fe2ebe | 29,886 |
def jaccard_similarity(x, y):
""" Returns the Jaccard Similarity Coefficient (Jarccard Index) between two
lists.
From http://en.wikipedia.org/wiki/Jaccard_index: The Jaccard
coefficient measures similarity between finite sample sets, as is defined as
the size of the intersection divided by th... | 81cf0c882ff4b06e79b102abb2d8f13755b68873 | 29,887 |
def align_address_to_size(address, align):
"""Align the address to the given size."""
return address + ((align - (address % align)) % align) | 9496c969e257fb3c00ecddf8e941ddb0bd41155e | 29,888 |
import shlex
def tokenizer_word(text_string, keep_phrases=False):
"""
Tokenizer that tokenizes a string of text on spaces and new lines (regardless of however many of each.)
:param text_string: Python string object to be tokenized.
:param keep_phrases: Booalean will not split "quoted" text
:retur... | 940f716072e9b2ce522c9854b2394327fbd1e934 | 29,889 |
def getiso():
"""Get iso level of sensor.."""
global camera
maxtint = 4
iso = float(camera.analog_gain) # get current ambient brightness 0..8
iso = (iso * maxtint) # adjust buy max tint level
iso = (256 - (maxtint * 8)) + iso # clear - max tint + ISO tint
return int(iso) | 45fa48897cd297232fde00cbe49d7717608466ed | 29,890 |
import logging
import traceback
def _get_credentials(rse, endpoint):
"""
Pass an endpoint and return its credentials.
:param endpoint: URL endpoint string.
:param rse: RSE name.
:returns: Dictionary of credentials.
"""
key = '%s_%s' % (rse, endpoint)
result... | 25ce4eee8eb0bcb84e312cc1658376b0dbeaf7c6 | 29,891 |
from typing import Union
from typing import Sequence
from typing import List
from typing import Dict
def get_manual_comparisons(db: cosem_db.MongoCosemDB,
cropno: Union[None, str, int, Sequence[Union[str, int]]] = None,
mode: str = "across_setups") -> \
Li... | fc4a62d09f9df289b08a249d70875ce6ca19ed39 | 29,892 |
def draw_circle(center_x:float, center_y:float, radius:float = 0.3, segments:int = 360, fill:bool=False):
"""
Returns an Object2D class that draws a circle
Arguments:
center_x : float : The x cord for the center of the circle.
center_y : float : The y cord for the center of the circle.
radius : flo... | 78caa0cbb25df7c947053a10d54f7ae3fd2fc8b2 | 29,893 |
def weighted_mean(values, weights):
"""Calculate the weighted mean.
:param values: Array of values
:type values: numpy.ndarray
:param weights: Array of weights
:type weights: numpy.ndarray
:rtype: float
"""
weighted_mean = (values * weights).sum() / weights.sum()
return weighted_me... | 886d7cff1555c40b448cda03e08620a0e2d69ede | 29,894 |
def shared_cluster():
"""Create a shared cluster"""
global _shared_cluster
if _shared_cluster is None:
cluster = PseudoHdfs4()
atexit.register(cluster.stop)
try:
cluster.start()
except Exception, ex:
LOG.exception("Failed to fully bring up test cluster: %s" % (ex,))
# Fix config t... | fd51186f8d46ae236b3f4220750ab0f412354669 | 29,895 |
import reprlib
def _format_args(args):
"""Format function arguments.
Special case for a single parameter: ('hello',) is formatted as ('hello').
"""
# use reprlib to limit the length of the output
args_repr = reprlib.repr(args)
if len(args) == 1 and args_repr.endswith(',)'):
args_repr ... | a54f06358b629340c1f16ecc86eff15b8fca3bd3 | 29,896 |
import requests
import logging
import json
def request(config, url_params={}):
"""Wrapper for sending GET to Facebook.
Args:
config: YAML object of config file.
url_params: Dictionary of parameters to add to GET.
Returns:
HTTP response or error.
"""
host = HOST + f"/{config['user_id']}/"
... | e4ef9315170ab7d1c7e39645bde46b6cbb9f9de9 | 29,897 |
import miniupnpc
def setup(hass, config):
"""Register a port mapping for Home Assistant via UPnP."""
upnp = miniupnpc.UPnP()
hass.data[DATA_UPNP] = upnp
upnp.discoverdelay = 200
upnp.discover()
try:
upnp.selectigd()
except Exception:
_LOGGER.exception("Error when attempti... | ca5d7d90efb849412e2256dab3516deca1531539 | 29,898 |
def load_formatted_objects_json(fp):
"""A function to load formatted object data data. The function assumes
the input json is of the form:
[
{
id: <number>,
regions :
[
{
x: <number>,
... | 2647f2c2cfc7530998361b19693ea6e187bf64f1 | 29,899 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.