content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import io
def read_template(filename):
"""[summary]
This function is for reading a template from a file
[description]
Arguments:
filename {[type]} -- [description]
Returns:
[type] -- [description]
"""
with io.open(filename, encoding = 'utf-8') as template_file:
content = template_file.read()
return ... | f4eceb6d2b9075d0cf61d31842b754d6f3c01ce4 | 21,000 |
def S(a):
"""
Return the 3x3 cross product matrix
such that S(a)*b = a x b.
"""
assert a.shape == (3,) , "Input vector is not a numpy array of size (3,)"
S = np.asarray([[ 0.0 ,-a[2], a[1] ],
[ a[2], 0.0 ,-a[0] ],
[-a[1], a[0], 0.0 ]])
return S | b71f2529ccdafcc2b27f28c030ec2e3be9bf43ea | 21,001 |
from typing import Collection
from typing import Mapping
from typing import Any
from typing import Set
from typing import Dict
from typing import List
import itertools
def bulk_get_subscriber_user_ids(
stream_dicts: Collection[Mapping[str, Any]],
user_profile: UserProfile,
subscribed_stream_ids: Set[int],... | 49c6fc717340523ef4bdc1d66de111c4c86ce777 | 21,002 |
def adjust_learning_rate(optimizer, step):
"""Sets the learning rate to the initial LR decayed by 10 every 30 epochs"""
if step == 500000:
for param_group in optimizer.param_groups:
param_group['lr'] = 0.0005
elif step == 1000000:
for param_group in optimizer.param_groups:
... | 729c6650eb9b88102b68ba5e8d356e1cfa8b6632 | 21,003 |
def get_menu_permissions(obj):
"""
接收request中user对象的id
:param obj:
:return: 通过表级联得到user或者user所属group对应的菜单信息
"""
menu_obj = Menu.objects # 菜单对象
umids = [x.id for x in UserMenu.objects.get(user=obj).menu.all()]
isgroups = [x.id for x in User.objects.get(id=obj).groups.all()] # 用户所属组
... | 45b68b8f39b5507aa1aa1a58c3cc16eb5a1a983a | 21,004 |
import typing
def process_package(
package_path: str,
include_patterns: typing.Optional[typing.List[str]] = None,
exclude_patterns: typing.Optional[typing.List[str]] = None,
) -> SchemaMap:
"""
Recursively process a package source folder and return all json schemas from the top level functions it ... | f0297d8d93161dc481f8d2aca81a4618ced603fe | 21,005 |
import os
def find_file(path, include_str='t1', exclude_str='lesion'):
"""finds all the files in the given path which include include_str in their
name and do not include exclude_str
----------
path: path to the directory
path where the files are stored
include_str: string
strin... | 32f3e373268f3cf310eebceb339c0c6cb9e34cb8 | 21,006 |
import os
import sqlite3
def parse_datasets(dataset_option, database):
""" Parses dataset names from command line. Valid forms of input:
- None (returns None)
- Comma-delimited list of names
- File of names (One per line)
Also checks to make sure that the datasets are i... | 720ab961d5357837ee757be4f837c4d7cf25e219 | 21,007 |
def remove_suffix(input_string, suffix):
"""From the python docs, earlier versions of python does not have this."""
if suffix and input_string.endswith(suffix):
return input_string[: -len(suffix)]
return input_string | af4af2442f42121540de00dfaece13831a27cc57 | 21,008 |
def ais_TranslatePointToBound(*args):
"""
:param aPoint:
:type aPoint: gp_Pnt
:param aDir:
:type aDir: gp_Dir
:param aBndBox:
:type aBndBox: Bnd_Box &
:rtype: gp_Pnt
"""
return _AIS.ais_TranslatePointToBound(*args) | a45701c8a35fdd07e870ec850467a49145acd644 | 21,009 |
def unet_deepflash2(pretrained=None, **kwargs):
"""
U-Net model optimized for deepflash2
pretrained (str): specifies the dataset for pretrained weights
"""
model = _unet_deepflash2(pretrained=pretrained, **kwargs)
return model | 40b11641e3e2c418458c7e1d7e6180d4015ab2b9 | 21,010 |
import requests
def get_bga_game_list():
"""Gets a geeklist containing all games currently on Board Game Arena."""
result = requests.get("https://www.boardgamegeek.com/xmlapi2/geeklist/252354")
return result.text | 61418d5c0e0ad12c3f7af8a7831d02f94153ac84 | 21,011 |
def artifact(name: str, path: str):
"""Decorate a step to create a KFP HTML artifact.
Apply this decorator to a step to create a Kubeflow Pipelines artifact
(https://www.kubeflow.org/docs/pipelines/sdk/output-viewer/).
In case the path does not point to a valid file, the step will fail with
an erro... | b5033a66612d0f2aa5b138b368ca0f1acb7c2b21 | 21,012 |
import http
def build_status(code: int) -> str:
"""
Builds a string with HTTP status code and reason for given code.
:param code: integer HTTP code
:return: string with code and reason
"""
status = http.HTTPStatus(code)
def _process_word(_word: str) -> str:
if _word == "OK":
... | 9730abf472ddc3d5e852181c9d60f8c42fee687d | 21,013 |
def pretty_picks_players(picks):
"""Formats a table of players picked for the gameweek, with live score information"""
fields = ["Team", "Position", "Player", "Gameweek score", "Chance of playing next game",
"Player news", "Sub position", "Id"]
table = PrettyTable(field_names=fields)
table... | f4269fedad07b3302f724ba38f3afc1d8d9afc9f | 21,014 |
def open_path(request):
"""
handles paths authors/
"""
if(request.method == "POST"):
json_data = request.data
new_author = Author(is_active=False)
# Creating new user login information
if "password" in json_data:
password = json_data["password"]
... | 3c6a8d8fa6ac03a0bdd2b805fa348c43cf088f35 | 21,015 |
def encode_task(task):
""" Encodes a syllogistic task.
Parameters
----------
task : list(list(str))
List representation of the syllogism (e.g., [['All', 'A', 'B'], ['Some', 'B', 'C']]).
Returns
-------
str
Syllogistic task encoding (e.g., 'AI1').
"""
return Syllog... | b05b9e691d045bcc4877e1d9b9875902b9201bf7 | 21,016 |
def resize_small(image, resolution):
"""Shrink an image to the given resolution."""
h, w = image.shape[0], image.shape[1]
ratio = resolution / min(h, w)
h = tf.round(h * ratio, tf.int32)
w = tf.round(w * ratio, tf.int32)
return tf.image.resize(image, [h, w], antialias=True) | c44f615c788f300c62eef617f47b81c761ce63bc | 21,017 |
import time
def retry(func_name, max_retry, *args):
"""Retry a function if the output of the function is false
:param func_name: name of the function to retry
:type func_name: Object
:param max_retry: Maximum number of times to be retried
:type max_retry: Integer
:param args: Arguments passed... | 29051605dbad65823c1ca99afb3237679a37a08c | 21,018 |
def encode_randomness(randomness: hints.Buffer) -> str:
"""
Encode the given buffer to a :class:`~str` using Base32 encoding.
The given :class:`~bytes` are expected to represent the last 10 bytes of a ULID, which
are cryptographically secure random values.
.. note:: This uses an optimized strategy... | 5d1ba06d4d16f724a86c2c47c180c12fe0b16602 | 21,019 |
from typing import OrderedDict
import six
import json
def obtain_parameter_values(flow):
"""
Extracts all parameter settings from the model inside a flow in OpenML
format.
Parameters
----------
flow : OpenMLFlow
openml flow object (containing flow ids, i.e., it has to be downloaded
... | 25374b844eb3172927e74fe20b26483e547a1583 | 21,020 |
def logging_sync_ocns(cookie, in_from_or_zero, in_to_or_zero):
""" Auto-generated UCSC XML API Method. """
method = ExternalMethod("LoggingSyncOcns")
method.cookie = cookie
method.in_from_or_zero = str(in_from_or_zero)
method.in_to_or_zero = str(in_to_or_zero)
xml_request = method.to_xml(optio... | 178e8207305f419a8f7d182b10b23ab8548ad624 | 21,021 |
def story_role(name, rawtext, text, lineno, inliner, options=None, content=None):
"""Link to a JIRA issue.
Returns 2 part tuple containing list of nodes to insert into the
document and a list of system messages.
Both are allowed to be empty.
:param name: The role name used in the document.
:pa... | 0f347d7c5a7a802b9f3b23ee70996e86155d2ca9 | 21,022 |
def benedict_bornder_constants(g, critical=False):
""" Computes the g,h constants for a Benedict-Bordner filter, which
minimizes transient errors for a g-h filter.
Returns the values g,h for a specified g. Strictly speaking, only h
is computed, g is returned unchanged.
The default formula for the ... | ca40941b4843b3d71030549da2810c9241ebdf72 | 21,023 |
import ispyb.model.datacollection
import ispyb.model.processingprogram
import ispyb.model.screening
import ispyb.model.image_quality_indicators
import ispyb.model.detector
import ispyb.model.sample
import ispyb.model.samplegroup
import logging
import configparser
def enable(configuration_file, section="ispyb"):
"... | a48ce8d2157f151a4f3e7146e7d8c8881a4dfc23 | 21,024 |
def median(f, x, y, a, b):
"""
Return the median value of the `size`-neighbors of the given point.
"""
# Create the sub 2d array
sub_f = f[x - a:x + a + 1, y - b:y + b + 1]
# Return the median
arr = np.sort(np.asarray(sub_f).reshape(-1))
return np.median(arr) | 7cdb625ad4906efac92cd94b1dfce91df7854daf | 21,025 |
from typing import Set
from pathlib import Path
def build_relevant_api_reference_files(
docstring: str, api_doc_id: str, api_doc_path: str
) -> Set[str]:
"""Builds importable link snippets according to the contents of a docstring's `# Documentation` block.
This method will create files if they do not exi... | e83aaed8cfc0ec7ee8fffb3f95eb2c5aa948d212 | 21,026 |
def find_zip_entry(zFile, override_file):
"""
Implement ZipFile.getinfo() as case insensitive for systems with a case
insensitive file system so that looking up overrides will work the same
as it does in the Sublime core.
"""
try:
return zFile.getinfo(override_file)
except KeyError:... | 33b1b868378a789ebc014615b1bc93b34b3f1e67 | 21,027 |
def get_mode(elements):
"""The element(s) that occur most frequently in a data set."""
dictionary = {}
elements.sort()
for element in elements:
if element in dictionary:
dictionary[element] += 1
else:
dictionary[element] = 1
# Get the max value
max_value ... | bc792ffe58ffb3b9368559fe45ec623fe8accff6 | 21,028 |
def holtWintersAberration(requestContext, seriesList, delta=3):
"""
Performs a Holt-Winters forecast using the series as input data and plots the
positive or negative deviation of the series data from the forecast.
"""
results = []
for series in seriesList:
confidenceBands = holtWintersConfidenceBands(r... | 05040695e7d6f6e5d8e117d32f66ebbfb0cb7392 | 21,029 |
def get_in_addition_from_start_to_end_item(li, start, end):
"""
获取除开始到结束之外的元素
:param li: 列表元素
:param start: 开始位置
:param end: 结束位置
:return: 返回开始位置到结束位置之间的元素
"""
return li[start:end + 1] | 7106a9d409d9d77ab20e7e85d85c2ddb7a2a431c | 21,030 |
import re
def remove_special_message(section_content):
"""
Remove special message - "medicinal product no longer authorised"
e.g.
'me di cin al p ro du ct n o lo ng er a ut ho ris ed'
'me dic ina l p rod uc t n o l on ge r a uth ori se d'
:param section_content: content of a section
:ret... | 37d9cbd697a98891b3f19848c90cb17dafcd6345 | 21,031 |
def simulate_cash_flow_values(cash_flow_data, number_of_simulations=1):
"""Simulate cash flow values from their mean and standard deviation.
The function returns a list of numpy arrays with cash flow values.
Example:
Input:
cash_flow_data: [[100, 20], [-500, 10]]
number_of_simulations: 3
O... | 691122945f811e20b40032cb49920d3b2c7f5c13 | 21,032 |
import time
def sim_v1(sim_params, prep_result, progress=None, pipeline=None):
"""
Map the simulation over the peptides in prep_result.
This is actually performed twice in order to get a train and (different!) test set
The "train" set includes decoys, the test set does not; furthermore
the the er... | 243fca643749a5d346013f0547cefea1c1df7767 | 21,033 |
def apply_function_elementwise_series(ser, func):
"""Apply a function on a row/column basis of a DataFrame.
Args:
ser (pd.Series): Series.
func (function): The function to apply.
Returns:
pd.Series: Series with the applied function.
Examples:
>>> df = pd.Da... | d2af0a9c7817c602b4621603a8f06283f34ae81a | 21,034 |
from bs4 import BeautifulSoup
def is_the_bbc_html(raw_html, is_lists_enabled):
"""
Creates a concatenate string of the article, with or without li elements included from bbc.co.uk.
:param raw_html: resp.content from response.get().
:param is_lists_enabled: Boolean to include <Li> elements.
:return... | fb6bca09e1ebb78d7afd6d2afaa52feab9843d21 | 21,035 |
def create_empty_module(module_name, origin=None):
"""Creates a blank module.
Args:
module_name: The name to be given to the module.
origin: The origin of the module. Defaults to None.
Returns:
A blank module.
"""
spec = spec_from_loader(module_name, loader=None, origin=ori... | f65e1fbbbba13fc25e84ea89c57329ba48d22ac7 | 21,036 |
def _warp_3d_cupy(image, vector_field, mode, block_size: int = 8):
"""
Parameters
----------
image
vector_field
mode
block_size
Returns
-------
"""
xp = Backend.get_xp_module()
source = r"""
extern "C"{
__global__ void warp_3d(float* wa... | 4dc6f0ebeb580833cb7f2a247b1c2e1d46b65535 | 21,037 |
def BitWidth(n: int):
""" compute the minimum bitwidth needed to represent and integer """
if n == 0:
return 0
if n > 0:
return n.bit_length()
if n < 0:
# two's-complement WITHOUT sign
return (n + 1).bit_length() | 46dcdfb0987268133d606e609d39c641b9e6faab | 21,038 |
import copy
import numpy
def read_many_nam_cube(netcdf_file_names, PREDICTOR_NAMES):
"""Reads storm-centered images from many NetCDF files.
:param netcdf_file_names: 1-D list of paths to input files.
:return: image_dict: See doc for `read_image_file`.
"""
image_dict = None
keys_to_concat = [PR... | 100e6dfcd998ae6d2d2f673251c6110ccec90b00 | 21,039 |
def rouge_l_summary_level(evaluated_sentences, reference_sentences):
"""
Computes ROUGE-L (summary level) of two text collections of sentences.
http://research.microsoft.com/en-us/um/people/cyl/download/papers/
rouge-working-note-v1.3.1.pdf
Calculated according to:
R_lcs = SUM(1, u)[LCS<union>(... | 9022cc4cc90d9b57f48716839b5e97315a7b78c6 | 21,040 |
def construct_classifier(cfg,
module_names,
in_features,
slot_machine=False,
k=8,
greedy_selection=True
):
"""
Constructs a sequential model of fully-connected l... | 84091ce1a74a5baae8cde8b32c2ab28e0ccc7175 | 21,041 |
def size_adjustment(imgs, shape):
"""
Args:
imgs: Numpy array with shape (data, width, height, channel)
= (*, 240, 320, 3).
shape: 256 or None.
256: imgs_adj.shape = (*, 256, 256, 3)
None: No modification of imgs.
Returns:
imgs_adj: Numpy array wit... | 5143a34b3ad2085596a682811b6f35dca040c3e0 | 21,042 |
def to_full_model_name(root_key: str) -> str:
"""
Find model name from the root_key in the file.
Args:
root_key: root key such as 'system-security-plan' from a top level OSCAL model.
"""
if root_key not in const.MODEL_TYPE_LIST:
raise TrestleError(f'{root_key} is not a top level mod... | 8c73a54cb03c8cc52d24ec4bc284326289ff04f1 | 21,043 |
from typing import Dict
def is_unique(s: str) -> bool:
"""
Time: O(n)
Space: O(n)
"""
chars: Dict[str, int] = {}
for char in s:
if char in chars:
return False
else:
chars[char] = 1
return True | 4f77691be1192202b57b20bdc5676a31bc8b175e | 21,044 |
def _title(soup):
"""
Accepts a BeautifulSoup object for the APOD HTML page and returns the
APOD image title. Highly idiosyncratic with adaptations for different
HTML structures that appear over time.
"""
LOG.debug('getting the title')
try:
# Handler for later APOD entries
c... | ca9cd150e1d9f51e1e57628ed202b723f8aa3e82 | 21,045 |
def is_available() -> bool:
"""Return ``True`` if the handler has its dependencies met."""
return HAVE_RLE | b4e035dc62ef79211cb038a8b567985679c500aa | 21,046 |
def model_with_buckets(encoder_inputs,
decoder_inputs,
targets,
weights,
buckets,
seq2seq,
softmax_loss_function=None,
per_example_loss=False,
... | 795c7445bdf608db85148656179ccc0467af6dee | 21,047 |
def sqlite_cast(vtype, v):
"""
Returns the casted version of v, for use in
database.
SQLite does not perform any type check or conversion
so this function should be used anytime a data comes
from outstide to be put in database.
This function also handles CoiotDatetime objects and
accept... | 2ecf79b5aec2d5516cc624b9aa279be9f1b9d1b2 | 21,048 |
import os
import shlex
import sys
import subprocess
from datetime import datetime
import queue
import threading
def command_runner(
command, # type: Union[str, List[str]]
valid_exit_codes=None, # type: Optional[List[int]]
timeout=3600, # type: Optional[int]
shell=False, # type: bool
encoding=N... | d04ec3d96bf8caf4dea71dfdc90847c29b8440bd | 21,049 |
def read_table(name):
"""
Mock of IkatsApi.table.read method
"""
return TABLES[name] | 261ab82a5389155997924c1468087a139b50f9e8 | 21,050 |
def cosh(x, out=None):
"""
Raises a ValueError if input cannot be rescaled to a dimensionless
quantity.
"""
if not isinstance(x, Quantity):
return np.cosh(x, out)
return Quantity(
np.cosh(x.rescale(dimensionless).magnitude, out),
dimensionless,
copy=False
) | d50891be37de3c9729c3a15e1315f74ff55baedc | 21,051 |
from datetime import datetime
def dates_from_360cal(time):
"""Convert numpy.datetime64 values in 360 calendar format.
This is because 360 calendar cftime objects are problematic, so we
will use datetime module to re-create all dates using the
available data.
Parameters
----------
tim... | d13e2146414a4dbd25cab0015348281503134331 | 21,052 |
def db_queue(**data):
"""Add a record to queue table.
Arguments:
**data: The queue record data.
Returns:
(dict): The inserted queue record.
"""
fields = data.keys()
assert 'request' in fields
queue = Queue(**data)
db.session.add(queue)
db.session.commit()
return... | ca5dda54fecf37be9eae682c2b04325b55caf931 | 21,053 |
def loadMnistData(trainOrTestData='test'):
"""Loads MNIST data from sklearn or web.
:param str trainOrTestData: Must be 'train' or 'test' and specifies which \
part of the MNIST dataset to load.
:return: images, targets
"""
mnist = loadMNIST()
if trainOrTestData == 'train':
X = mni... | 3fb06616a784ac863f4df093e981982be077f5a7 | 21,054 |
def times_once() -> _Timing:
"""
Expect the request a single time
:return: Timing object
"""
return _Timing(1) | dd4d97344613676668cf7e07fad6e5f696861924 | 21,055 |
def linear_growth(mesh, pos, coefficient):
"""Applies a homotety to a dictionary of coordinates.
Parameters
----------
mesh : Topomesh
Not used in this algorithm
pos : dict(int -> iterable)
Dictionary (pid -> ndarray) of the tissue vertices
coefficient : ... | bed27bc4a75d1628bf3331062817d1bf1b21e9c8 | 21,056 |
def einstein_t(tini, tfin, npoint, HT_lim=3000,dul=False,model=1):
"""
Computes the *Einstein temperature*
Args:
tini: minimum temperature (K) of the fitting interval
tfin: maximum temperature
npoint: number of points in the T range
HT_lim: high temperature limit where C... | bc914dcd600f9f5b3327a0e954356f4dd5d87493 | 21,057 |
import pathlib
def normalize_uri(path_uri: str) -> str:
"""Convert any path to URI. If not a path, return the URI."""
if not isinstance(path_uri, pathlib.Path) and is_url(path_uri):
return path_uri
return pathlib.Path(path_uri).resolve().as_uri() | b0682d1b2b1dea07195865db4be534a18e6b965e | 21,058 |
import logging
def RETune(ont: Ontology, training: [Annotation]):
""" Tune the relation extraction class over a range of various values and return the correct
parameters
Params:
ont (RelationExtractor/Ontology) - The ontology of information needed to form the base
training ([Datapoint]) -... | d53831f08fd1855537b3bb7cb5a5f27625fa8b31 | 21,059 |
def create_instance(test_id, config, args):
"""
Invoked by TestExecutor class to create a test instance
@test_id - test index number
@config - test parameters from, config
@args - command line args
"""
return TestNodeConnectivity(test_id, config, args) | a3defb1f0f72fc0788fa2120829334f9a9670042 | 21,060 |
def to_me() -> Rule:
"""
:说明:
通过 ``event.is_tome()`` 判断事件是否与机器人有关
:参数:
* 无
"""
return Rule(ToMeRule()) | 92b6a04bbeac6e0b3eb3f53641efd2552b19f620 | 21,061 |
def unsaturated_atom_keys(xgr):
""" keys of unsaturated (radical or pi-bonded) atoms
"""
atm_unsat_vlc_dct = atom_unsaturated_valences(xgr, bond_order=False)
unsat_atm_keys = frozenset(dict_.keys_by_value(atm_unsat_vlc_dct, bool))
return unsat_atm_keys | 0af0469b3370a0c015238cad5b2717fbb977e6c5 | 21,062 |
def clip_data(input_file, latlim, lonlim):
"""
Clip the data to the defined extend of the user (latlim, lonlim)
Keyword Arguments:
input_file -- output data, output of the clipped dataset
latlim -- [ymin, ymax]
lonlim -- [xmin, xmax]
"""
try:
if input_file.split('.')[-1] == 'tif... | bf691d4021cf0bbeade47b6d389e5daa3261f22a | 21,063 |
def fetch_last_posts(conn) -> list:
"""Fetch tooted posts from db"""
cur = conn.cursor()
cur.execute("select postid from posts")
last_posts = cur.fetchall()
return [e[0] for e in last_posts] | dd5addd1ba19ec2663a84617904f6754fe7fc1fc | 21,064 |
def update_click_map(selectedData, date, hoverData, inputData):
"""
click to select a airport to find the detail information
:param selectedData:
:param date:
:param hoverData:
:return:
"""
timestamp = pd.to_datetime(date) if date else 0
fig = px.scatter_geo(
airports_info,
... | 1baaba25254eede65c2dff9b95c9ac40a0777dac | 21,065 |
def EncoderText(model_name, vocab_size, word_dim, embed_size, num_layers, use_bi_gru=False, text_norm=True, dropout=0.0):
"""A wrapper to text encoders. Chooses between an different encoders
that uses precomputed image features.
"""
model_name = model_name.lower()
EncoderMap = {
'scan': Enco... | bf3657e2c5def238e9ec84cd674c21c079169b9e | 21,066 |
def feat_extract(pretrained=False, **kwargs):
"""Constructs a ResNet-Mini-Imagenet model"""
model_urls = {
'resnet18': 'https://download.pytorch.org/models/resnet18-5c106cde.pth',
'resnet34': 'https://download.pytorch.org/models/resnet34-333f7ec4.pth',
'resnet52': 'https://do... | 9e628b4905e696aa55c9e4313888f406bf1fb413 | 21,067 |
from typing import Union
from pathlib import Path
from typing import Optional
import fnmatch
import tempfile
def compose_all(
mirror: Union[str, Path],
branch_pattern: str = "android-*",
work_dir: Optional[Path] = None,
force: bool = False,
) -> Path:
"""Iterates through all the branches in AOSP a... | 4293df4708633574ccab70fe597ca390b04aa12c | 21,068 |
def rearrange_digits(input_list):
"""
Rearrange Array Elements so as to form two number such that their sum is maximum.
Args:
input_list(list): Input List
Returns:
(int),(int): Two maximum sums
"""
n = len(input_list)
heap_sort(input_list)
decimal_value = 1
n1 = 0
... | 3d0d4964ce5faca8aeb27bef56de1840e5cb5f51 | 21,069 |
def _partial_ema_scov_update(s:dict, x:[float], r:float=None, target=None):
""" Update recency weighted estimate of scov-like matrix by treating quadrants individually """
assert len(x)==s['n_dim']
# If target is not supplied we maintain a mean that switches from emp to ema
if target is None:
... | b54f2897abe45eec85cb843a23e8d6f0f4f2642d | 21,070 |
import urllib2
from urllib import error, request
import sys
import json
def refresh_rates(config, path="rates.json"):
"""Fetch and save the newest rates
Arguments:
config {currency.config} -- Config object
Keyword Arguments:
path {str} -- path or filename of Rates JSON to be saved
... | b9f2d3b5f0ff85e954419335936fe8da8bdfb239 | 21,071 |
def _get_chrome_options():
"""
Returns the chrome options for the following arguments
"""
chrome_options = Options()
# Standard options
chrome_options.add_argument("--disable-infobars")
chrome_options.add_argument('--ignore-certificate-errors')
# chrome_options.add_argument('--no-sandbo... | 0db0799c53487e35b4d2de977fa07fb260d7e930 | 21,072 |
def add_document(dbname, colname, doc, url=cc.URL_KRB, krbheaders=cc.KRBHEADERS) :
"""Adds document to database collection.
"""
resp = post(url+dbname+'/'+colname+'/', headers=krbheaders, json=doc)
logger.debug('add_document: %s\n to %s/%s resp: %s' % (str(doc), dbname, colname, resp.text))
return ... | 96885464a8a9ad9f61a39391ce950594d282ff07 | 21,073 |
def legendre(n, monic=0):
"""Returns the nth order Legendre polynomial, P_n(x), orthogonal over
[-1,1] with weight function 1.
"""
if n < 0:
raise ValueError("n must be nonnegative.")
if n==0: n1 = n+1
else: n1 = n
x,w,mu0 = p_roots(n1,mu=1)
if n==0: x,w = [],[]
hn = 2.0/(2*... | bfd2bb0603e320e9ea330c8e51b17ab53a03382f | 21,074 |
def cal_sort_key(cal):
"""
Sort key for the list of calendars: primary calendar first,
then other selected calendars, then unselected calendars.
(" " sorts before "X", and tuples are compared piecewise)
"""
if cal["selected"]:
selected_key = " "
else:
selected_key = "X"
... | 4235700b003689fed304b88085ba9fa9880f3839 | 21,075 |
import os
import torch
import datasets
def get_data_loader():
"""Safely downloads data. Returns training/validation set dataloader."""
mnist_transforms = transforms.Compose(
[transforms.ToTensor(),
transforms.Normalize((0.1307, ), (0.3081, ))])
# We add FileLock here because multiple wor... | a7c194cddd10f4febea18096555dc44fa68baf8d | 21,076 |
def preview_game_num():
"""retorna el numero de la ultima partida jugada"""
df = pd.read_csv('./data/stats.csv', encoding="utf8")
x = sorted(df["Partida"],reverse=True)[0]
return x | 7af698416fd60be4e7be74e7a104cd6fa956f649 | 21,077 |
def XCO(
directed = False, preprocess = "auto", load_nodes = True, load_node_types = True,
load_edge_weights = True, auto_enable_tradeoffs = True,
sort_tmp_dir = None, verbose = 2, cache = True, cache_path = None,
cache_sys_var = "GRAPH_CACHE_DIR", version = "4.46", **kwargs
) -> Graph:
"""Return XC... | 34c77f3074031b41fba8da0523a263a511734bff | 21,078 |
def rasterize_layer_by_ref_raster(src_vector, ref_raster, use_attribute, all_touched=False, no_data_value=0):
"""Rasterize vector data. Get the cell value in defined grid of ref_raster
from its overlapped polygon.
Parameters
----------
src_vector: Geopandas.GeoDataFrame
Which vector data to... | acc3b73882548f8fbfee6855773f902fd2689bc8 | 21,079 |
def wraplatex(text, width=WIDTH):
""" Wrap the text, for LaTeX, using ``textwrap`` module, and ``width``."""
return "$\n$".join(wrap(text, width=width)) | b558f2524917ec73160f4bea48029dedb9b6a12e | 21,080 |
def register(request):
"""
Render and process a basic registration form.
"""
ctx = {}
if request.user.is_authenticated():
if "next" in request.GET:
return redirect(request.GET.get("next", 'control:index'))
return redirect('control:index')
if request.method == 'POST':
... | f8d81d16903d0d5fe2e3224a535fd8f1795f9ad0 | 21,081 |
from typing import List
def green_agg(robots: List[gs.Robot]) -> np.ndarray:
"""
This is a dummy aggregator function (for demonstration) that just saves
the value of each robot's green color channel
"""
out_arr = np.zeros([len(robots)])
for i, r in enumerate(robots):
out_arr[i] = r._co... | 8e86200bf7ed51cea3bdce06be2fb3300ac20a5a | 21,082 |
import socket
def tcp_port_open_locally(port):
"""
Returns True if the given TCP port is open on the local machine
"""
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
result = sock.connect_ex(("127.0.0.1", port))
return result == 0 | f5c801a5016085eedbed953089742e184f514db5 | 21,083 |
def wrap(text, width=80):
"""
Wraps a string at a fixed width.
Arguments
---------
text : str
Text to be wrapped
width : int
Line width
Returns
-------
str
Wrapped string
"""
return "\n".join(
[text[i:i + width] for i in range(0, len(text), w... | 793840a1cae51397de15dd16051c5dfffc211768 | 21,084 |
def parallel_vector(R, alt, max_alt=1e5):
"""
Generates a viewing and tangent vectors
parallel to the surface of a sphere
"""
if not hasattr(alt, '__len__'):
alt = np.array([alt])
viewer = np.zeros(shape=(3, len(alt)))
tangent = np.zeros_like(viewer)
viewer[0] = -(R+max_alt*2)
... | 49f4a1c4fe7267078cfac05af78c2fc850c1edfb | 21,085 |
from pathlib import Path
def load_datasets(parser, args):
"""Loads the specified dataset from commandline arguments
Returns:
train_dataset, validation_dataset
"""
args = parser.parse_args()
dataset_kwargs = {
"root": Path(args.train_dir),
}
source_augmentations = Compos... | 17f25443b34b9b6bc87c259c65d4af13b76b5303 | 21,086 |
def stock_total_deal_money():
"""
总成交量
:return:
"""
df = stock_zh_index_spot()
# 深证成指:sz399001,上证指数:sh00001
ds = df[(df['代码'] == 'sz399001') | (df['代码'] == 'sh000001')]
return ds['成交额'].sum() / 100000000 | 241c0080ed64acc21c1d8072befd168415184130 | 21,087 |
def _ls(dir=None, project=None, all=False, appendType=False, dereference=False, directoryOnly=False):
"""
Lists file(s) in specified MDSS directory.
:type dir: :obj:`str`
:param dir: MDSS directory path for which files are listed.
:type project: :obj:`str`
:param project: NCI project identi... | 7a26c9459381364ad145bab2b6230fd2037e5433 | 21,088 |
def uploadMetadata(doi, current, delta, forceUpload=False, datacenter=None):
"""
Uploads citation metadata for the resource identified by an existing
scheme-less DOI identifier (e.g., "10.5060/FOO") to DataCite. This
same function can be used to overwrite previously-uploaded metadata.
'current' and 'delta'... | 22902f2649f20d638ba61b8db7ff6a32821bf965 | 21,089 |
def one_away(string_1: str, string_2: str)-> bool:
"""DP, classic edit distance
funny move, we calculate the LCS and then substract from the len() of the biggest string in O(n*m)
"""
if string_1 == string_2: return False
@lru_cache(maxsize=1024)
def dp(s_1, s_2, distance=0):
"""standard ... | 754cd1b383d21935992ba95bde65bde5340a8ef8 | 21,090 |
def test(net, loss_normalizer):
"""
Tests the Neural Network using IdProbNet on the test set.
Args:
net -- (IdProbNet instance)
loss_normalizer -- (Torch.Tensor) value to be divided from the loss
Returns:
3-tuple -- (Execution Time, End loss value,
Model's predictio... | 4abdd1426545af6d093be2f549f6e2b8e86b3659 | 21,091 |
def scale_from_matrix(matrix):
"""Return scaling factor, origin and direction from scaling matrix.
"""
M = jnp.array(matrix, dtype=jnp.float64, copy=False)
M33 = M[:3, :3]
factor = jnp.trace(M33) - 2.0
try:
# direction: unit eigenvector corresponding to eigenvalue factor
w, V = jnp.linalg.eig(M33)
... | 1e6ef044b35ec4eff86764d9a222764c74977fb1 | 21,092 |
def get_fort44_info(NDX, NDY, NATM, NMOL, NION, NSTRA, NCL, NPLS, NSTS, NLIM):
"""Collection of labels and dimensions for all fort.44 variables, as collected in the
SOLPS-ITER 2020 manual.
"""
fort44_info = {
"dab2": [r"Atom density ($m^{-3}$)", (NDX, NDY, NATM)],
"tab2": [r"Atom tempe... | 0eca35ae512d3fd690124c45d5cde303d860ae0b | 21,093 |
def lens2memnamegen_first50(nmems):
"""Generate the member names for LENS2 simulations
Input:
nmems = number of members
Output:
memstr(nmems) = an array containing nmems strings corresponding to the member names
"""
memstr=[]
for imem in range(0,nmems,1):
if (imem < 10)... | 81ebbf1b17c56d604d8c6c9bc7bacd4a3093ec82 | 21,094 |
def initialize_settings(tool_name, source_path, dest_file_name=None):
""" Creates settings directory and copies or merges the source to there.
In case source already exists, merge is done.
Destination file name is the source_path's file name unless dest_file_name
is given.
"""
settings_dir = os... | c32e35f6323e2ae87c5d53a8b2e2c0d69a30c6e4 | 21,095 |
def get_stopword_list(filename=stopword_filepath):
""" Get a list of stopword from a file """
with open(filename, 'r', encoding=encoding) as f:
stoplist = [line for line in f.read().splitlines()]
return stoplist | 8578428ec387309907f428f3eec91a526f11167a | 21,096 |
def append_composite_tensor(target, to_append):
"""Helper function to append composite tensors to each other in the 0 axis.
In order to support batching within a fit/evaluate/predict call, we need
to be able to aggregate within a CompositeTensor. Unfortunately, the CT
API currently does not make this easy - es... | e7831319fffe3f35c47c192f5c5ffd6e7c13e182 | 21,097 |
def to_text(value):
"""Convert an opcode to text.
*value*, an ``int`` the opcode value,
Raises ``dns.opcode.UnknownOpcode`` if the opcode is unknown.
Returns a ``str``.
"""
return Opcode.to_text(value) | 85395ecdaa2fae4fc121072747401c114d7b4ed3 | 21,098 |
def prompt_merge(target_path,
additional_uris,
additional_specs,
path_change_message=None,
merge_strategy='KillAppend',
confirmed=False,
confirm=False,
show_advanced=True,
show_verbosi... | 16390cc74421d08bb0b764c9905a70dd30284609 | 21,099 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.