content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def onRequestLogin(loginName, password, clientType, datas):
"""
KBEngine method.
账号请求登陆时回调
此处还可以对登陆进行排队,将排队信息存放于datas
"""
INFO_MSG('onRequestLogin() loginName=%s, clientType=%s' % (loginName, clientType))
errorno = KBEngine.SERVER_SUCCESS
if len(loginName) > 64:
errorno = KBEngine.SERVER_ERR_NAME
if len(... | 08c428f5ac27e009b9d1ffe1af9daee1c5cca2f1 | 26,200 |
import logging
from typing import Callable
from typing import Any
def log_calls(
logger: logging.Logger, log_result: bool = True
) -> GenericDecorator:
"""
Log calls to the decorated function.
Can also decorate classes to log calls to all its methods.
:param logger: object to log to
"""
... | 43e71d224ed45a4f92ddda5f4ac042922b254104 | 26,201 |
def bag(n, c, w, v):
"""
测试数据:
n = 6 物品的数量,
c = 10 书包能承受的重量,
w = [2, 2, 3, 1, 5, 2] 每个物品的重量,
v = [2, 3, 1, 5, 4, 3] 每个物品的价值
"""
# 置零,表示初始状态
value = [[0 for j in range(c + 1)] for i in range(n + 1)]
for i in range(1, n + 1):
for j in range(1, c + 1):
value[i][... | 27dd9c5f9367afe865686c8f68853bc966bcdaa6 | 26,202 |
def _to_bytes(key: type_utils.Key) -> bytes:
"""Convert the key to bytes."""
if isinstance(key, int):
return key.to_bytes(128, byteorder='big') # Use 128 as this match md5
elif isinstance(key, bytes):
return key
elif isinstance(key, str):
return key.encode('utf-8')
else:
... | 8df22eb02674cb61ef0e8a413f1eed7dc92f0aef | 26,203 |
def _online(machine):
""" Is machine reachable on the network? (ping)
"""
# Skip excluded hosts
if env.host in env.exclude_hosts:
print(red("Excluded"))
return False
with settings(hide('everything'), warn_only=True, skip_bad_hosts=True):
if local("ping -c 2 -W 1 %s" % machin... | 114b9b708d81c6891a2f99c5c600d9d4aa59c138 | 26,204 |
import sys
def download_subs_from_public_amara(amara, ytid, lang):
"""Returns tuple subtitles downloaded from Public Amara"""
# Check whether the video is already on Amara
video_url = 'https://www.youtube.com/watch?v=%s' % ytid
amara_response = amara.check_video(video_url)
if amara_response['meta... | 626a5c801aeb83b4169a015c503d3037f8d8bc3b | 26,205 |
import os
def profile_exists_at(path):
"""
Check that a profile exists at the given path.
:param path: path to a profile
:type path: str
:returns: True if profile exists in given path, else False
:rtype: bool
"""
return os.path.isdir(path) and os.path.isfile(
os.path.join(pat... | ee0e9a8521592d710cdb0a7135348eae99412629 | 26,206 |
def get_expectation_value(
qubit_op: QubitOperator, wavefunction: Wavefunction, reverse_operator: bool = False
) -> complex:
"""Get the expectation value of a qubit operator with respect to a wavefunction.
Args:
qubit_op: the operator
wavefunction: the wavefunction
reverse_operator: ... | e0e634bc6c0d5c9d5252e29963333fac3ccc3acd | 26,207 |
def create_proxy_to(logger, ip, port):
"""
:see: ``HostNetwork.create_proxy_to``
"""
action = CREATE_PROXY_TO(
logger=logger, target_ip=ip, target_port=port)
with action:
encoded_ip = unicode(ip).encode("ascii")
encoded_port = unicode(port).encode("ascii")
# The fir... | 006ae25e069f3ac82887e9071170b334a0c6ea74 | 26,208 |
def get_output_shape(tensor_shape, channel_axis):
"""
Returns shape vector with the number of channels in the given channel_axis location and 1 at all other locations.
Args:
tensor_shape: A shape vector of a tensor.
channel_axis: Output channel index.
Returns: A shape vector of a tensor... | 7c7058c2da9cb5a4cdb88377ece4c2509727894a | 26,209 |
import numbers
def process_padding(pad_to_length, lenTrials):
"""
Simplified padding interface, for all taper based methods
padding has to be done **before** tapering!
Parameters
----------
pad_to_length : int, None or 'nextpow2'
Either an integer indicating the absolute length of
... | b018e32c2c12a67e05e5e324f4fcd8547a9d992b | 26,210 |
from ..constants import asecperrad
def angular_to_physical_size(angsize,zord,usez=False,**kwargs):
"""
Converts an observed angular size (in arcsec or as an AngularSeparation
object) to a physical size.
:param angsize: Angular size in arcsecond.
:type angsize: float or an :class:`AngularSepa... | 80fbd5aa90807536e06157c338d86973d6050c7c | 26,211 |
import sys
from sys import stderr
import getopt
def handle_arguments():
""" verifies the presence of all necessary arguments and returns the data dir """
if len ( sys.argv ) == 1:
stderr( "no arguments provided." )
show_help()
try: # check for the right arguments
keys, values = getopt.getopt( ... | 46f7bf9c5778bdc762d8f29c33f708da9ca3b2ba | 26,212 |
def is_tuple(x):
"""
Check that argument is a tuple.
Parameters
----------
x : object
Object to check.
Returns
-------
bool
True if argument is a tuple, False otherwise.
"""
return isinstance(x, tuple) | ac129c4ab7c6a64401f61f1f03ac094b3a7dc6d4 | 26,213 |
def find_verbalizer(tagged_text: str) -> pynini.FstLike:
"""
Given tagged text, e.g. token {name: ""} token {money {fractional: ""}}, creates verbalization lattice
This is context-independent.
Args:
tagged_text: input text
Returns: verbalized lattice
"""
lattice = tagged_text @ ver... | fef98d7a2038490f926dc89fc7aefbbda52ed611 | 26,214 |
def get_color_pattern(input_word: str, solution: str) -> str:
"""
Given an input word and a solution, generates the resulting
color pattern.
"""
color_pattern = [0 for _ in range(5)]
sub_solution = list(solution)
for index, letter in enumerate(list(input_word)):
if letter == solution... | a8746a5854067e27e0aefe451c7b950dd9848f50 | 26,215 |
import inspect
def getargspec(obj):
"""Get the names and default values of a function's arguments.
A tuple of four things is returned: (args, varargs, varkw, defaults).
'args' is a list of the argument names (it may contain nested lists).
'varargs' and 'varkw' are the names of the * and ** arguments ... | bcfe75de95ccf22bcefdba52c8556f0722dbbcb7 | 26,216 |
def nearest(x, xp, fp=None):
"""
Return the *fp* value corresponding to the *xp* that is nearest to *x*.
If *fp* is missing, return the index of the nearest value.
"""
if len(xp) == 1:
if np.isscalar(x):
return fp[0] if fp is not None else 0
else:
return np.a... | 77ebcb08adbc5b1a70d801c7fe1f4b31f1b14717 | 26,217 |
def generate_warning_message(content: str):
"""
Receives the WARNING message content and colorizes it
"""
return (
colorama.Style.RESET_ALL
+ colorama.Fore.YELLOW
+ f"WARNING: {content}"
+ colorama.Style.RESET_ALL
) | bdb22e6c434db2252fe50a552d889fc5f506931f | 26,218 |
def extract_Heff_params(params, delta):
"""
Processes the VUMPS params into those specific to the
effective Hamiltonian eigensolver.
"""
keys = ["Heff_tol", "Heff_ncv", "Heff_neigs"]
Heff_params = {k: params[k] for k in keys}
if params["adaptive_Heff_tol"]:
Heff_params["Heff_tol"] ... | 0153b3f7bdca639c7aab659b60ef0a3c28339935 | 26,219 |
def illumination_correction(beam_size: sc.Variable, sample_size: sc.Variable,
theta: sc.Variable) -> sc.Variable:
"""
Compute the factor by which the intensity should be multiplied to account for the
scattering geometry, where the beam is Gaussian in shape.
:param beam_size:... | 59ec50e8e8268677b536638e7d6897be38d4ab43 | 26,220 |
def get_subscription_query_list_xml(xml_file_path):
"""
Extract the embedded windows event XML QueryList elements out of a an XML subscription setting file
"""
with open(xml_file_path, 'rb') as f_xml:
x_subscription = lxml.etree.parse(f_xml)
# XPath selection requires namespace to used!
x_subscript... | 9c76a525a691ea91804304efc5e2e0aeab7d87ac | 26,221 |
async def create_state_store() -> StateStore:
"""Create a ready-to-use StateStore instance."""
deck_data = DeckDataProvider()
# TODO(mc, 2020-11-18): check short trash FF
deck_definition = await deck_data.get_deck_definition()
deck_fixed_labware = await deck_data.get_deck_fixed_labware(deck_definit... | 5e0835db894fb3aca6c5321a782b5eacea5681a8 | 26,222 |
from typing import Optional
from typing import Mapping
def get_stream(name: Optional[str] = None,
tags: Optional[Mapping[str, str]] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetStreamResult:
"""
Use this data source to get information about a Kinesis Stream... | ec12fe08019e6d41ec8694d620efdab1e8d7683f | 26,223 |
def get_vlan_config_commands(vlan, vid):
"""Build command list required for VLAN configuration
"""
reverse_value_map = {
"admin_state": {
"down": "shutdown",
"up": "no shutdown"
}
}
if vlan.get('admin_state'):
# do we need to apply the value map?
... | 23be6435f008eb9e043e2dcb5bfdc1e1d72f6778 | 26,224 |
def kdf():
"""
Returns a dataframe with a few values for generic testing
"""
return ks.DataFrame(
{
"x": [36.12, 47.32, 56.78, None],
"y": [28.21, 87.12, 90.01, None],
"names": ["geography", "place", "location", "geospatial"],
}
) | ce0500c5e028c6480a2e500d2f0a70063e6ab13d | 26,225 |
from pathlib import Path
def build_name(prefix: str, source_ind: int, name: Path) -> str:
"""Build a package name from the index and path."""
if name.name.casefold() == '__init__.py':
name = name.parent
name = name.with_suffix('')
dotted = str(name).replace('\\', '.').replace('/', '.')
ret... | d777b1b875ff6ab6f3228538a9e4c1cfa3c398a0 | 26,226 |
def step(x, mu, sigma, bkg, a):
"""
A step function template
Can be used as a component of other fit functions
"""
step_f = bkg + a * erfc((x-mu)/(np.sqrt(2)*sigma))
return step_f | af83a9773ee0907a2dadd065870025fcc2d41441 | 26,227 |
import json
def json_line_to_track(line):
"""Converts a json line to an appropriate Track object
"""
track_dct = json.loads(line)
# Clean up word count dictionary
wc_dct = {}
for word_id, word_count in track_dct['wordcount'].iteritems():
wc_dct[int(word_id)] = int(word_count)
track... | e3b63aec0b1dce0fdf9d5c47f235496ae61fc18e | 26,228 |
def update_planting(
key, secret, planting_info,
):
"""Updates a specified planting.
API reference: https://docs.awhere.com/knowledge-base-docs/field-plantings/
Parameters
----------
key : str
API key for a valid aWhere API application.
secret : str
API secret for a valid ... | 02d5509513e484e35a580a0127b95615e30580fb | 26,229 |
def check_for_multiple(files):
""" Return list of files that looks like a multi-part post """
for regex in _RE_MULTIPLE:
matched_files = check_for_sequence(regex, files)
if matched_files:
return matched_files
return "" | 8e9985ef1ef5c85734c576704b7d9e3d690306a0 | 26,230 |
def get_density2D(f,data,steps=100):
""" Calcule la densité en chaque case d'une grille steps x steps dont les bornes sont calculées à partir du min/max de data. Renvoie la grille estimée et la discrétisation sur chaque axe.
"""
xmin, xmax = data[:,0].min(), data[:,0].max()
ymin, ymax = data[:,1].min(), data[:,1].m... | 441a2a440d7d1a095d5719e07da2289059057279 | 26,231 |
def draw_cards_command(instance, player, arguments):
""" Draw cards from the deck and put them into the calling player's hand.
Args:
instance: The GameInstance database model for this operation.
player: The email address of the player requesting the action.
arguments: A list of arguments to this comman... | ad9ef6240b5d9ec8ab2f1331b737a89539ade673 | 26,232 |
def recipe_content(*,
projects_base,
project,
recipe):
"""
Returns the content of a recipe in a project, based on the
projects base path, and the project and recipe name.
Kwargs:
projects_base (str): base path for all projects, e.g.
... | 0b6ccc19202927b49383ae5f991f5e66ece89b6a | 26,233 |
from typing import Union
def precision_score(
y_true: str,
y_score: str,
input_relation: Union[str, vDataFrame],
cursor=None,
pos_label: (int, float, str) = 1,
):
"""
---------------------------------------------------------------------------
Computes the Precision Score.
Parameters
---------... | 6b849504719d6f85402656d70dba6609e4822f49 | 26,234 |
import click
def new_deployment(name):
"""
Creates a new deployment in the /deployments directory.
Usage:
`drone-deploy new NAME`
Where NAME == a friendly name for your deployment.
Example:
`drone-deploy new drone.yourdomain.com`
"""
# create the deployment/$name directo... | ab1ae5a8e8d397c493fbd330eacf3986b2f7c448 | 26,235 |
def GenerateConfig(context):
"""Returns a list of configs and waiters for this deployment.
The configs and waiters define a series of phases that the deployment will
go through. This is a way to "pause" the deployment while some process on
the VMs happens, checks for success, then goes to the next phase.
Th... | 19a8601b876cd3c6793ba6263adc5e30f39bb25f | 26,236 |
import re
def _format_param_value(value_repr):
"""
Format a parameter value for displaying it as test output. The
values are string obtained via Python repr.
"""
regexs = ["^'(.+)'$",
"^u'(.+)'$",
"^<class '(.+)'>$"]
for regex in regexs:
m = re.match(regex... | 87d881a3159c18f56dd2bb1c5556f3e70d27c1bc | 26,237 |
import logging
def redis_get_keys(duthost, db_id, pattern):
"""
Get all keys for a given pattern in given redis database
:param duthost: DUT host object
:param db_id: ID of redis database
:param pattern: Redis key pattern
:return: A list of key name in string
"""
cmd = 'sonic-db-cli {}... | 4ac06e03048d59ffb28b7950e4bdca71bd6532a5 | 26,238 |
def data_process(X, labels, window_size, missing):
"""
Takes in 2 numpy arrays:
- X is of shape (N, chm_len)
- labels is of shape (N, chm_len)
And returns 2 processed numpy arrays:
- X is of shape (N, chm_len)
- labels is of shape (N, chm_len//window_size)
"""
# Re... | bc4e1b89e68cbf069a986a40e668311d04e2d158 | 26,239 |
def check_response_status(curr_response, full_time):
"""Check response status and return code of it.
This function also handles printing console log info
Args:
curr_response (str): Response from VK API URL
full_time (str): Full format fime for console log
Returns:
int: Sta... | e1a53cc8ae594dd333e6317840127b0bb6e3c005 | 26,240 |
def height_to_amplitude(height, sigma):
"""
Convert height of a 1D Gaussian to the amplitude
"""
return height * sigma * np.sqrt(2 * np.pi) | 18712e2a308e87e8c2ceb745d7f8c4ebccc7e28d | 26,241 |
def get_param_value(val, unit, file, line, units=True):
"""
Grab the parameter value from a line in the log file.
Returns an int, float (with units), bool, None (if no value
was provided) or a string (if processing failed).
"""
# Remove spaces
val = val.lstrip().rstrip()
# Is there a v... | 05dba3f7b3f138b4481c03cd711bee39c83bb0c0 | 26,242 |
def exact_auc(errors, thresholds):
"""
Calculate the exact area under curve, borrow from https://github.com/magicleap/SuperGluePretrainedNetwork
"""
sort_idx = np.argsort(errors)
errors = np.array(errors.copy())[sort_idx]
recall = (np.arange(len(errors)) + 1) / len(errors)
errors = np.r_[0.,... | 792652ab45096c76d448980ab527bc4d5c2a5440 | 26,243 |
def avalanche_basic_stats(spike_matrix):
"""
Example
-------
total_avalanches, avalanche_sizes, avalanche_durations = avalanche_stats(spike_matrix)
"""
total_spikes = spike_matrix.sum(axis=0)
total_spikes = np.hstack(([0], total_spikes)) # Assure it starts with no spike
avalanche = pd.S... | c053ad281b6dddd5f144c9717e7ffd352e4a6f94 | 26,244 |
from utils import indices_to_subscripts
def parse_jax_dot_general(parameters, innodes):
"""
Parse the JAX dot_general function.
Parameters
----------
parameters: A dict containing the parameters of the dot_general function.
parameters['dimension_numbers'] is a tuple of tuples of the form
... | d73b3f737411990b3c37d06d4ef3d7b89b74b795 | 26,245 |
from typing import Dict
from typing import Any
def get_stratum_alert_data(threshold: float, notification_channel: int) -> Dict[str, Any]:
""" Gets alert config for when stratum goes below given threshold
:param threshold: Below this value, grafana should send an alert
:type description: float
... | bae4aafe18286eeb5b0f59ad87804a19936ec182 | 26,246 |
def opponent1(im, display=False):
""" Generate Opponent color space. O3 is just the intensity """
im = img.norm(im)
B, G, R = np.dsplit(im, 3)
O1 = (R - G) / np.sqrt(2)
O2 = (R + G - 2 * B) / np.sqrt(6)
O3 = (R + G + B) / np.sqrt(3)
out = cv2.merge((np.uint8(img.normUnity(O1) * 255),
... | 18ff83f9cc192892c12c020a1d781cabff497544 | 26,247 |
import random
def shuffle_multiset_data(rv, rv_err):
"""
"""
#shuffle RV's and their errors
comb_rv_err = zip(rv, rv_err)
random.shuffle(comb_rv_err)
comb_rv_err_ = [random.choice(comb_rv_err) for _ in range(len(comb_rv_err))]
rv_sh, rv_err_sh = zip(*comb_rv_err_)
return np.array(... | 3075cb3cd414122b93f4ceed8d82fdd6955a7051 | 26,248 |
import time
import re
def parse_pubdate(text):
"""Parse a date string into a Unix timestamp
>>> parse_pubdate('Fri, 21 Nov 1997 09:55:06 -0600')
880127706
>>> parse_pubdate('2003-12-13T00:00:00+02:00')
1071266400
>>> parse_pubdate('2003-12-13T18:30:02Z')
1071340202
>>> parse_pubdat... | 74bc178cc4ea8fc9c7d1178b5b58cb663f1673b6 | 26,249 |
from typing import List
def find_ngram(x: np.ndarray, occurence: int= 2) -> List[int]: # add token
"""
Build pairwise of size occurence of conssecutive value.
:param x:
:type x: ndarray
:param occurence: number of succesive occurence
:type occurence: int
:return:
:rtype:
Example:
... | 0e2d5287cd145c558360a7e4a647dd49b5308b78 | 26,250 |
import sys
def list2ids(listf, verbose=False):
""" Read a list of ids, one per line
:param listf: file of ids
:param verbose: more output
:return: a set of IDS
"""
if verbose:
sys.stderr.write(f"{bcolors.GREEN} Reading IDs from text file: {listf}{bcolors.ENDC}")
i=set()
with ... | 672b66c5a9e0e47e13eaff8e059642c9950a1d9e | 26,251 |
def ewma(current, previous, weight):
"""Exponentially weighted moving average: z = w*z + (1-w)*z_1"""
return weight * current + ((1.0 - weight) * previous) | 5a678b51618ebd445db0864d9fa72f63904e0e94 | 26,252 |
def srs_double(f):
"""
Creates a function prototype for the OSR routines that take
the OSRSpatialReference object and
"""
return double_output(f, [c_void_p, POINTER(c_int)], errcheck=True) | 6b17a0fa068779c32fc7f8dc8ec45da34dc01b62 | 26,253 |
def atmost_one(*args):
"""Asserts one of the arguments is not None
Returns:
result(bool): True if exactly one of the arguments is not None
"""
return sum([1 for a in args if a is not None]) <= 1 | 448469e2e0d7cb7c00981f899ef09138e8fa17fc | 26,254 |
def _get_default_group():
"""
Getting the default process group created by :func:`init_process_group`.
"""
if not is_initialized():
raise RuntimeError(
"Default process group has not been initialized, "
"please make sure to call init_process_group."
)
return ... | 0f9c396eb33abf9441f6cd6ba4c3911efe888efb | 26,255 |
def string_parameter(name, in_, description=None):
"""
Define a string parameter.
Location must still be specified.
"""
return parameter(name, in_, str, description=description) | a149a7ad491d3a077909b10ce72187cd7b8aafcb | 26,256 |
def greater_version(versionA, versionB):
"""
Summary:
Compares to version strings with multiple digits and returns greater
Returns:
greater, TYPE: str
"""
try:
list_a = versionA.split('.')
list_b = versionB.split('.')
except AttributeError:
return versio... | 6c4a947dbc22cd26e96f9d3c8d43e7e3f57239be | 26,257 |
from bs4 import BeautifulSoup
def get_post_mapping(content):
"""This function extracts blog post title and url from response object
Args:
content (request.content): String content returned from requests.get
Returns:
list: a list of dictionaries with keys title and url
"""
post_d... | 0b3b31e9d8c5cf0a3950dc33cb2b8958a12f47d4 | 26,258 |
import os
def get_output_foldername(start_year: int, end_year: int) -> str:
""" Create an output folder and return its name """
folder_name = "app/data/{}-{}".format(start_year, end_year)
if not os.path.exists(folder_name):
os.mkdir(folder_name)
return folder_name | af098e90b858ca35c834e04af2cc293167b722d5 | 26,259 |
import textwrap
def _dict_attribute_help(object_name, path, parent_object_names, attribute):
"""
Get general help information or information on a specific attribute.
See get_help().
:param (str|unicode) attribute: The attribute we'll get info for.
"""
help_dict = {
'object_name': ob... | eb029790bc24d561d79596cd986abeba49e69a54 | 26,260 |
def len_iter(iterator):
"""Count items in an iterator"""
return sum(1 for i in iterator) | 1d828b150945cc4016cdcb067f65753a70d16656 | 26,261 |
import copy
def clones(module, N):
"""Produce N identical layers."""
return nn.ModuleList([copy.deepcopy(module) for _ in range(N)]) | 3dfc9d0d8befa26dbecaa8deda53c7fc1d00d3a1 | 26,262 |
import re
def form_transfer(form):
"""
:param form: formula in string type. e.g. 'y~x1+x2|id+firm|id',dependent_variable~continuous_variable|fixed_effect|clusters
:return: Lists of out_col, consist_col, category_col, cluster_col, fake_x, iv_col respectively.
"""
form = form.replace(' ', '')
... | 77d817a32d5df270a351f7c6a49062aa6ba72941 | 26,263 |
import os
import json
import six
def merge_metadata(preprocess_output_dir, transforms_file):
"""Merge schema, analysis, and transforms files into one python object.
Args:
preprocess_output_dir: the output folder of preprocessing. Should contain
the schema, and the numerical and categorical
an... | 68538c4f33823c5b11a945f4aefdd369cb783799 | 26,264 |
def get_user(request):
"""
Returns the user model instance associated with the given request session.
If no user is retrieved an instance of `MojAnonymousUser` is returned.
"""
user = None
try:
user_id = request.session[SESSION_KEY]
token = request.session[AUTH_TOKEN_SESSION_KEY]... | 94360776b1048c53c0f31b78207a7077fcd76058 | 26,265 |
import pprint
def main(database):
"""
:type database: db.BlogDB
"""
sqls = []
sql_create_articles = 'CREATE TABLE {} '.format(database.table_name['articles']) + \
'(id INTEGER PRIMARY KEY AUTOINCREMENT, slug CHAR(100) NOT NULL UNIQUE, cat_id INT,' + \
... | d0aa5ea2ad4d3eb7909785f427604e3e0bc7681a | 26,266 |
def fav_rate(y_pred_group):
"""
Gets rate of favorable outcome.
:param y_pred_group: Model-predicted labels of test set for privileged/unprivileged group
:type y_pred_group: `np.array`
:return: rate of favorable outcome
:rtype: `float`
"""
if y_pred_group == []:
return 0
els... | cc416dd0bcb37c413728a769652b4074bdd178ee | 26,267 |
def parse_date(datestring):
"""
Parse a date/time string into a tuple of integers.
:param datestring: The date/time string to parse.
:returns: A tuple with the numbers ``(year, month, day, hour, minute,
second)`` (all numbers are integers).
:raises: :exc:`InvalidDate` when the date ca... | c28ac922ba11e032a5400f4d8fb866a87dad2ae6 | 26,268 |
def read_datafiles(filepath):
"""
Example function for reading in data form a file.
This needs to be adjusted for the specific format that
will work for the project.
Parameters
----------
filepath : [type]
[description]
Returns
-------
[type]
[descriptio... | 789feb11cfa62d2fc2f5ac244ae2be3f618aaf2f | 26,269 |
def get_outputs(var_target_total, var_target_primary, reg, layer):
"""Construct standard `vlne` output layers."""
outputs = []
if var_target_total is not None:
target_total = Dense(
1, name = 'target_total', kernel_regularizer = reg
)(layer)
outputs.append(target_total... | 16c6307cb4d9d2e5d908fec0293cf317f8ff3d24 | 26,270 |
import os
def getJsonPath(name, moduleFile):
"""
获取JSON配置文件的路径:
1. 优先从当前工作目录查找JSON文件
2. 若无法找到则前往模块所在目录查找
"""
currentFolder = os.getcwd()
currentJsonPath = os.path.join(currentFolder, name)
if os.path.isfile(currentJsonPath):
jsonPathDict[name] = currentJsonPath
return c... | b62265f3c017c70026bb9e5264e42c219ac28d93 | 26,271 |
import functools
import operator
def flatten_list(l):
"""
Function which flattens a list of lists to a list.
"""
return functools.reduce(operator.iconcat, l, []) | 37e8918ce2f71754e385f017cdfdf38ed5a30ff4 | 26,272 |
import os
def js_to_python(in_file, out_file=None, use_qgis=True, github_repo=None):
"""Converts an Earth Engine JavaScript to Python script.
Args:
in_file (str): File path of the input JavaScript.
out_file (str, optional): File path of the output Python script. Defaults to None.
use_... | e28fb363495756212c89ded69b60daf56c0720de | 26,273 |
def getPutDeltas(delta, optType):
"""
delta: array or list of deltas
optType: array or list of optType "C", "P"
:return:
"""
# otm_x = put deltas
otm_x = []
for i in range(len(delta)):
if optType[i] == "C":
otm_x.append(1-delta[i])
else:
otm_x.appe... | a9950bd383f91c49e6c6ff745ab9b83a677ea9e8 | 26,274 |
def test_folders_has_path_long(list_folder_path, max_path=260):
"""tests a serie of folders if any of them has files whose pathfile
has a larger length than stipulated in max_path
Args:
list_folder_path (list): list of folder_path to be tested
max_path (int, optional): max file_path len per... | e00ef7a2707099b0a2606e7f7a032e1347836979 | 26,275 |
def get_positive_empirical_prob(labels: tf.Tensor) -> float:
"""Given a set of binary labels, determine the empirical probability of a positive label (i.e., the proportion of ones).
Args:
labels: tf.Tensor, batch of labels
Returns:
empirical probability of a positive label
"""
n_pos_labels = tf.math... | db2cc7b5a17c74c27b2cdb4d31e5eeef57fa9411 | 26,276 |
def networks_get_by_id(context, network_id):
"""Get a given network by its id."""
return IMPL.networks_get_by_id(context, network_id) | d7c8ac06dcf828090ec99e884751bd0e3ecde384 | 26,277 |
def get_particles(range_diff, image, clustering_settings):
"""Get the detections using Gary's original method
Returns a list of particles and their properties
Parameters
----------
range_diff:
output from background subtraction
image:
original image frame for intensity calculat... | ee98806ed38e341da80a9bf3c84d57310a84f2ca | 26,278 |
def validate_file(file):
"""Validate that the file exists and is a proper puzzle file.
Preemptively perform all the checks that are done in the input loop of sudoku_solver.py.
:param file: name of file to validate
:return True if the file passes all checks, False if it fails
"""
try:
o... | 31b9a5fa7dc999d0336b69642c549517399686c1 | 26,279 |
def poly(coeffs, n):
"""Compute value of polynomial given coefficients"""
total = 0
for i, c in enumerate(coeffs):
total += c * n ** i
return total | 332584e7bc634f4bcfbd9b6b4f4d04f81df7cbe2 | 26,280 |
from typing import Iterable
from typing import Dict
from typing import Hashable
from typing import Tuple
def group_by_vals(
features: Iterable[feature]
) -> Dict[Hashable, Tuple[feature, ...]]:
"""
Construct a dict grouping features by their values.
Returns a dict where each value is mapped to a ... | 436b3e038a11131ea6c0b967c57dd5db59a4b67c | 26,281 |
def coords2cells(coords, meds, threshold=15):
"""
Single plane method with KDTree. Avoid optotune <-> holography mismatch weirdness.
Threshold is in pixels.
"""
holo_zs = np.unique(coords[:,2])
opto_zs = np.unique(meds[:,2])
matches = []
distances = []
ismatched = []
for hz, oz... | 7286be31c9e201df4aea9881bc8226816d0fbf32 | 26,282 |
def how_many(num):
"""Count the number of digits of `num`."""
if num < 10:
return 1
else:
return 1 + how_many(num // 10) | 6b6f8c2a95dac9f2a097300924e29bbca0bdd55c | 26,283 |
def line_length_check(line):
"""Return TRUE if the line length is too long"""
if len(line) > 79:
return True
return False | 2cde1a2b8f20ebf57c6b54bf108e97715789a51d | 26,284 |
def load_image_into_numpy_array(path):
"""Load an image from file into a numpy array.
Puts image into numpy array to feed into tensorflow graph.
Note that by convention we put it into a numpy array with shape
(height, width, channels), where channels=3 for RGB.
Args:
path: a file path.
Returns:
u... | e0ac545486a7ae18cf7c40c03352a04d606c093f | 26,285 |
def possibly_intersecting(dataframebounds, geometry, buffer=0):
"""
Finding intersecting profiles for each branch is a slow process in case of large datasets
To speed this up, we first determine which profile intersect a square box around the branch
With the selection, the interseting profiles can be de... | a3e5d031555f92de1fe9ee2d1fb75163d0e29eb9 | 26,286 |
def compute_complexity(L, k=5, from_evalues=False, from_gram=False):
"""
Computes a variety of internal representation complexity metrics at once.
Parameters
----------
L : numpy.ndarray, shape (n_samples, ...)
internal representation matrix or precomputed eigenvalues
k : int, default=5
... | 57283101a1dc266f2059b760715f6b2a782a5e4c | 26,287 |
import os
import io
import logging
import traceback
def write_html_report(xml_root, work_dir, html_dir, html_name = 'index.html'):
""" Write the HTML report in a given directory
"""
if not os.path.isdir(html_dir):
os.makedirs(html_dir)
html_path = os.path.join(html_dir, html_name)
... | 6de29e8531a08931f18ebead4c2bd2c5211125e3 | 26,288 |
def settings(request, username, args={}, tab="change_password"):
"""
Show a page which allows the user to change his settings
"""
if not request.user.is_authenticated():
return render(request, "users/settings/settings_error.html", {"reason": "not_logged_in"})
profile_user = User.objects... | 1325f952bc89644e6a9df0c64c43af85e52858a0 | 26,289 |
import hashlib
def check_contents(md5, filepath, ignore):
"""
md5 - the md5 sum calculated last time the data was validated as correct
filepath - the location/file where the new data is, this is to be validated
ignore - a list of regular expressions that should be thrown out, line by line in the compa... | fb6ae4a3b6600f7df64cf2ccfe24d035c4a98042 | 26,290 |
def create_id(prefix=None):
""" Create an ID using the module-level ID Generator"""
if not prefix:
return _get_generator().create_id()
else:
return _get_generator().create_id(prefix) | cfebf908175fc0a0dc64664f5ceb94eb8395671f | 26,291 |
from re import A
def evaluate_policy(theta, F):
"""
Given theta (scalar, dtype=float) and policy F (array_like), returns the
value associated with that policy under the worst case path for {w_t}, as
well as the entropy level.
"""
rlq = qe.robustlq.RBLQ(Q, R, A, B, C, beta, theta)
K_F, P_F,... | 40db3c4215aea266ed2b85256c901f135fdc5b50 | 26,292 |
def arspec(x, order, nfft=None, fs=1):
"""Compute the spectral density using an AR model.
An AR model of the signal is estimated through the Yule-Walker equations;
the estimated AR coefficient are then used to compute the spectrum, which
can be computed explicitely for AR models.
Parameters
--... | b0e003bf387870320ea61419a169a80b1a41165d | 26,293 |
import warnings
def T_asymmetry(x, beta):
"""Performs a transformation over the input to break the symmetry of the symmetric functions.
Args:
x (np.array): An array holding the input to be transformed.
beta (float): Exponential value used to produce the asymmetry.
Returns:
The tr... | 8ad3fa58fc2d1b641e4fc122517dc4202a76f840 | 26,294 |
def fit_improved_B2AC_numpy(points):
"""Ellipse fitting in Python with improved B2AC algorithm as described in
this `paper <http://autotrace.sourceforge.net/WSCG98.pdf>`_.
This version of the fitting simply applies NumPy:s methods for calculating
the conic section, modelled after the Matlab code in the... | 85544ec311edce8eebdd6c143a68e5fc40b0a882 | 26,295 |
import copy
def generate_complex_topologies_and_positions(ligand_filename, protein_pdb_filename):
"""
Generate the topologies and positions for complex phase simulations, given an input ligand file (in supported openeye
format) and protein pdb file. Note that the input ligand file should have coordinates ... | 6c47957c1d70936486d4bf5167f3724935a5f4df | 26,296 |
def aten_append(mapper, graph, node):
""" 构造对list进行append的PaddleLayer。
TorchScript示例:
%90 : int[] = aten::append(%_output_size.1, %v.1)
参数含义:
%90 (list): 输出,append后的list。
%_output_size.1 (list): 需要进行append的list。
%v.1 (-): append的元素。
"""
scope_name = mapper.normal... | f95977daf6da0fc2aafceda404d4dd6faf4d5f0c | 26,297 |
def res_from_obseravtion_data(observation_data):
"""create a generic residual dataframe filled with np.NaN for
missing information
Parameters
----------
observation_data : pandas.DataFrame
pyemu.Pst.observation_data
Returns
-------
res_df : pandas.DataFrame
"""
res_df ... | d569c80d1536c3a46c7f9b6120753e56c118a74e | 26,298 |
import re
def dtype_ripper(the_dtype, min_years, max_years):
"""Extract the range of years from the dtype of a structured array.
Args:
the_dtype (list): A list of tuples with each tuple containing two
entries, a column heading string, and a string defining the
data type for th... | 1cbcc30cf7760d466187873aa5ea221691b2092d | 26,299 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.