content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def categorical_iou(y_true, y_pred, target_classes=None, strict=True):
"""画像ごとクラスごとのIoUを算出して平均するmetric。
Args:
target_classes: 対象のクラスindexの配列。Noneなら全クラス。
strict: ラベルに無いクラスを予測してしまった場合に減点されるようにするならTrue、ラベルにあるクラスのみ対象にするならFalse。
"""
axes = list(range(1, K.ndim(y_true)))
y_classes = K.ar... | b79f399479127271c3af3ee9b28203622f8d17fe | 3,645,063 |
def convert_string(string: str, type: str) -> str:
"""Convert the string by [e]ncrypting or [d]ecrypting.
:param type: String 'e' for encrypt or 'd' for decrypt.
:return: [en/de]crypted string.
"""
hash_string = hash_()
map_ = mapping(hash_string)
if type.lower() == 'e':
output = e... | 824122fa035dcb164f21eadb5c0e840f8acd2914 | 3,645,064 |
def create_saml_security_context(token, private_key):
"""
Create a security context for SAML token based
authentication scheme
:type token: :class:`str`
:param token: SAML Token
:type private_key: :class:`str`
:param private_key: Absolute file path of the private key of the user
:rtyp... | 430e71697eb3e5b3df438f400a7f07ab8e936af7 | 3,645,065 |
def predictIsDeviceLeftRunning():
"""
Returns if the device is presumed left running without a real need
---
parameters:
name: -device_id
in: query
description: the device id for which the prediction is made
required: false
style: form
explode: true
... | 8a50962f3c52e100d79a74413df0d4bf8230bafd | 3,645,066 |
from typing import Optional
from typing import Callable
from pathlib import Path
def load(
source: AnyPath,
wordnet: Wordnet,
get_synset_id: Optional[Callable] = None,
) -> Freq:
"""Load an Information Content mapping from a file.
Arguments:
source: A path to an information content weigh... | 962bdfbe5d101bdeae966566c16d8a7216c36d8b | 3,645,067 |
from datetime import datetime
def iso_time_str() -> str:
"""Return the current time as ISO 8601 format
e.g.: 2019-01-19T23:20:25.459Z
"""
now = datetime.datetime.utcnow()
return now.isoformat()[:-3]+'Z' | 203617006175079181d702f7d7ed6d2974714f2e | 3,645,068 |
def mass(snap: Snap) -> Quantity:
"""Particle mass."""
massoftype = snap._file_pointer['header/massoftype'][()]
particle_type = np.array(
np.abs(get_dataset('itype', 'particles')(snap)).magnitude, dtype=int
)
return massoftype[particle_type - 1] * snap._array_code_units['mass'] | cf67d66f1e1a47f162b5e538444d2c406b377238 | 3,645,069 |
import torch
def batchify_rays(rays_flat, chunk=1024*32, random_directions=None, background_color=None, **kwargs):
"""Render rays in smaller minibatches to avoid OOM.
"""
all_ret = {}
for i in range(0, rays_flat.shape[0], chunk):
ret = render_rays(rays_flat[i:i+chunk], random_directions=random... | 9897575462e47f98016ebd0a2fcaee186c440f9a | 3,645,072 |
def extract_surfaces(pvol):
""" Extracts surfaces from a volume.
:param pvol: input volume
:type pvol: abstract.Volume
:return: extracted surface
:rtype: dict
"""
if not isinstance(pvol, BSpline.abstract.Volume):
raise TypeError("The input should be an instance of abstract.Volume")
... | cd2b24f200adf9f5ff29cc847693d57d450521ad | 3,645,073 |
def euler2quaternion( euler_angs ):
"""
Description
-----------
This code is directly from the following reference
[REF] https://computergraphics.stackexchange.com/questions/8195/how-to-convert-euler-angles-to-quaternions-and-get-the-same-euler-angles-back-fr
Conv... | 307385911573af8a6e65617a8b438ca680130b79 | 3,645,075 |
def run_server(server, thread=False, port=8080):
"""
Runs the server.
@param server if None, it becomes ``HTTPServer(('localhost', 8080), SimpleHandler)``
@param thread if True, the server is run in a thread
and the function returns right away,
... | 524b58f012a1029e52d845f40a20e2ae1f7f9c0a | 3,645,076 |
def validate(aLine):
"""
>>> validate(b"$GPGSA,A,2,29,19,28,,,,,,,,,,23.4,12.1,20.0*0F")
[b'GPGSA', b'A', b'2', b'29', b'19', b'28', b'', b'', b'', b'', b'', b'', b'', b'', b'', b'23.4', b'12.1', b'20.0']
>>> validate(b"$GPGSA,A,2,29,19,28,,,,,,,,,,23.4,") # doctest: +IGNORE_EXCEPTION_DETAIL
Traceb... | a8f302f0a03f567bc3c61930ecdf147ff9670b04 | 3,645,077 |
def matlabize(s):
"""Make string s suitable for use as a MATLAB function/script name"""
s = s.replace(' ', '_')
s = s.replace('.', '_')
s = s.replace('-', '_')
assert len(s) <= 63 # MATLAB function/script name length limitation
return s | 5dccb9497a3ee28dae5fb7de6e15a1fa02f144cf | 3,645,078 |
def getApiResults(case, installer, version, criteria):
"""
Get Results by calling the API
criteria is to consider N last results for the case success criteria
"""
results = json.dumps([])
# to remove proxy (to be removed at the end for local test only)
# proxy_handler = urllib2.ProxyHandler... | d54eaf785bc1e80e633cf3f6588f135c54425b79 | 3,645,079 |
def generate_noisy_gaussian(center, std_dev, height, x_domain, noise_domain,
n_datapoints):
"""
Generate a gaussian with some aspect of noise.
Input:
center = central x value
std_dev = standard deviation of the function
height = height (y-off set) of the ... | 5120bb23be1b98663b61ad67df0aa43c61ed1714 | 3,645,080 |
from typing import Tuple
def filter_group_delay(
sos_or_fir_coef: np.ndarray,
N: int = 2048,
fs: float = None,
sos: bool = True,
) -> Tuple[np.ndarray, np.ndarray]:
"""
Given filter spec in second order sections or (num, den) form, return group delay.
Uses method in [1], which is cited by ... | 9cdcf30db5f1308dac27ce057f392fb38d805f1f | 3,645,081 |
import re
def query():
"""Perform a query on the dataset, where the search terms are given by the saleterm parameter"""
# If redis hasn't been populated, stick some tweet data into it.
if redis_db.get("tweet_db_status") != "loaded":
tweet_scraper.add_tweets(default_num_tweets_to_try)
sale_ter... | 9cdb937d45b1314884afb0d53aee174ef160f8a8 | 3,645,082 |
def get_spec_res(z=2.2, spec_res=2.06, pix_size=1.8):
""" Calculates the pixel size (pix_size) and spectral resolution (spec_res) in
km/s for the MOCK SPECTRA.
arguments: z, redshift. spec_res, spectral resoloution in Angst. pixel_size
in sngst.
returns:
(pixel_size, spec_res) in km/s
"""
... | 597db8ce00c071624b0877fe211ab9b01ec889de | 3,645,083 |
def api_response(response):
"""Response generation for ReST API calls"""
# Errors present
if response.message:
messages = response.message
if not isinstance(messages, list):
messages = [messages]
# Report the errors
return Response({'errors': messages}, status=s... | f41bca36b1cabc6002f730b3b40170415baffc62 | 3,645,085 |
from tensorflow.python.training import moving_averages
def batch_norm(name, inpvar, decay=0.9, epsilon=1e-5, use_affine=True, param_dtype=__default_dtype__):
"""
Batch normalization.
:param name: operator name
:param inpvar: input tensor, of data type NHWC
:param decay: decay for moving average
... | 74565379d15d4ec7cfa647a4f7833328f2c86ac7 | 3,645,086 |
from typing import Callable
def _window_when(closing_mapper: Callable[[], Observable]) -> Callable[[Observable], Observable]:
"""Projects each element of an observable sequence into zero or
more windows.
Args:
source: Source observable to project into windows.
Returns:
An observable ... | d0f51f8385b2d45f1cbd64649953c312247644eb | 3,645,088 |
def generate_features(df):
"""Generate features for a stock/index based on historical price and performance
Args:
df(dataframe with columns "Open", "Close", "High", "Low", "Volume", "Adjusted Close")
Returns:
dataframe, data set with new features
"""
df_new = pd.DataFrame()
#... | ec64c9562287e0dd32b7cfd07c477acd8d799dc3 | 3,645,089 |
from typing import Dict
from typing import Union
from typing import Optional
def format_plate(barcode: str) -> Dict[str, Union[str, bool, Optional[int]]]:
"""Used by flask route /plates to format each plate. Determines whether there is sample data for the barcode and if
so, how many samples meet the fit to pi... | 5508ee508ef6d2a8329a2899bf9e90c9ac399874 | 3,645,090 |
def method_only_in(*states):
"""
Checks if function has a MethodMeta representation, calls wrap_method to
create one if it doesn't and then adds only_in to it from *states
Args:
*args(list): List of state names, like DefaultStateMachine.RESETTING
Returns:
function: Updated function... | 33fbd619deb4b2a1761b3bf7f860ed2ae728df44 | 3,645,091 |
import igraph
def to_igraph(adjacency_matrix:Image, centroids:Image=None):
"""
Converts a given adjacency matrix to a iGraph [1] graph data structure.
Note: the given centroids typically have one entry less than the adjacency matrix is wide, because
those matrices contain a first row and column repre... | e0cac1dd85b79b30e3f7e3139201b97e092603eb | 3,645,092 |
def Laplacian(src, ddepth, dst=None, ksize=1, scale=1, delta=0, borderType=cv2.BORDER_DEFAULT):
"""dst = cv.Laplacian( src, ddepth[, dst[, ksize[, scale[, delta[, borderType]]]]] )
Executes the Laplacian operator on hardware if input parameters fit to hardware constraints.
Otherwise the OpenCV Laplacian fun... | 88237f83ed9b2159829f4a9b194c18007699c1a9 | 3,645,093 |
def get_docptr(n_dw_matrix):
"""
Parameters
----------
n_dw_matrix: array-like
Returns
-------
np.array
row indices for the provided matrix
"""
return _get_docptr(n_dw_matrix.shape[0], n_dw_matrix.indptr) | 7a20ca17f16475d6fd836bb5b7b70221f5cf4378 | 3,645,094 |
def check_if_shift_v0(data, column_name, start_index, end_index, check_period):
""" using median to see if it changes significantly in shift """
period_before = data[column_name][start_index - check_period: start_index]
period_in_the_middle = data[column_name][start_index:end_index]
period_after = data[... | e73629dae7d6cce70b344f24acb98a3ae24c4e64 | 3,645,095 |
def opening2d(value, kernel, stride=1, padding="SAME"):
"""
erode and then dilate
Parameters
----------
value : Tensor
4-D with shape [batch, in_height, in_width, depth].
kernel : Tensor
Must have the same type as 'value'. 3-D with shape '[kernel_height, kernel_width, depth]... | b425735dacceac825b4394fdc72a744b168acc91 | 3,645,096 |
def convert_npy_mat(user_num, item_num, df):
"""
method of convert dataframe to numpy matrix
Parameters
----------
user_num : int, the number of users
item_num : int, the number of items
df : pd.DataFrame, rating dataframe
Returns
-------
mat : np.matrix, rating matrix
"""
... | 627fcc45a490be1554445582dc8a2312e25b1152 | 3,645,097 |
def user_enter_state_change_response():
"""
Prompts the user to enter a key event response.
nothing -> str
"""
return input('>> ') | 22da5cb99fa603c3dff04e8afd03cb9fae8210cd | 3,645,098 |
def call_worker(job_spec):
"""Calls command `cron_worker run <job_spec>` and parses the output"""
output = call_command("cron_worker", "run", job_spec)
status = exc_class_name = exc_message = None
if output:
result_match = RESULT_PATTERN.match(output)
if result_match:
status ... | 5a914c742319e2528b1668309ff57e507efd26bb | 3,645,099 |
def overlap(a, b):
"""check if two intervals overlap.
Positional arguments:
a -- First interval.
b -- Second interval.
"""
return a[1] > b[0] and a[0] < b[1] | 88860f46a94eb53f1d6f636211916dd828c83550 | 3,645,100 |
import warnings
import re
def contAvg_headpos(condition, method='median', folder=[], summary=False):
"""
Calculate average transformation from dewar to head coordinates, based
on the continous head position estimated from MaxFilter
Parameters
----------
condition : str
String contain... | 42b65ce84f7b303575113ca2d57f5b61841f8294 | 3,645,101 |
def scalar_prod_logp0pw_beta_basis_npf(pw, p0, DV, alpha):
"""
From normalized p_fact
Args:
pw: a batch of probabilities (row:word, column:chi)
DV: centered statistics (for p0, to be consistent)
p0: the central probability on which tangent space to project (row vector)
alpha... | be63a3bcd791be4ee116a1e9abbd10a455e10bfc | 3,645,103 |
from typing import List
from typing import Tuple
from datetime import datetime
from bs4 import BeautifulSoup
def get_seminars() -> List[Tuple[str, str, datetime, str]]:
"""
Returns summary information for upcoming ITEE seminars, comprising
seminar date, seminar title, venue, and an information link.
"... | c1f149fa1625492f60b81b7c987f839c9d14abf3 | 3,645,104 |
def cluster_hierarchically(active_sites,num_clusters=7):
"""
Cluster the given set of ActiveSite instances using a hierarchical algorithm.
Input: a list of ActiveSite instances
(OPTIONAL): number of clusters (default 7)
Output: a list of clusterings
(each clustering is a list of lists o... | e7ca3f8a9a098630a51944ae870b1beb730684dd | 3,645,105 |
def insert(table: _DMLTableArgument) -> Insert:
"""Construct an :class:`_expression.Insert` object.
E.g.::
from sqlalchemy import insert
stmt = (
insert(user_table).
values(name='username', fullname='Full Username')
)
Similar functionality is available via... | 70bd0accf66e72d6240f7cd586fc47c927e109a6 | 3,645,106 |
def parallelize_window_generation_imap(passed_args, procs=None):
"""Produce window files, in a parallel fashion
This method calls the get_win function as many times as sets of arguments
specified in passed_args. starmap is used to pass the list of arguments to
each invocation of get_win. The pool is cr... | 74cf5c8138ad1511c9aeae62a3f14c705a3735b5 | 3,645,107 |
def build_train(q_func, ob_space, ac_space, optimizer, sess, grad_norm_clipping=None,
scope="deepq", reuse=None, full_tensorboard_log=False):
"""
Creates the train function:
:param q_func: (DQNPolicy) the policy
:param ob_space: (Gym Space) The observation space of the environment
:... | 395899bdb0497db5f56d42bd968ad07117cf0126 | 3,645,108 |
def _make_global_var_name(element):
"""creates a global name for the MAP element"""
if element.tag != XML_map:
raise ValueError('Expected element <%s> for variable name definition, found <%s>' % (XML_map,element.tag))
base_name = _get_attrib_or_None(element,XML_attr_name)
if base_name is None:
... | 7a4c26ae3791ea0543a2690a61651604e727abf6 | 3,645,109 |
def list_user_images(user_id):
"""
Given a user_id, returns a list of Image objects scoped to that user.
:param user_id: str user identifier
:return: List of Image (messsage) objects
"""
db = get_session()
try:
imgs = [msg_mapper.db_to_msg(i).to_dict() for i in db.query(Image).filte... | 5a00ccae4fdea9417f26158d9042cc62a56e1013 | 3,645,110 |
def is_lower_cased_megatron(pretrained_model_name):
"""
Returns if the megatron is cased or uncased
Args:
pretrained_model_name (str): pretrained model name
Returns:
do_lower_cased (bool): whether the model uses lower cased data
"""
return MEGATRON_CONFIG_MAP[pretrained_model_na... | 6ff0954a35e19144e99aa0bdbbbeddc7542aad9d | 3,645,111 |
def decipher(string, key, a2i_dict, i2a_dict):
"""
This function is BASED on https://github.com/jameslyons/pycipher
"""
key = [k.upper() for k in key]
ret = ''
for (i, c) in enumerate(string):
i = i % len(key)
ret += i2a_dict[(a2i_dict[c] - a2i_dict[key[i]]) % len(a2i_dict)]
... | a414892f8ccf18ab5d3189b662b284939c931382 | 3,645,113 |
def keep_samples_from_pcoa_data(headers, coords, sample_ids):
"""Controller function to filter coordinates data according to a list
Parameters
----------
headers : list, str
list of sample identifiers, if used for jackknifed data, this
should be a list of lists containing the sample ide... | c33eaf6c593fcebc09e98ec479ca0505c52424c8 | 3,645,114 |
import platform
def get_default_command() -> str:
"""get_default_command returns a command to execute the default output of g++ or clang++. The value is basically `./a.out`, but `.\a.exe` on Windows.
The type of return values must be `str` and must not be `pathlib.Path`, because the strings `./a.out` and `a.... | d06abdefab189f9c69cba70d9dab25ce83bebc75 | 3,645,115 |
from skymaps import Band
def roi_circle(roi_index, galactic=True, radius=5.0):
""" return (lon,lat,radius) tuple for given nside=12 position
"""
sdir = Band(12).dir(roi_index)
return (sdir.l(),sdir.b(), radius) if galactic else (sdir.ra(),sdir.dec(), radius) | 303c288749e3bd9ee63c95e79ef5460468d2cea0 | 3,645,116 |
from typing import List
def find_by_user_defined_key(user_defined_key: str) -> List[models.BBoundingBoxDTO]:
"""Get a list of bounding boxes by a user-defined key."""
res_json = BoundingBoxes.get('query/userdefinedkey/{}'.format(user_defined_key))
return list(map(models.BBoundingBoxDTO.from_dict, res_json... | a60137fdc43b04c1404eaeae021f61381c39c761 | 3,645,117 |
def object_type(r_name):
"""
Derives an object type (i.e. ``user``) from a resource name (i.e. ``users``)
:param r_name:
Resource name, i.e. would be ``users`` for the resource index URL
``https://api.pagerduty.com/users``
:returns: The object type name; usually the ``type`` property of... | b74e373691edf8a8b78c2a3ff5d7b9666504330a | 3,645,118 |
import traceback
def create_comment(args, global_var):
"""
创建一条新评论 (每天只能允许创建最多 1000 条评论)
-------------
关于 uuid:
1. raw_str 就用 data["content"]
2. 由于生成的 comment_id 格式中有中划线, 很奇怪, 所以建议删掉: uuid = "-".join(uuid)
"""
can_create = hit_daily_comment_creation_threshold(global_var)
if not c... | d8596febf2a020357654291952e447f175f2fe20 | 3,645,119 |
from fairseq.models.bart import BARTModel
import torch
def get_bart(folder_path, checkpoint_file):
"""
Returns a pretrained BART model.
Args:
folder_path: str, path to BART's model, containing the checkpoint.
checkpoint_file: str, name of BART's checkpoint file (starting from BART's folde... | 504a242d24946761f2a880db66e1955752b89677 | 3,645,121 |
def _mixed_s2(x, filters, name=None):
"""Utility function to implement the 'stride-2' mixed block.
# Arguments
x: input tensor.
filters: a list of filter sizes.
name: name of the ops
# Returns
Output tensor after applying the 'stride-2' mixed block.
"""
if len(filte... | b4260c1b2a9e5c38a6c48baab611ac2e0d73c888 | 3,645,123 |
from typing import Union
from typing import Type
def get_convertor(cls: Union[Type, str]) -> Convertor:
"""Returns Convertor for data type.
Arguments:
cls: Type or type name. The name could be simple class name, or full name that includes
the module name.
Note:
When `cls` is... | c70ce0a032efc031de67fc965a6984779dd635e7 | 3,645,124 |
def _is_mchedr(filename):
"""
Checks whether a file format is mchedr
(machine-readable Earthquake Data Report).
:type filename: str
:param filename: Name of the mchedr file to be checked.
:rtype: bool
:return: ``True`` if mchedr file.
.. rubric:: Example
>>> _is_mchedr('/path/to/m... | f8d5521cfd6ebcdf490af41877e865fb185f0f7c | 3,645,125 |
import math
def ddr3_8x8_profiling(
trace_file=None,
word_sz_bytes=1,
page_bits=8192, # number of bits for a dram page/row
min_addr_word=0,
max_addr_word=100000
):
"""
this code takes non-stalling dram trace and reorganizes the trace to meet the bandwidth requirement.
currently, it doe... | 6a3369a79ae77e6f984b5250e17a7e79393e18d2 | 3,645,126 |
def get_sites_by_latlon(latlon, filter_date='', **kwargs):
"""Gets list of sites from BETYdb, filtered by a contained point.
latlon (tuple) -- only sites that contain this point will be returned
filter_date -- YYYY-MM-DD to filter sites to specific experiment by date
"""
latlon_api_arg = "%s,%... | 40c9bcbd8884d287a8bbdf233376f27c6c2d041e | 3,645,127 |
import logging
def get_context(book, chapter, pharse):
"""
Given book, chapter, and pharse number, return the bible context.
"""
try:
context = repository['{} {}:{}'.format(book, chapter, pharse)]
return context
except KeyError:
bookname = bookid2chinese[book]
phars... | a9d261a780b57db06af921c11001786107886b68 | 3,645,128 |
from typing import OrderedDict
def _compare_namelists(gold_namelists, comp_namelists, case):
###############################################################################
"""
Compare two namelists. Print diff information if any.
Returns comments
Note there will only be comments if the namelists were... | 7a4b8fc1fa23f54bf1015c2cfd7b4b05da33b5b4 | 3,645,131 |
def directMultiCreate( data, cfg_params='', *, dtype='',
doInfo = True, doScatter = True, doAbsorption = True ):
"""Convenience function which creates Info, Scatter, and Absorption objects
directly from a data string rather than an on-disk or in-memory
file. Such usage obviously... | 1fe6262c0f59c836d1edcc7555b30f3182ceb2e0 | 3,645,132 |
def write_date_json(date: str, df: DataFrame) -> str:
""" Just here so we can log in the list comprehension """
file_name = f"pmg_reporting_data_{date}.json"
print(f"Writing file {file_name}")
df.to_json(file_name, orient="records", date_format="iso")
print(f"{file_name} written")
return file... | 7af4d44559b28c92f2df409cb59abd441f29dde5 | 3,645,133 |
def fit_composite_peak(bands, intensities, locs, num_peaks=2, max_iter=10,
fit_kinds=('lorentzian', 'gaussian'), log_fn=print,
band_resolution=1):
"""Fit several peaks to a single spectral feature.
locs : sequence of float
Contains num_peaks peak-location guesses,
... | b6cffef481fb158cf019831db716fd14ca8d6a86 | 3,645,134 |
def param():
"""
Create a generic Parameter object with generic name, description and no value defined
"""
return parameter.Parameter("generic_param",template_units.kg_s,"A generic param") | 1062351f477405a8be66ea1b3e10ae1f8a6403c7 | 3,645,135 |
def extract_filter(filter_path):
"""Given a path to the weka's filter file,
return a list of selected features."""
with open(filepath) as f:
lnum = 0
for line in f:
lnum += 1 #pointer to the next line to read
if line.strip().startswith('Selected attributes:'):
... | cc8e91ac268cdeb4d9a0e4c72eeb50659342cda6 | 3,645,136 |
def convert_to_roman_numeral(number_to_convert):
"""
Converts Hindi/Arabic (decimal) integers to Roman Numerals.
Args:
param1: Hindi/Arabic (decimal) integer.
Returns:
Roman Numeral, or an empty string for zero.
"""
arabic_numbers = (1000, 900, 500, 400, 100, 90, 50, 40, 10, 9,... | f970517a7c2d1ceb13ec025d6d446499ce5c21ff | 3,645,137 |
def rotate_xyz(vector: Vector, angle_x: float = 0., angle_y: float = 0., angle_z: float = 0.):
"""
Rotate a 3d-vector around the third (z) axis
:param vector: Vector to rotate
:param angle_x: Rotation angle around x-axis (in degrees)
:param angle_y: Rotation angle around y-axis (in degrees)
:pa... | efe98080d3354713dfc4b7b26a19b21a1551ab69 | 3,645,138 |
def get_project_from_data(data):
"""
Get a project from json data posted to the API
"""
if 'project_id' in data:
return get_project_by_id(data['project_id'])
if 'project_slug' in data:
return get_project_by_slug(data['project_slug'])
if 'project_name' in data:
return get_... | 6ab01c4273248310ecd780fa24d6541fe1e9b0ad | 3,645,139 |
def _from_atoms_and_bonds(atm_dct, bnd_dct):
""" Construct a molecular graph from atom and bond dictionaries.
format:
gra = (atm_dct, bnd_dct)
:param atm_dct: atom dictionary
:type atm_dct: dict
:param bnd_dct: bond dictionary
:type bnd_dct: dict
:rtype:... | 0bd2d37442e2a141d9a0f81f77b6b45c5b82c06a | 3,645,140 |
def __getattr__(item):
"""Ping the func map, if an attrib is not registered, fallback to the dll"""
try:
res = func_map[item]
except KeyError:
return dll.__getattr__(item)
else:
if callable(res):
return res # Return methods from interface.
else:
r... | 7b93dd68ce4b658226c0f6c072bb3cb51be82206 | 3,645,141 |
def seed_random_state(seed):
"""
Turn seed into np.random.RandomState instance
"""
if (seed is None) or (isinstance(seed, int)):
return np.random.RandomState(seed)
elif isinstance(seed, np.random.RandomState):
return seed
raise ValueError("%r cannot be used to generate numpy.rand... | 61639222ab74ffbb3599c5d75ee0c669db463965 | 3,645,142 |
def _normalize_dashboard_link(link, request):
"""
Given a dashboard link, make sure it conforms to what we expect.
"""
if not link.startswith("http"):
# If a local url is given, assume it is using the same host
# as the application, and prepend that.
link = url_path_join(f"{reque... | 57ff43c2b364fbce94ef06447a79eeec29c06b90 | 3,645,143 |
async def delete(category_id: int):
"""Delete category with set id."""
apm.capture_message(param_message={'message': 'Category with %s id deleted.', 'params': category_id})
return await db.delete(category_id) | 2c1aa6e9f40006d5c07fe94a9838b5f2709bc781 | 3,645,144 |
def to_canonical_name(resource_name: str) -> str:
"""Parse a resource name and return the canonical version."""
return str(ResourceName.from_string(resource_name)) | e9e972a8bc2eb48751da765b65ea8881e033d05c | 3,645,146 |
import six
def apply_query_filters(query, model, **kwargs):
"""Parses through a list of kwargs to determine which exist on the model,
which should be filtered as ==, and which should be filtered as LIKE
"""
for k, v in six.iteritems(kwargs):
if v and hasattr(model, k):
column = ge... | 1a7885ab55645d6a00f35668718bc119a8b18939 | 3,645,147 |
def bytes_to_b64_str(bytestring: bytes) -> str:
"""Converts random bytes into a utf-8 encoded string"""
return b64encode(bytestring).decode(config.security.ENCODING) | cff8e979b3d5578c39477e88f2895ebbb07f794e | 3,645,148 |
def read_event_analysis(s:Session, eventId:int) -> AnalysisData:
"""read the analysis data by its eventId"""
res = s.query(AnalysisData).filter_by(eventId=eventId).first()
return res | 4dba5e7489e6cee28312710fa233b7066d04b995 | 3,645,149 |
def eval_semeval2012_analogies(
vectors, weight_direct, weight_transpose, subset, subclass
):
"""
For a set of test pairs:
* Compute a Spearman correlation coefficient between the ranks produced by vectors and
gold ranks.
* Compute an accuracy score of answering MaxDiff questions.... | f8b13ef5520129e753024bc5ec3d25d7ab24ccee | 3,645,150 |
def get_typefromSelection(objectType="Edge", info=0):
""" """
m_num_obj, m_selEx, m_objs, m_objNames = get_InfoObjects(info=0, printError=False)
m_found = False
for m_i_o in range(m_num_obj):
if m_found:
break
Sel_i_Object = m_selEx[m_i_o]
Obj_i_Object = m_objs[m_i_o]... | a2e55139219417b05fc9486bb9880bc6d17e1777 | 3,645,152 |
def load_file(file_path, mode='rb', encoder='utf-8'):
"""
Loads the content of a given filename
:param file_path: The file path to load
:param mode: optional mode options
:param encoder: the encoder
:return: The content of the file
"""
with xbmcvfs.File(xbmcvfs.translatePath(file_path), ... | 118f18fd651a332728e71d0b7fac5e57ad536f4b | 3,645,153 |
def centcalc_by_weight(data):
"""
Determines the center (of grtavity) of a neutron beam on a 2D detector by weigthing each pixel with its count
--------------------------------------------------
Argments:
----------
data : ndarray : l x m x n array with 'pixel' - data to weight ove... | 6d3bb14820bb11ac61c436055d723bbd49f77740 | 3,645,154 |
import textwrap
def public_key():
""" returns public key """
return textwrap.dedent('''
-----BEGIN RSA PUBLIC KEY-----
MIIBCgKCAQEAwBLTc+75h13ZyLWlvup0OmbhZWxohLMMFCUBClSMxZxZdMvyzBnW
+JpOQuvnasAeTLLtEDWSID0AB/EG68Sesr58Js88ORUw3VrjObiG15/iLtAm6hiN
BboTqd8jgWr1yC3LfNSKJk82qQzH... | 4d27c3e72714bccd885178c05598f0f1d8d7914d | 3,645,157 |
import pickle
import tqdm
def fetch_WIPOgamma(subset, classification_level, data_home, extracted_path, text_fields = ['abstract', 'description'], limit_description=300):
"""
Fetchs the WIPO-gamma dataset
:param subset: 'train' or 'test' split
:param classification_level: the classification level, eith... | 05d3f19950321c5e94abf846bd7fab2d9b905f39 | 3,645,158 |
from typing import Optional
import requests
def latest_maven_version(group_id: str, artifact_id: str) -> Optional[str]:
"""Helper function to find the latest released version of a Maven artifact.
Fetches metadata from Maven Central and parses out the latest released
version.
Args:
group_id (... | 1c5f3b3e683e5e40f9779d53d93dad9e1397e25d | 3,645,159 |
def zeropoint(info_dict):
"""
Computes the zero point of a particular system configuration
(filter, atmospheric conditions,optics,camera).
The zeropoint is the magnitude which will lead to one count per second.
By definition ZP = -2.5*log10( Flux_1e-_per_s / Flux_zeromag ),
where Flux_1e-_per_s ... | 0deba397aa14226a45af7a1acca6f51ec846083b | 3,645,160 |
def model_comp(real_data, deltaT, binSize, maxTimeLag, abc_results1, final_step1, abc_results2, final_step2,\
model1, model2, distFunc, summStat_metric, ifNorm,\
numSamplesModelComp, eval_start = 3, disp1 = None, disp2 = None):
"""Perform Baysian model comparison with ABC fits from m... | 060fa9dcd133363b93dd22353eee5c47e3fd90dd | 3,645,161 |
def unwrap(*args, **kwargs):
"""
This in a alias for unwrap_array, which you should use now.
"""
if deprecation_warnings:
print('Use of "unwrap" function is deprecated, the new name '\
' is "unwrap_array".')
return unwrap_array(*args, **kwargs) | 156b5607b3b76fff66ede40eed79ca5cf74b1313 | 3,645,162 |
def solve():
"""solve form"""
if request.method == 'GET':
sql="SELECT g.class, p.origin, p.no, p.title, p.address FROM GIVE g, PROBLEM p WHERE g.origin=p.origin AND g.no=p.no AND class = 1"
cursor.execute(sql)
week1=[]
for result in cursor.fetchall():
week1.append({
"class":result['class'],
"origin... | 4d1d117b686ef4bb265b9fcc2185f07351710f49 | 3,645,163 |
import re
def build_path(entities, path_patterns, strict=False):
"""
Constructs a path given a set of entities and a list of potential
filename patterns to use.
Args:
entities (dict): A dictionary mapping entity names to entity values.
path_patterns (str, list): One or more filename p... | 120811c5560fabe48e10f412c0b3c0ab3592a887 | 3,645,164 |
def schedule_compensate():
"""
swagger-doc: 'schedule'
required: []
req:
course_schedule_id:
description: '课程id'
type: 'string'
start:
description: '课程开始时间 format YYYY-mm-dd HH:MM:ss.SSS'
type: 'string'
end:
description: '课程结束时间 in sql format YYY... | 7c3a14af27287e64535d7b9150531d8646cb0cfe | 3,645,165 |
def parse(xml):
"""
Parse headerdoc XML into a dictionary format.
Extract classes, functions, and global variables from the given XML output
by headerdoc. Some formatting and text manipulation takes place while
parsing. For example, the `@example` is no longer recognized by headerdoc.
`parse()` will extract exam... | f130a7b457d3b347153a3ea013f69a11dc3859c2 | 3,645,166 |
def getSolventList():
"""
Return list of solvent molecules for initializing solvation search form.
If any of the Mintz parameters are None, that solvent is not shown in the list since it will cause error.
"""
database.load('solvation', '')
solvent_list = []
for index, entry in database.solva... | ea202459ac69b02d362c422935e396be04e7ec30 | 3,645,168 |
import random
def subset_samples(md_fp: str, factor: str, unstacked_md: pd.DataFrame,
number_of_samples: int, logs:list) -> pd.DataFrame:
"""
Subset the metadata to a maximum set of 100 samples.
! ATTENTION ! In case there are many columns with np.nan,
these should be ... | 36b99aaecf7fc67b4a5809bb00758b158d753997 | 3,645,169 |
def _process_image(filename, coder):
"""Process a single image file.
Args:
filename: string, path to an image file e.g., '/path/to/example.JPG'.
coder: instance of ImageCoder to provide TensorFlow image coding utils.
Returns:
image_buffer: string, JPEG encoding of RGB image.
height:... | 2b5c78a6b641ce31aed3f80590dcf6dbe3a36baa | 3,645,170 |
def to_rna_sequences(model):
"""
Convert all the sequences present in the model to RNA.
:args dict model: Description model.
"""
for seq, path in yield_sub_model(model, ["sequence"]):
set_by_path(model, path, str(Seq(seq).transcribe().lower()))
return model | 8a0929e631e6d162f47ba1773975116b0e2caff4 | 3,645,171 |
def rest_get_repositories(script, project=None, start=0, limit=50):
"""
Gets a list of repositories via REST
:param script: A TestScript instance
:type script: TestScript
:param project: An optional project
:type project: str
:param start: The offset to start from
:type start: int
:p... | 772b1682ba3de11b98d943f4a768386b7907b1d9 | 3,645,172 |
def clean_float(input_float):
"""
Return float in seconds (even if it was a timestamp originally)
"""
return (timestamp_to_seconds(input_float)
if ":" in str(input_float) else std_float(input_float)) | 8ce6ca89b40750bb157d27a68631ddd64a824f3a | 3,645,173 |
def resize(
image,
output_shape,
order=1,
mode="constant",
cval=0,
clip=True,
preserve_range=False,
anti_aliasing=False,
anti_aliasing_sigma=None,
):
"""A wrapper for Scikit-Image resize().
Scikit-Image generates warnings on every call to resize() if it doesn't
receive the rig... | 21273e385e892e21e6fb40241d9c430b6f41ba3d | 3,645,174 |
def get_subsystem_fidelity(statevector, trace_systems, subsystem_state):
"""
Compute the fidelity of the quantum subsystem.
Args:
statevector (list|array): The state vector of the complete system
trace_systems (list|range): The indices of the qubits to be traced.
to trace qubits... | 13d3ef7fc3e7d414fe6b936f839c42321a5e0982 | 3,645,175 |
import requests
def jyfm_data_coke(indicator="焦炭总库存", headers=""):
"""
交易法门-数据-黑色系-焦炭
:param indicator: ["焦企产能利用率-100家独立焦企产能利用率", "焦企产能利用率-230家独立焦企产能利用率",
"焦炭日均产量-100家独立焦企焦炭日均产量", "焦炭日均产量-230家独立焦企焦炭日均产量", "焦炭总库存",
"焦炭焦企库存-100家独立焦企焦炭库存", "焦炭焦企库存-230家独立焦企焦炭库存", "焦炭钢厂库存", "焦炭港口库存", "焦企焦化利润"]
:typ... | 23f1c0cad5cb93953f5d5745f0c3e14aedd51fd8 | 3,645,176 |
from typing import Tuple
from typing import Any
def generate_index_distribution(
numTrain: int, numTest: int, numValidation: int, params: UQDistDict
) -> Tuple[Any, ...]:
"""
Generates a vector of indices to partition the data for training. NO
CHECKING IS DONE: it is assumed that the data could be par... | f3c35d5c99a3f79b40f3c7220519152b85fe679d | 3,645,177 |
def generacionT (v, m):
"""
Signature of a message with hash, hashed. Here we have to use the private key.
Parameters:
m (int): Number of oil
v (int): Number of vinager
Returns:
T (matrix): Matrix with dimension nxn
"""
#Matriz de distorsion
T = []
n = v + m
for i in range(n):
... | 6fd4d9f8ebeea5f422c937b3b92c5c5134ffd541 | 3,645,178 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.