content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def _valid_dimension_name(name):
"""Check if given dimension name is valid for PRMS.
:param str name: dimension name
:returns: True if dimension name is valid otherwise False
:rtype: bool
"""
return name in DIMENSION_NAMES | d80d044eccf9aa7fc525c96944c32325592d9b0b | 45,200 |
from typing import List
def construct_relative_positions(pos: int, max_length: int) -> List[int]:
"""Construct relative positions to a specified pos
Args:
pos: the pos that will be `0`
max_length: max sequence length
Returns:
a list of relative positions
Raises:
Valu... | 152c59d288f797ef87f9e0dbf1b415b71f1fe9e7 | 45,201 |
def get_jira_task(req_sheet, row_num):
""" Accessor for JIRA Key
Args:
req_sheet: A variable holding an Excel Workbook sheet in memory.
row_num: A variable holding the row # of the data being accessed.
Returns:
A string value of the Notes
"""
return (req_sheet['F' + str(r... | e96a2d7f09f6d723795f6d24df231c332a19d628 | 45,202 |
import time
def make_Palomar_pupil(N, apRad, sp_thickness=0.0127, write=False, plot=False, spiders=True, obscuration=True):
"""
Make Palomar pupil
:param N:
:param apRad:
:return:
"""
outer_diameter = 5.09
inner_diameter = 1.83
#sp_thickness = 0.0127
Rin = apRad*inner_diameter... | 6a394acc478da21b1dc545ab8c3cbfde72fbc57c | 45,203 |
def plot_grid(lon,lat,
title_string = 'N/A',
meridians_delta = 15,
parallels_delta = 15,
same_figure = False,
figsize = None,
file_name = None,
dpi = 80,
skip = 5,
return_map = False,
marker = '+'
):
"""Function to plot grids similar to those generated by WPS
Modified 27/01/08: Minor ... | ee06ac2804539a45d65114f72708ce3aa85ed4be | 45,204 |
import subprocess
import os
def score(molfile1, molfile2, path_to_lsalign='/data/rsg/chemistry/yangk/LSalign/src'):
"""
LSalign similarity score for two molecules, each in a separate molfile whose path is given as input.
"""
with open('tmp.txt', 'w') as f:
subprocess.call([os.path.join(path_to... | 42a12c1b88d14793f13068fcdd097a5fb51cddbf | 45,205 |
import pathlib
def _match_path(p1, p2):
"""Compare two paths from right to left and return True if they could refer
to the same file.
As a special case, if the second argument is None, or empty, it is always
considered a match. This simplifies query logic when the target does not
have a path comp... | 7935e4312c444c9e2d0ee62611e1db5d6af210ad | 45,206 |
import tempfile
import os
import shutil
def get_consensus_data(issue, project_path, consensus=False):
"""Get full data for one issue and project path.
Checks out the commit locally, reads the hunks from the db and pre-labels everything.
"""
commits = []
folder = tempfile.mkdtemp()
git.repo.b... | 6f29de1be76c1c740d707a2b968d3c00d0e0784a | 45,207 |
def submit(host, entity_class, body):
"""
Negotiate submitting the data for an entity to the target service.
:param host: host url
:type host: str
:param entity_class: which entity class is being sent
:type entity_class: class
:param body: map between entity keys and values
:type body: ... | b450a396df3354af288128538c94b8772181e7c1 | 45,208 |
import re
def note_name_to_number(note_name):
"""Converts a note name in the format
``'(note)(accidental)(octave number)'`` (e.g. ``'C#4'``) to MIDI note
number.
``'(note)'`` is required, and is case-insensitive.
``'(accidental)'`` should be ``''`` for natural, ``'#'`` for sharp and
``'!'`` or... | 22395fd81f4a66592d4292d87292f709fa34ef13 | 45,209 |
def determine_temps_for_date_range(start, end):
"""Return a JSON list of the minimum temperature, the average temperature, and the max temperature for a given start or start-end range."""
"""When given the start only, calculate TMIN, TAVG, and TMAX for all dates greater than and equal to the start date."""
... | e44d339e58218e3c8d54c7e0bbb1a094dfc38177 | 45,210 |
def is_acceptable_mutant(client_bugzoo: bugzoo.Client,
client_boggart: boggart.Client,
snapshot: bugzoo.Bug,
mutation: boggart.Mutation
) -> bool:
"""
Determines whether a given mutant is suitable for use in a gr... | 1bbaabfa084b973a5ddb2451f28bf2cca7efe814 | 45,211 |
def scan_coordinate(rxn, zma):
""" Obtain the scan coordinates
:param rxn: a hydrogen migration Reaction object
"""
return SCAN_COORD_DCT[rxn.class_](rxn, zma) | 81953983f49e7a5965bbc5bfe0918978c8e7ff40 | 45,212 |
import argparse
def create_parent_parser(prog_name):
"""
Create parent parser
Args:
prog_name (str): program name
Returns:
parser: parent argument parser
Raises:
DistributionNotFound: version of family not found
"""
parent_parser = argparse.ArgumentParser(prog=p... | 48cf982799d68ead1db28a95cf5d816a5cd2873c | 45,213 |
def rescaleImage(image, output_size=128, scale=1 / 255.0):
"""Rescale the image in a sample to a given size.
Args:
output_size (tuple or int): Desired output size. If tuple, output is
matched to output_size. If int, smaller of image edges is matched
to output_size keeping aspect ... | 4fedf92940daba680b88206b8271b2756c3a7ba9 | 45,214 |
import datasets
def generate_and_write_mol_dataset(task_type: tasks.Task):
"""Generate all variables and optionally files needed for a molecular task."""
task = tasks.get_task(task_type)
use_h = task_type == tasks.Task.crippen
use_data_aug = isinstance(
task.task_type,
tasks.BinaryClas... | aa88f0d2f2ff329fe3a0418e386841df2caea365 | 45,215 |
def test_run(ray_start_2_cpus):
"""Tests that Train can be run without any specific backends."""
num_workers = 2
key = "value"
value = 1
config = TestConfig()
def train_func():
checkpoint = train.load_checkpoint()
train.report(**checkpoint)
train.save_checkpoint(**checkp... | 61e52c62a71bd69945f3918375da1f9e857b0af7 | 45,216 |
def import_files(configuration):
"""
Import trades from configured files.
"""
return CsvOrderImporter(configuration).import_orders() | f20a29ea921a8747d33e2ffd1975c3a3d9362e86 | 45,217 |
def image_targets_bottom(x, model_hparams, vocab_size):
"""Bottom transformation for target images."""
pixel_embedding_size = 64
inputs = x
with tf.variable_scope("image_modality"):
if not tf.executing_eagerly():
tf.summary.image(
"targets_bottom",
common_layers.tpu_safe_image_summ... | 80b824e17dbf96b0a91702a7bddf3a86e0ff9a98 | 45,218 |
def _GetEventTriggerEventParams(trigger_event, trigger_resource):
"""Get the args for creating an event trigger.
Args:
trigger_event: The trigger event
trigger_resource: The trigger resource
Returns:
A dictionary containing trigger_provider, trigger_event, and
trigger_resource.
"""
trigger_pr... | 4b961910e4d31107b128db97a680cd7e390e87ed | 45,219 |
def pie_chart(start_date, end_date):
# select date range
"""
Presents the day of the week proportion summary of the energy consumed by the appliances in the house.
Parameters
----------
df : pd.DataFrame(selected_data)
Groups the initial dataframe by day_of_week.
start_date : start... | 3cfc55936d0842f9a918fb52cd3729854c52f819 | 45,220 |
def _propose_rois_tpu(scores,
boxes,
anchor_boxes,
height,
width,
scale,
rpn_pre_nms_topn,
rpn_post_nms_topn,
rpn_nms_threshold,
... | a203f8ef6ae52b800632a363fa98f4b80b9476b0 | 45,221 |
import re
def has_text_an_image(text):
"""
:param text: String with base64 data
:return: true if text has base64 data otherwise false
"""
regex_to_extract = r'data:image.+\"'
return re.search(regex_to_extract, text) | c1d23738cc2f8f415a059a51b647d17157474655 | 45,222 |
import os
def grab_dir(inpath, outdir=None, r=False):
"""
Grabs all image files in a directory
:param inpath: path to directory of desired files
:param outdir: path to output csv directory, to check for existing images
:param r: Recursively grab images from all subdirectories as well
:return: ... | 46e17c69e44d70b8f6a1490584e71d7a6bf86b7d | 45,223 |
def post(url, data={}, headers={}, files=None, cookies=None, auth=None, **kwargs):
"""Sends a POST request. Returns :class:`Response` object.
:param url: URL for the new :class:`Request` object.
:param data: (optional) Dictionary of POST data to send with the :class:`Request`.
:param headers: (optional... | 2cab2601f3a1321188b46c98e970b0989fc23ebd | 45,224 |
def _get_max(lhs, rhs):
"""Get max value"""
if lhs < 0:
return lhs
if rhs < 0:
return rhs
return max(lhs, rhs) | 244c9401a4f578a4cc4dbdf5d476bc15fdcf054a | 45,225 |
def csr_matmat(data, indices, indptr, B, *, shape, transpose=False):
"""Product of CSR sparse matrix and a dense matrix.
Args:
data : array of shape ``(nse,)``.
indices : array of shape ``(nse,)``
indptr : array of shape ``(shape[0] + 1,)`` and dtype ``indices.dtype``
B : array of shape ``(shape[0]... | 0c43f938cbcc532d728d1b23365f2301b54cf7b5 | 45,226 |
import os
def create_output_dir_for_chromosome(output_dir, chr_name):
"""
Create an internal directory inside the output directory to dump chromosomal summary files
:param output_dir: Path to output directory
:param chr_name: chromosome name
:return: New directory path
"""
path_to_dir = ou... | 118ea1a6a7d1c0c5616fbf83a9e471eb8691fe27 | 45,227 |
def simplify_elaspic_data(data) -> DataFrame:
"""
Given ELASPIC results data, simplify it into three columns: "UniProt_ID", "Mutation", "Interactor_UniProt_ID".
"""
data = data[["UniProt_ID", "Mutation", "Interactor_UniProt_ID"]].copy(deep=True)
return data | e9c6ba46d076f81faa2cfe84e146e3b06315a2a3 | 45,228 |
import io
def pickle_load(content, safe_to_import=None):
"""
**pickle_load**
Load the pickled content. content should be a bytes object.
**Parameters**
content : Bytes of pickled object. It needs to have Delta header in it that is
separated by a newline character from the rest of the pic... | 13c392a3489f60c8039a327107cdfa2607c973a5 | 45,229 |
def import_string(dotted_path: str):
"""
Import a dotted module path and return the attribute/class designated by the
last name in the path. Raise ImportError if the import failed.
"""
try:
module_path, class_name = dotted_path.rsplit(".", 1)
except ValueError as err:
raise Impor... | d4c7f70111f2333d992bfdcc84f5624def0fae17 | 45,230 |
def get_new_ids(index, playlist_name, client):
"""
Gets a list of youtube videoIDs that are in the Elasticsearch index but not
in the Youtube playlist
"""
playlist_id = get_playlist_id(playlist_name, client)
# Force evaluation of scan here since it can throw an exception if done
# lazily (El... | f31c5567fb239e7720528d55fdecb062c01b7568 | 45,231 |
def process_articles(articles_list):
"""Function that processes the article results and transforms them to a list of Article Objects"""
articles_results = []
for article in articles_list:
author = article.get("author")
article_title = article.get("title")
article_description = articl... | ffa2c6094d281e21aabbb48b4b1b52d3488f4e91 | 45,232 |
def delete_vocabulary(word_id: int) -> str:
"""削除する"""
slack_msg = "該当する番号は見つからなかったっぽ!"
with VocabularyDatabase() as v_d:
result = v_d.get_word_list()
cnt = 1
for row in result:
row_id, _ = row
if cnt == word_id:
delete_id = row_id
... | 79f960cd85a1f0b09b6e94b341a88634364ea5ca | 45,233 |
def regnety160(**kwargs):
"""
RegNetY-16GF model from 'Designing Network Design Spaces,' https://arxiv.org/abs/2003.13678.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for... | db0c63e23ec12531f7824f97ab64e57459c93d57 | 45,234 |
import codecs
def unicode_open(filename, *args, **kwargs):
"""
Opens a file with UTF-8 encoding, in a Python 2- and 3-compatible way.
:param filename: Name of file to open.
:param *args: Optional args to be passed on to `open()`.
:param **kwargs: Optional kwargs to be passed on to `open()`.
"... | 49616adedd6dff5b04082de9e42ce54f8384ba86 | 45,235 |
def tupled_argmax(a):
"""
Argmax that returns an index tuple. Note that `numpy.argmax` will return a
scalar index as if you had flattened the array.
Parameters
----------
a : array_like
Input array.
Returns
-------
index : tuple
Tuple of index, even if `a` is one-di... | f84e60e8d8fddc0d114a170c74db667f9602926b | 45,236 |
import collections
def flood_fill(board, start_pos, allow_start_in_occupied_cell=False):
""" Flood fill is an algorithm that expands from a starting position into adjacent
vacant cells. Returns the set of all vacant cells found.
If allow_start_in_occupied_cell is True, the flood fill start position may b... | d5c0c535c55c025d92ddb3a6cdd1fae2cd58e8f8 | 45,237 |
def record_permission_factory(record=None, action=None):
"""Record permission factory."""
return RecordPermission.create(record, action) | 5b59c5f830e3908eefb5209224812ee765342d71 | 45,238 |
def create_parameter(name, **kwargs):
"""Create ArcPy parameter object using an attribute mapping.
Note that this doesn't check if the attribute exists in the default
parameter instance. This means that you can attempt to set a new
attribute, but the result will depend on how the class implements setat... | c58ca1a18e502cc47b85490157adf30f2306e3cf | 45,239 |
def title_match_ratio(title1, title2):
"""
Returns a number between 0 and 100, representing the percent
match (Levenshtein Distance) between book title1 and book title2,
after each has been normalized.
"""
title1 = normalize_title_for_matching(title1)
title2 = normalize_title_for_matching(ti... | 5855f0dcf33e3f09a2e2936589c903ae9a7c26de | 45,240 |
def get_theme(txt, min_topic_freq=0.05):
"""return the most likely topic based on text"""
new_doc = get_tokens(txt)
new_doc_bow = dictionary.doc2bow(new_doc)
main_theme = sorted(lda.get_document_topics(new_doc_bow), key=itemgetter(1), reverse=True)[0]
return main_theme | 12157d2a2a3a2524698247e1436d43407dd933f1 | 45,241 |
def merge(lhs: _cpp.Dataset, rhs: _cpp.Dataset) -> _cpp.Dataset:
"""Merge two datasets into one.
:param lhs: First dataset.
:param rhs: Second dataset.
:raises: If there are conflicting items with different content.
:return: A new dataset that contains the union of all data items,
coor... | 3a4836fc2fb2b148f47b501685136e669a08bed3 | 45,242 |
import sys
def calc_uff_atom_types(bonds, elements, override_rules=None):
"""
"""
g = nx.Graph()
g.add_edges_from(bonds)
if override_rules is None:
override_rules = default_uff_rules()
uff_keys = UFF4MOF.keys()
atom_types = []
add_aromatic_flag(g)
for n in sorted(g.node... | 633905f38e73883cc225aa3d5a2f53ad3c287c80 | 45,243 |
def _extract_asm_mnemonic(asm):
"""
:param asm:
:type asm:
"""
return asm.split()[0].strip().upper() | 058d92ceaa3fc6cae505c795c58a4e3f231bc849 | 45,244 |
def calc_model_age(t2_parent, t1_parent, t2_daughter, t1_daughter,
decay_constant):
"""Calculate the model age of a sample. NOTE: THIS FUNCTION IS UNDER
TESTING AND MAY NOT GIVE THE CORRECT ANSWER!
Parameters
----------
t2_parent : float
The measured parent composition.
... | f8d0e501a3b1b354c5195503b4ed4495106c7923 | 45,245 |
def Tri(a, b, c, tag=None):
"""
A triangular random variate
Parameters
----------
a : scalar
Lower bound of the distribution support (default=0)
b : scalar
Upper bound of the distribution support (default=1)
c : scalar
The location of the triangle's peak (a <= c ... | 2050e2331e6fac0c54a992aeee9d24bd74e994b9 | 45,246 |
def reverse_match(text, dict_word, longest_term):
"""
反向最長匹配
參數 text : 要分詞的文字
參數 dict_word : 繁體中文詞語字典
參數 longest_term : 字典中最長詞語的長度
回傳值 : 一個串列 內部元素為 詞語的(起始索引,結束索引)
"""
result_list = []
stack = [] #因為反向最長匹配是由後往前進行分詞 所以使用堆疊的資料結構
end = len(text) - 1
while end... | 860292300f1842195958d535e3926ca27bd1cece | 45,247 |
import json
import urllib
import sys
def available_packages():
"""Returns a list of package names available for the current version of Holodeck
Returns (:obj:`list` of :obj:`str`):
List of package names
"""
# Get the index json file from the backend
url = "packages/{ver}/available".format... | 722331358d980b26b461be20870311e914531efb | 45,248 |
def mean(sample1, sample2, axis=0, sample_size=130, borders=0, max_sample=1460, ratio=True,
median=False, **kwargs):
""" Adjustment method using mean differences or ratios
ratio=False
dataset[sampleout] + (MEAN(dataset[sample1]) - MEAN(dataset[sample2]))
ratio=True
dataset[sampleout] * ... | 2fdf559749ce268dd0777cdc7d720b7060da5013 | 45,249 |
def get_mean_ztf_alert_braai(_db, ra, dec):
"""
Cross-match by position and get mean alert braai score
"""
try:
ra_geojson = float(ra)
# geojson-friendly ra:
ra_geojson -= 180.0
dec_geojson = float(dec)
''' catalogs '''
catalog = 'ZTF_alerts'
... | edb0fb4768577464c93739332f39d747be12b138 | 45,250 |
def get_spaces(depth):
"""returns the required number of spaces
for indentation purpose"""
return ' ' * (depth * 4 - 2) | f59faaa963b8f1c16e20925b088eb1b7b8fda953 | 45,251 |
def load_webcat_data(webcat_csv):
""" Create a dictionary that maps from eids to lists with webcat data"""
table = generate_form.csv_to_numpy(webcat_csv, FIRST_ROW)
data = {}
for i in range(table.shape[0]):
eid = table[i, USER].strip().lower()
data[eid] = list(table[i, :])
return da... | 4f4f38b1c6eb0e7466b866b3ff77e4243c3eaaa0 | 45,252 |
import torch
import time
def get_pbo_pe_comparisons(
outcome_X,
train_comps,
problem,
utils,
init_round,
total_training_round,
comp_noise_type,
comp_noise,
pe_strategy,
):
"""
Generate TS-based comparisons on previously observed points
Args:
outcome_X ([type]):... | 0e50cfcbddb8119f2a7369dcf2aaef566ee1f84f | 45,253 |
import asyncio
async def _named_spooled_temporary_file(max_size=0, mode='w+b', buffering=-1,
encoding=None, newline=None,
suffix=None, prefix=None, dir=None,
loop=None, executor=None):
"""Open a... | 5ae67aed895a6583d6ff51b8db16dba2a7c6d548 | 45,254 |
def Covariance4D2Correlation4D(Cov_MPMB):
"""It normalizes each element of the 4-D Multi-Polarimetric Multi-Baseline
with respect to the corresponding diagonal terms.
INPUT
Cov_MPMB: [Nimm*Npol x Nimm*Npol x Nr x Na] Covariance matrices
OUTPUT
Corr_MPMB: [Nimm*Npol x Ni... | 44a24db1839f8fcfca0c368de226b246e4bcdee9 | 45,255 |
from typing import Optional
from typing import Iterator
from typing import Tuple
def header(
term: Terminal,
ui: UI,
*,
host: Host,
dbinfo: DBInfo,
tps: int,
active_connections: int,
system_info: Optional[SystemInfo] = None,
) -> Iterator[str]:
"""Return window header lines."""
... | e2f26147c621099abb8c79681ebb27f2c822654c | 45,256 |
from typing import Union
from typing import List
def text_pos(text: Union[StringView, str],
line: int, column: int,
lbreaks: List[int] = []) -> int:
"""
Returns the text-position for a given line and column or -1 if the line
and column exceed the size of the text.
"""
if ... | 35534a25e00bc0086c0cb4bd22391385622de77e | 45,257 |
def formatList(inputList):
"""
Formats a list of items to html unordered list
:param inputList: list of items to be formatted
"""
report = HTML()
htmlList = report.ul
for val in inputList:
val = str(val)
htmlList.li(val)
return report | 1e816e5d1390a72c1a13dff47e0615dc621dc861 | 45,258 |
import sys
def multi_maps_dfs(job_func, dfs_chunks, rou, reduce_num=1):
"""
执行与文件chunk数相同数量的map
:param job_func: 全部slave统一的默认的job python脚本位置
:param dfs_chunks:所有的文件chunk 编号list
:param admm_para_path: ADMM 的本地参数路径
:param reduce_num: partition中需要reduce的数量
:return:
"""
# 执行map时,触发一个异步... | 7b7d32901559d7fe2eab1643e215380b191ef84f | 45,259 |
async def get_images_list(
request: Request,
page: schemas.PageRequest,
):
"""
According to params to get images list
:param request: pony ORM
:param page: page_num page_size To decide how many images return
:return: List[image_url]
"""
with request.pony_session:
imag... | 877337892fc4bcf44cdde9f4147fdab0693bf81d | 45,260 |
from typing import List
def _get_det_bboxes(
pred: List[dict], labels: List[str], im_path: str = None
) -> List[DetectionBbox]:
""" Gets the bounding boxes and labels from the prediction object
Args:
pred: the output of passing in an image to torchvision's FasterRCNN
model
labels:... | c145842b8c4e2172646647ffd701c4c6ef2e2776 | 45,261 |
from datetime import datetime
import yaml
import os
def test_net(
args,
dataset_name,
proposal_file,
output_dir,
ind_range=None,
gpu_id=0,
include_feat=False):
"""Run inference on all images in a dataset or over an index range of images
in a dataset usin... | 087cf759210b2ff7fd3b7a1545657ebaf92a7e66 | 45,262 |
import json
import sys
def main():
"""Run main function."""
data = json.loads(sys.stdin.read())
# Prepare the node data by adjoining a key value equal to each record's
# index in the original data.
nodes = [add_key(record, index) for (index, record) in enumerate(data["nodes"])]
# Convert th... | ba6697e6b1c28af6c75663b8990903837413ba64 | 45,263 |
def contrastive_loss_test(y_true, dist):
"""Test function above using implementation with numpy instead tensors."""
margin = P.margin
return y_true * np.square(dist) + (1 - y_true) * np.square(np.max(margin - dist, 0)) | 90f456178b71fbc030ff769c9d1f438df01d23b6 | 45,264 |
def verify_password_hash(password: str, password_hash: str) -> bool:
"""
Helper function for verifying hashed password against
plain password.
Args
----
password: str
password_hash: str
Returns
-------
bool (Confirming if password is same as ... | 3bec34b48dce60f3b2d836749d76c548239343f2 | 45,265 |
def _get_project_results_for_jobs(jobs):
"""Return projects for jobs."""
projects = {}
for job in sorted(jobs, key=lambda j: j.name):
project_name = job.get_environment().get('PROJECT_NAME', job.name)
if project_name not in projects:
projects[project_name] = {'name': project_name, 'jobs': []}
i... | a4637710daf2f4ed9caf31d49fb5db8ff5660d74 | 45,266 |
import re
def untex(s):
"""Replace tex constructs with unicode"""
s = s.replace('$^{\circ}$', degree)
s = re.sub(emph, '<i>\g<emph_text></i>', s)
s = s.replace('\&', '&')
s = s.replace(r'$\beta$', beta)
s = s.replace(r'{\AE}', 'Æ')
s = s.replace(r'{\O}', 'Ø')
s = s.replace(r'{\AA}', 'Å... | 624de244ed86446f504ae837a5b868f71ef8b81f | 45,267 |
import re
def _clean(arr):
"""Convert ratio values for missing pieces of the tax into "unclassified"
and remove empty entries.
Rules:
- if all the cols are unclassified then remove row.
- if there is no classification for either genus, subfamily or family then remove row.
- collaps... | c898fe0b9ecf6afef47f76a8d4f74947a0df389f | 45,268 |
def to_categorical(batch, num_classes):
"""
Converts a batch of length-padded integer sequences to a one-hot encoded sequence
:param batch:
:param num_classes:
:return:
"""
b, l = batch.shape
out = np.zeros((b, l, num_classes))
for i in range(b):
seq = batch[0, :]
... | aa14fcb88c135c15ed9c8b6d24fa5c72bcbbffa7 | 45,269 |
from os import popen
def unixgetaddr(program):
"""Get the hardware address on a Unix machine."""
for line in popen(program):
words = line.lower().split()
if 'hwaddr' in words:
addr = words[words.index('hwaddr') + 1]
return int(addr.replace(':', ''), 16)
if 'ethe... | aef054ae0f3d1d812dacce9da483d45aceb2bbfa | 45,270 |
def format_summary(translation):
""" Transforms the output of the `from_batch` function
into nicely formatted summaries.
"""
raw_summary, _, _ = translation
summary = (
raw_summary.replace("[unused0]", "")
.replace("[unused3]", "")
.replace("[PAD]", "")
.replace("[unu... | a23fd464fdfa1efa5f8652d110bfff12919cf92a | 45,271 |
def splitintopolygons(polygons,d):
"""
Give a 1d array of length (N*(d*(d+1))), consisting of a series of N simplexes. Each simplex
has d+1 locations, each location is d long. For example, for 2d:
[(x1,y1),(x2,y2),(x3,y3)][(x1,y1),(x2,y2),(x3,y3)]...
d = dimensions
... | 2a1afaa2fefd5dfece9b77c56e033e71c00c20df | 45,272 |
import sys
def pwbs_execute_scommand(command, vdm, special):
"""Funkcja wykonująca zadanie specjalne"""
verbose_debug_mode = vdm
if command == "--new-config":
print("PWBS: Generowanie Pustego Pliku Komend")
dane = []
if not special: # pragma: no cover
write_json(config_... | aff3e54e9390bedcf0a796aaee6dcfb3211467d1 | 45,273 |
def read_image(filename):
"""
Reads a filename of an image as PIL pytorch format image. Returns the image
:param filename: Path to image
:return: PIL Image
"""
return Image.open(filename) | 2dac9364031214a9e1351e878415c512aecd098b | 45,274 |
def normalise(x):
"""
Normalises a given 3D vector.
Parameter:
x - a 3D vector that is an array.
"""
if x is not None and len(x) == 3:
return x/np.sqrt(np.dot(x,x))
else:
raise Exception("Three coordinates are required in the array.")
return None | f65417c142cc564c8670d61d5e186042a3edf968 | 45,275 |
def sequence_id(sqlite_connection):
"""
Функция возвращает список из id всех остановок
"""
try:
cur = sqlite_connection.cursor()
cur.execute("SELECT _id FROM stopsker")
seq = list()
for elem in cur.fetchall():
seq.append(int(elem[0]))
except Exception a... | f73352b977c2c96a378985899f02674ab0c2cb14 | 45,276 |
def asin(x):
"""
Computes inverse sine element-wise.
:param x: y-coordinate on the unit circle.
:type x: array
:return: The inverse sine of each element in x, in radians and in the closed interval [-pi/2, pi/2].
"""
return _cur_framework(x).asin(x) | bc7d5f7c8fb7a73c6eb777dcdca9b08d1cba846b | 45,277 |
import socket
from typing import cast
def sockaddr_from_tupe(addr):
"""
Converts a socket address tuple (host, port) to a proper socketaddr_*
C struct.
@param addr:
@return:
"""
if ":" in addr[0]:
family = socket.AF_INET6
if len(addr) == 4:
addr, port, flowinf... | 90b06bf907fafc401524a4d612f9b7dfb3f19295 | 45,278 |
def add_matches(flight_matches, flight_ids):
"""
Add new matches to the flight_ids dict.
Returns the number of newly matched flights.
"""
matches = 0
for i in flight_matches.index:
prev_id = flight_matches.loc[i, 'FLIGHT_ID_x']
next_id = flight_matches.loc[i, 'FLIGHT_ID_y']
... | 93d086cd580ac13622c4acaa359fa2a65b718ff3 | 45,279 |
async def handle_command(
request: Request,
response: Response,
background_tasks: BackgroundTasks,
x_slack_request_timestamp: int = Header(None),
x_slack_signature: str = Header(None),
db_session: Session = Depends(get_db),
):
"""Handle all incomming Slack commands."""
raw_request_body =... | 38eac9e1b54ec35e201a4df99430f84a7560b5c9 | 45,280 |
import logging
import os
import json
import subprocess
def inference(request):
""" Function: inference
* inference top
"""
def _get_selected_object():
project_name = request.session.get('inference_view_selected_project', None)
selected_project = Project.objects.get(name=project_name)
... | 5a5e45154b22c3cfb91b073ad3e5bfe00153b84a | 45,281 |
def parse_registry_url(registry_url):
"""
Given an AWS ECR registry URL, parses out the AWS Account ID and Region
>>> aid, region = parse_registry_url('http://12345.dkr.ecr.us-west-2.amazonaws.com')
('12345', 'us-west-2')
>>> aid, region = parse_registry_url('12345.dkr.ecr.us-west-2.amazonaws.com'... | 9df231b3f067dadc4fd248d9b15b8228cdcb7b00 | 45,282 |
import sys
def add_repository_to_path(repo, rev="HEAD", in_repo_path=""):
"""
Adds a repository reference to sys.path. If gitimporter is not initialized yet, it will also be added to
sys.path_hooks
:param repo: a pygit2 repository object or a path to a git repository
:param rev: the revision whic... | 53d8de6dbc562a6b647880e0f2abd6573c6f1c42 | 45,283 |
def add_zone_ideal_loads_energy(idf):
"""add fmu output of
- Zone Ideal Loads Zone Total Heating Energy
- Zone Ideal Loads Zone Total Cooling Energy
"""
idf = ensure_contains(
idf,
'EnergyManagementSystem:GlobalVariable',
'gv_the')
idf = ensure_contains(
... | 6cee5da2f7159ffe88d0ee1195a7745e6139b594 | 45,284 |
def _entropy(data, group_pop_var, total_pop_var):
"""Calculate Entropy index.
Parameters
----------
data : pandas.DataFrame or geopandas.GeoDataFrame
Dataframe or geodataframe if spatial index holding data for location of interest
group_pop_var : string
Variable containing the popul... | 3076e43ba227d426e4a4680b31f61d94511c1065 | 45,285 |
import scipy
def Delta_calc(airtemp=scipy.array([])):
"""
Function to calculate the slope of the temperature - vapour pressure curve
(Delta) from air temperature T:
.. math::
\\Delta = 1000 \\cdot \\frac{e_s \\cdot 4098}{(T + 237.3)^2}
where es is the saturated vapour pressure at tempera... | bdae190a64deb5734e21b40898ec8c65cb9da2e0 | 45,286 |
def determineRotation(steroid_orientation,reference_orientation,cutoff=1e-2):
"""
Only does rotation if angle differs significantly from 0 or pi. This
minimizes the number of transformations that are done. At the end, we
then decide the correct way to describe the signs of each flip.
"""
... | 5e22633ee0c90f0fbbab655ce6316fee487c7650 | 45,287 |
def make_survey_and_score(theta,args):
"""
Wrapper for score_survey. Makes a new field_list, then scores the stars in star_list.
Parameter
---------
theta : list
Should be a list of length N_fieldx2, with first N_field entries being RAs, next
N_field entries being Decs.
arg... | e0df37f12881eeaa6b3efe7dfb9a2fd4a10e289b | 45,288 |
def crawler1(request):
"""
Hello world
"""
# 方案一的代码
code_crawler1_1_path = crawler_code_dir / 'crawler1_1.py'
code_crawler1_1 = open(code_crawler1_1_path).read()
# 方案二的代码
code_crawler1_2_path = crawler_code_dir / 'crawler1_2.py'
code_crawler1_2 = open(code_crawler1_2_path).read()
... | cf5785e7f27fb2502e760a2270666898b84b2093 | 45,289 |
import random
from unittest.mock import patch
def test_sample_independent_int_loguniform_distributions() -> None:
"""Test sampling from int distribution returns integer."""
study = optuna.create_study()
def int_value_fn(idx: int) -> float:
random.seed(idx)
return random.randint(0, 100)
... | 55e10a9219c28282eb28062fbfdf8ad3083765fb | 45,290 |
from ibeis.control import _autogen_annotmatch_funcs
def get_annotmatch_rowids_from_aid2(ibs, aid2_list, eager=True, nInput=None,
force_method=None):
"""
# This one is slow because aid2 is the second part of the index
Returns a list of the aids that were reviewed as cand... | 8d810d6f9d5eadb8589d21bc758afd3034169c4b | 45,291 |
def get_data_source_dropdown_options(dataSource, dataType, language):
"""Creates and returns the dropdown options for each data source.
The dropdown options include the label, the value and the title
for each dropdown item.
Parameters
----------
dataSource : str
The name of the data so... | 1e49eea9a5ee5a265fb06657967cc75271330218 | 45,292 |
def Run(args):
"""Adds a binding to the IAM policy for a Google Cloud Function.
Args:
args: an argparse namespace. All the arguments that were provided to this
command invocation.
Returns:
The updated IAM policy.
"""
function_ref = args.CONCEPTS.name.Parse()
return util.AddFunctionIamPolicyB... | 60ddc3d062781d1caab39e2627bcfb1d65f0867b | 45,293 |
def cifar10_resnet23_prediction(image, maps=64,
test=False):
"""
Construct Resnet23 as reference.
"""
# Residual Unit
def res_unit(x, scope_name, dn=False):
C = x.shape[1]
with nn.parameter_scope(scope_name):
# Conv -> BN -> Relu
... | f7c2c013a9c56ef176e3b82a20932d8c5a7c3398 | 45,294 |
import types
def dshape_to_alchemy(dshape, primary_key=frozenset()):
"""
>>> dshape_to_alchemy('int')
<class 'sqlalchemy.sql.sqltypes.Integer'>
>>> dshape_to_alchemy('string')
<class 'sqlalchemy.sql.sqltypes.Text'>
>>> dshape_to_alchemy('{name: string, amount: int}')
[Column('name', Tex... | 7cf93fc59b0091dc0e8836985103093c35e5a06e | 45,295 |
def parse_percentiles(percentiles):
"""Parse lists of percentile values in (0,100) range.
Examples:
.2
10,15,99.9
"""
def parse_percentile(val):
try:
result = float(val)
if result <= 0 or result >= 100:
raise ValueError()
except ValueError:
raise ArgumentTypeEr... | 286c0d7383775d4fd9d1015090fa99e27af94df3 | 45,296 |
import logging
def lightcurve_from_alert(
alert: list,
# figsize: list=[6.47, 4],
figsize: list = [8, 5],
title: str = None,
include_ulims: bool = True,
include_cutouts: bool = True,
include_crossmatch: bool = True,
mag_range: list = None,
z: float = None,
legend: bool = False,... | 66cb00b9435ad2d188882870da5cdf890f32f9e2 | 45,297 |
def get_requirements_from_file(requirements_file):
"""
Get requirements from file.
:param str req_file: Name of file to parse for requirements.
:return: List of requirements
:rtype: list(str)
"""
requirements = []
with open(requirements_file) as f:
for line in f:
lin... | 5ec6ad1f4c2b22aae1cfa7eb3888b3279ffeca31 | 45,298 |
from typing import Tuple
from typing import List
def extract_encoded_headers(payload: bytes) -> Tuple[str, bytes]:
"""This function's purpose is to extract lines that can be decoded using the UTF-8 decoder.
>>> extract_encoded_headers("Host: developer.mozilla.org\\r\\nX-Hello-World: 死の漢字\\r\\n\\r\\n".encode("... | d1f3a371419b81b0e7ede1a7f90401cf7a89559f | 45,299 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.