content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import time
def solveSudoku(fileName = "", showResults = False, showTime = False, matrix = []):
"""
Solves a Sudoku by prompting the sudoku or reading a text file containing the sudoku or by directly
taking the matrix as a variable and either shows the solution or returns it. Can also tell the execution t... | a54cd39111638b9a02845781e7b731ca32d11089 | 3,638,798 |
def vertexval(val, size):
"""Converto to row,col or raise GTP error."""
val = val.lower()
if val == 'pass':
return None
letter = str(val[0])
number = int(val[1:], 10)
if not 'a' <= letter <= 'z':
raise GTPError('invalid vertex letter: {!r}'.format(val))
if number < 1:
... | 610441915c1d46baf9157a849140d1db7bf6f3d5 | 3,638,799 |
def v0abs(x_ratio, distance_source, lr_angle, br_angle):
""" Returns the norm for the velocity reference v_0"""
vy_comp = vly(x_ratio, distance_source, lr_angle, br_angle) - (1.-x_ratio)*voy(lr_angle)
vz_comp = vlz(x_ratio, distance_source, lr_angle, br_angle) - (1.-x_ratio)*voz(lr_angle, br_angle)
#vy ... | d2f55f1b92912d457a50cd7f89680b2452a6d2d4 | 3,638,800 |
def copy(stream, credentials, direction, hdfsFile=None, hdfsFileAttrName=None, localFile=None, name=None):
"""Copy a Hadoop Distributed File to local and copy a local file to te HDFS.
Repeatedly scans a HDFS directory and writes the names of new or modified files that are found in the directory to the output s... | 843d36d1a37591761d2791f7d78c5c3273e3abf8 | 3,638,802 |
from typing import List
def normalize(value: str) -> str:
"""Normalize a string by removing '-' and capitalizing the following character"""
char_list: List[str] = list(value)
length: int = len(char_list)
for i in range(1, length):
if char_list[i - 1] in ['-']:
char_list[i] = char_... | 52c1c8b5e950347cf63ed15d1efde47046b07873 | 3,638,803 |
def save_data(userId, columns, tableName, searchTerm="", objType="", sortBy=None,
tableId=None, isDefaultOnDashboard=False, maxRows=0,
dashboard=None, clone=False, row=0, grid_col=0, sizex=0,
sizey=0):
"""
Saves the customized table in the dashboard. Called by save_sear... | da6491135246ad785f95333eb30d4316971f51fe | 3,638,804 |
def heatmap(plot,
client_color=False,
low=(255, 200, 200), high=(255, 0, 0),
spread=0, transform="cbrt", **kwargs):
"""
Produce a heatmap from a set of shapes.
A heatmap is a scale of how often a single thing occurs.
This is a convenience function that encodes a commo... | 3e4b319b414cc7b751d44c0ef61db1e810d638a3 | 3,638,805 |
def add_comment_to_task(task_id, comment, status=None):
"""
Adds comment to given task
:param task_id:
:param comment:
:param status:
:return:
"""
task = get_task(task_id, as_dict=True)
if not task:
return
if not status:
status = gazu.task.get_task_status(task)
... | 2cd8d109c2420c10d5924178dbc491dfd5956ccf | 3,638,806 |
def score(h,r,t):
"""
:param h: (batch_size, dim)
:param r: (dim, )
:param t: (dim, )
:return:
"""
return np.dot(h, np.transpose(r*t)) | afacedde04ea12a310301f097e2200bab2ef7adc | 3,638,807 |
def migrate_file(file_name, file_content):
"""Migrate file."""
return V4Migrator(file_name, file_content).migrate() | 7828fa20f49594aae59cbce3a03af42f14eac28d | 3,638,808 |
def _GetOrganizedAnalysisResultBySuspectedCL(analysis_result):
"""Group tests it they have the same suspected CLs."""
organized_results = defaultdict(list)
if not analysis_result:
return organized_results
for step_failure in analysis_result.get('failures', []):
step_name = step_failure['step_name']
... | b9b28a530402d0745f4ec6adb715c3ac0bb9bf4c | 3,638,809 |
def volume_division(in_volume1, in_volume2):
"""Divide a volume by another one
Args:
in_volume1 (nibabel volume): data will be a [m,n,o] array
in_volume2 (nibabel volume): data will be a [m,n,o] array
Returns:
out_volume (nibabel volume): data will be a [m,n,o] array,
d... | 271ac81f4166324ca9d20eb6f12cf8efb5c7a4ae | 3,638,810 |
def sparse_eye(num_rows,
num_columns=None,
dtype=dtypes.float32,
name=None):
"""Creates a two-dimensional sparse tensor with ones along the diagonal.
Args:
num_rows: Non-negative integer or `int32` scalar `tensor` giving the number
of rows in the resulting mat... | 1b6f47af28e14dfb0cc0dfc3e4d8ced84b8b6c59 | 3,638,811 |
def count_num_sents_cluster(sents_vectors, sections_sents, n_clusters):
"""
Cluster sentences and count the number of times that sentences from each
section appear in each cluster.
Ex: 4 sents from introduction and 3 sentences from conclusion in cluster x.
"""
labels, centroids = cluster_sents(s... | 8ee94a7bc0bb10bfc2af3a03c46717691d534fef | 3,638,812 |
import hashlib
def check_password_pwned(password, fast=False):
"""Check if a password is in the pwned-passwords list.
:param password: The plaintext password
:param fast: Whether the check should finish quickly, even if that may
indicate not being able to check the password. This should
... | c4b7679930708750e8925e65fb6f73bf8283027b | 3,638,814 |
def is_plugin_loaded(plugin_name):
"""
Return whether given plugin is loaded or not
:param plugin_name: str
:return: bool
"""
return maya.cmds.pluginInfo(plugin_name, query=True, loaded=True) | 8c57793c620b209f6741c111361ce1c10ca5e7b5 | 3,638,815 |
def drydown_service(lat: float = Query(...), lon: float = Query(...)):
"""Babysteps."""
return handler(lon, lat) | 7996eaaf6f530815b20b66b5a8acf1f68c47d81c | 3,638,816 |
def service_vuln_iptable(hostfilter=None):
"""Returns a dict of services. Contains a list of IPs with (vuln, sev)
'0/info': { 'host_id1': [ (ipv4, ipv6, hostname), ( (vuln1, 5), (vuln2, 10) ... ) ] },
{ 'host_id2': [ (ipv4, ipv6, hostname), ( (vuln1, 5) ) ] }
"""
service_dict = {}
# go ... | a03383596551d9cb789459531c5e8d808c27b502 | 3,638,817 |
def validate_tier_name(name):
"""
Property: Tier.Name
"""
valid_names = [WebServer, Worker]
if name not in valid_names:
raise ValueError("Tier name needs to be one of %r" % valid_names)
return name | 6bba596f75dbdebe03bf133c4f1847ab0c5b6c49 | 3,638,818 |
def version_get(): # noqa: E501
"""Version
Version # noqa: E501
:rtype: InlineResponse2006
"""
response = InlineResponse2006()
version = Version()
v = CoreApiVersion.query.filter_by(active=True).first()
if v:
version.version = v.version
version.reference = v.reference... | 691bc9776d9f3c6cc1597d4d60fbc740c71ca27d | 3,638,819 |
def language_register(df):
"""
Add 'training language', 'test language', 'training register' and 'test register'
columns to a dataframe.
This assumes that:
- the dataframe contains a 'training set' and 'test set' column
- the sets mentioned in these columns are properly documented in
th... | e741eda59136a16d50ccf19350558e07177e6afa | 3,638,820 |
def init(request):
"""
Wraps an incoming WSGI request in a Context object and initializes
several important attributes.
"""
set_umask() # do it once per request because maybe some server
# software sets own umask
if isinstance(request, Context):
context, request = reques... | e8e455611aceea6ac5b745e9b618b1375b82108e | 3,638,822 |
def fetch_arm_sketch(X, ks, tensor_proj=True, **kwargs_rg):
"""
:param X: the tensor of dimension N
:param ks: array of size N
:param tensor_proj: True: use tensor random projection,
otherwise, use normal one
:param kwargs_rg:
:return: list of two, first element is list of arm sketches
a... | 893da47798a3c167111072fe627a78e15d1996dd | 3,638,823 |
def fitness(member):
"""Computes the fitness of a species member.
http://bit.ly/ui-lab5-dobrota-graf"""
if member < 0 or member >= 1024:
return -1
elif member >= 0 and member < 30:
return 60.0
elif member >= 30 and member < 90:
return member + 30.0
elif member >= 90 and member < 120:
retu... | 81e8bd12da458f0c4f2629e3781c2512c436c577 | 3,638,824 |
def style_loss(content_feats, style_grams, style_weights):
"""
Computes the style loss at a set of layers.
Inputs:
- feats: list of the features at every layer of the current image.
- style_targets: List of the same length as feats, where style_targets[i] is
a Tensor giving the Gram matri... | ee8b5007ba2adc88d9965408591d1018027cf7f9 | 3,638,825 |
def get_annotations(joints_2d, joints_3d, scale_factor=1.2):
"""Get annotations, including centers, scales, joints_2d and joints_3d.
Args:
joints_2d: 2D joint coordinates in shape [N, K, 2], where N is the
frame number, K is the joint number.
joints_3d: 3D joint coordinates in shape... | 27d7614ce32a3eb6b91db7edcb5abe757d011605 | 3,638,826 |
def Intensity(flag, Fin):
"""
I=Intensity(flag,Fin)
:ref:`Calculates the intensity of the field. <Intensity>`
:math:`I(x,y)=F_{in}(x,y).F_{in}(x,y)^*`
Args::
flag: 0= no normalization, 1=normalized to 1, 2=normalized to 255 (for bitmaps)
Fin: input field
... | 54642c7e5b68e7c87137534a91d990f90214a4b6 | 3,638,827 |
def index(request):
"""
Display the index for user related actions.
"""
export_form = ExportForm(request.POST or None)
return render(request, "users/index.html", {"export_form": export_form}) | 273e3d101034ef7cfd5b8795be42b48de0aea740 | 3,638,828 |
from typing import Dict
from typing import Any
import re
def _get_javascript_and_find_feature_flag(client: HttpSession, script_uri: str, headers: Dict[str, Any] = None) -> Any:
"""
Read through minified javascript for feature flags
"""
flag_str = None
# Since this is a large request, read incremen... | 632eeba5483dffd5ef9648c41e78cf3b135f0d3d | 3,638,829 |
def next_power_of_two(v: int):
""" returns x | x == 2**i and x >= v """
v -= 1
v |= v >> 1
v |= v >> 2
v |= v >> 4
v |= v >> 8
v |= v >> 16
v += 1
return v | 9c62840e2dc2cd44666328c32c48e5867523ba6c | 3,638,830 |
def triangle(times: np.ndarray, amp: complex, freq: float, phase: float = 0) -> np.ndarray:
"""Continuous triangle wave.
Args:
times: Times to output wave for.
amp: Pulse amplitude. Wave range is [-amp, amp].
freq: Pulse frequency. units of 1/dt.
phase: Pulse phase.
"""
... | 83933dbed893026b1a53490fb32587d918c15a1f | 3,638,831 |
def add_token(token_sequence: str, tokens: str) -> str:
"""Adds the tokens from 'tokens' that are not already contained in
`token_sequence` to the end of `token_sequence`::
>>> add_token('', 'italic')
'italic'
>>> add_token('bold italic', 'large')
'bold italic large'
>>>... | 2506dd00b55e9d842dc90c40578e0c21d942e73e | 3,638,832 |
def ket2dm(psi):
"""
convert a ket into a density matrix
Parameters
----------
psi : TYPE
DESCRIPTION.
Returns
-------
TYPE
DESCRIPTION.
"""
return np.einsum("i, j -> ij", psi, psi.conj()) | 96773dfe3db251a72d5da41be670c830cd3ff764 | 3,638,833 |
def _make_feature_stats_proto(
stats_values,
feature_name):
"""Creates the FeatureNameStatistics proto for one feature.
Args:
stats_values: A Dict[str,float] where the key of the dict is the name of the
custom statistic and the value is the numeric value of the custom
statistic of that feat... | e4babf49fad6a086860a6024aa0ffffc46e034a0 | 3,638,834 |
import torch
def build_lr_scheduler(
cfg, optimizer: torch.optim.Optimizer
) -> torch.optim.lr_scheduler._LRScheduler:
"""
Build a LR scheduler from config.
"""
name = cfg.NAME
if name == "WarmupMultiStepLR":
return WarmupMultiStepLR(
optimizer,
cfg.STEPS,
... | 3f4ec6a4ab2601642225118b9a7e9a60d7af6548 | 3,638,835 |
def cconv(x, y, P):
""" Periodic convolution with period P of two signals x and y
"""
x = _wrap(x, P)
h = _wrap(y, P)
return np.fromiter([np.dot(np.roll(x[::-1], k+1), h) for k in np.arange(P)], float) | 4bc0abba6af31ea98e292a82aab704c76748cceb | 3,638,836 |
def keypoint_loss_targets(uvd, keys_uvd, mparams):
"""Computes the supervised keypoint loss between computed and gt keypoints.
Args:
uvd: [batch, order, num_targs, 4, num_kp] Predicted set of keypoint uv's
(pixels).
keys_uvd: [batch, order, num_targs, 4, num_kp] The ground-truth set of uvdw
coo... | 0bd44661695e1024a56b441110ca4e9c3dae3634 | 3,638,839 |
import re
def get_initial_epoch(log_path):
"""
从log文件中获取最近训练结束时的epoch,重新运行代码后会接着这个epoch继续训练。
"""
initial_epoch = 0
if tf.gfile.Exists(log_path):
with open(log_path) as log_file:
line_ind = -1
for _, line in enumerate(log_file):
line = line.strip(... | d0e2adcccbfa59e1f685f698255c750d5a85ddaf | 3,638,840 |
from datetime import datetime
def categorise_town_flood_risk(stations, dt, degree, risklevel=3, plot=False):
"""A function that takes a list "stations" of station objects, performs polyfit over a period of "dt" days up to a "degree" degree and then returns towns with their respective flood risk.
The flood ris... | 526550890d8201c4a7b90f9ba37fa3f383118293 | 3,638,841 |
def create_clients(num_clients, client_data, input_str='input', label_str='label', client_str='client-',
distribute=False):
"""
create K clients
:param config: network_config
:param num_clients: the number of clients
:param client_data: Dictionary of clients data. data[client][inp... | 77a26cd53f701eaadd4d6577b80dc894022002d7 | 3,638,842 |
import typing
def l2_loss(
h: typing.Callable[[np.ndarray, np.ndarray], np.ndarray],
grad_h: typing.Callable[[np.ndarray, np.ndarray], np.ndarray],
theta: np.ndarray,
x, y):
"""l2_loss: standard l2 loss.
The l2 loss is defined as (h(x) - y)^2. This is usually used for linear
regression in... | f958476912a1866bd55653d3f896ddb0fe93a614 | 3,638,843 |
def BestLogLikelihood(aln, alphabet=None, exclude_chars = None,
allowed_chars='ACGT', motif_length=None, return_length=False):
"""returns the best log-likelihood according to Goldman 1993.
Arguments:
- alphabet: a sequence alphabet object.
- motif_length: 1 for nucleotide, 2 for dinucle... | a3b5338b3925281941a55ca28250d262a69dce1c | 3,638,844 |
def process_h5_file(h5_file):
"""Do the processing of what fields you'll use here.
For example, to get the artist familiarity, refer to:
https://github.com/tbertinmahieux/MSongsDB/blob/master/PythonSrc/hdf5_getters.py
So we see that it does h5.root.metadata.songs.cols.artist_familiarity[songidx]
... | de664a3e1ea88c8c8cd06b210e4c6b756a4d02a6 | 3,638,845 |
import logging
import copy
from perses.utils.openeye import iupac_to_oemol
import perses.rjmc.geometry as geometry
import perses.rjmc.topology_proposal as topology_proposal
from perses.tests.utils import compute_potential_components
def run_geometry_engine(index=0):
"""
Run the geometry engine a few times to ... | a2918f3073f3b0ec34ad3519693d25b433852b04 | 3,638,846 |
def add_changes_metrics(df, connection):
"""This function joins the data from the jira_issues table with the data
from the FTS3 table. It gets, for each issue, the number of lines_added,
lines_removed and files_changed.
"""
out_df = df.copy()
metrics = df["key"].apply(get_commits_from_issue, arg... | 67f61a4400f3ce67bc9c877017609e7460c82aaf | 3,638,847 |
def binary_str(num):
""" Return a binary string representation from the posive interger 'num'
:type num: int
:return:
Examples:
>>> binary_str(2)
'10'
>>> binary_str(5)
'101'
"""
# Store mod 2 operations results as '0' and '1'
bnum = ''
while num > 0:
bnum = str... | dde400323fccb9370c67197f555d9c41c40084a6 | 3,638,848 |
def sample_target_pos(batch_size,TARGET_MAX_X, TARGET_MIN_X, TARGET_MAX_Y, TARGET_MIN_Y):
"""
Sample target_position or robot_position by respecting to their limits.
"""
random_init_x = np.random.random_sample(batch_size) * (TARGET_MAX_X - TARGET_MIN_X) + \
TARGET_MIN_X
random_in... | 5e0536662976b3965b3325b0214e6d41678e6f3f | 3,638,849 |
def clf_perceptron(vector_col:str,
df_train:pd.DataFrame,
model:Perceptron,
) -> list:
"""return classification for multi-layer perception
Arguments:
vector_col (str): name of the columns with vectors to classify
df_train (pd.DataFrame): dataframe with traini... | e692f4b887b5b0235ef196250fb3dc4415ec510a | 3,638,850 |
def compute_phot_error(flux_variance, bg_phot, bg_method, ap_area, epadu=1.0):
"""Computes the flux errors using the DAOPHOT style computation
Parameters
----------
flux_variance : array
flux values
bg_phot : array
background brightness values.
bg_method : string
backg... | 4470277ebc41cce0e2c8c41c2f03e3466473d749 | 3,638,851 |
def reflect_table(conn, table_name, schema='public'):
"""Reflect basic table attributes."""
column_meta = list(get_column_metadata(conn, table_name, schema=schema))
primary_key_columns = list(get_primary_keys(conn, table_name, schema=schema))
columns = [Column(**column_data) for column_data in column_... | fb41243328a7b3da27dbcc355fdf36ef20915f94 | 3,638,852 |
def get_token(token_file):
"""
Reads the first line from token_file to get a token
"""
with open(token_file, "r") as fin:
ret = fin.read().strip()
if not ret:
raise ReleaseException("No valid token found in {}".format(token_file))
return ret | 764d3ca320953cd5ccfeccd60a9cbeb2efb504e1 | 3,638,853 |
def get_description(soup):
"""Извлечь текстовое описание вакансии"""
non_branded = soup.find('div', {'data-qa':'vacancy-description'})
branded = soup.find('div', {'class':'vacancy-section HH-VacancyBrandedDescription-DANGEROUS-HTML'})
description = non_branded or branded
return description.get_text(... | 82a254774be3eb55762d9964928429d168572a2a | 3,638,854 |
from pathlib import Path
def read_fits(fn: Path, ifrm: int, twoframe: bool) -> np.ndarray:
"""
ifits not ifrm for fits!
"""
if fits is None:
raise ImportError('Need Astropy for FITS')
# memmap = False required thru at least Astropy 1.3.2 due to BZERO used...
with fits.open(fn, mode='re... | f307cb2dc17c518b26591a3a8adf165eca000d66 | 3,638,855 |
def normalize(arrList):
"""
Normalize the arrayList, meaning divide each column by its standard deviation if that
standard deviation is nonzero, and leave the column unmodified if it's standard deviation
is zero.
Args:
arrList (a list of lists of numbers)
Returns:
list, list: A... | dfde56e87ab916f2777257782bc3f797e8bdfe74 | 3,638,856 |
import requests
from bs4 import BeautifulSoup
import re
def get_reddit_backup_urls(mode):
"""
Parse reddit backups on pushshift.io
:param mode: 'Q' for questions, 'A' for answers
:return: dict of (year, month): backup_url
"""
mode = {'Q': 'submissions', 'A': 'comments'}[mode]
page = reques... | e66ee167d1b10d0e67f84c60d8f4ae589eaeec38 | 3,638,857 |
def collect_elf_segments(elf, file_type, segment_els, section_prefix, namespace, image, machine, pools):
"""
Process all of the segment elements in a program/kernel, etc.
"""
elf_seg_names = elf_segment_names(elf)
shash = segments_hash(segment_els)
# Test that every segment element references a... | 9c82b7dfb6d6d9bcdfeae6e11683826b6b4b2a18 | 3,638,858 |
def getStrVector(tarstr,cdict,clen=None):
"""
将字符串向量化,向量的每一项对应字符集中一种字符的频数,字符集、每种字符在向量中对应的下标由cdict提供
"""
if not clen:
clen=len(cdict.keys())
vec=[0]*clen
for c in tarstr:
vec[cdict[c]]+=1
#vec[cdict[c]]=1
return vec | d23b54288d6a9cff2f3999c54f53a7f8e2d5d35f | 3,638,859 |
def process_request(registry: ServiceRegistry, url: str) -> str:
""" Given URL (customer name), make a Request to handle interaction """
# Make the container that this request gets processed in
container = registry.create_container()
# Put the url into the container
container.register_singleton(ur... | 48773840f325838e97f7a8c2b7c6dfa056a4f8e6 | 3,638,860 |
def percent_color(percentage: float) -> str:
""" Generate a proper color for a percentage for printing. """
color = 'red'
if percentage > 30:
color = 'yellow'
if percentage > 70:
color = 'green'
return colored(percentage, color) | bff809b98a98492cd67f5f3b1274bbd9f2a42203 | 3,638,861 |
def _generate_image_and_label_batch(image, image_raw, label, min_queue_examples,
batch_size, shuffle):
"""Construct a queued batch of images and labels.'''
example: min_fraction_of_examples_in_queue = 0.4
min_queue_examples = int(NUM_EXAMPLES_PER_EPOCH_FOR_TRAIN *
... | 1abd2059b0c752b3c884c2525870581afc07fdab | 3,638,862 |
def elgamal_add(*ciphertexts: ElGamalCiphertext) -> ElGamalCiphertext:
"""
Homomorphically accumulates one or more ElGamal ciphertexts by pairwise multiplication. The exponents
of vote counters will add.
"""
assert len(ciphertexts) != 0, "Must have one or more ciphertexts for elgamal_add"
pads ... | eb06c4a893aada24c9acb82c5542a8e891802b23 | 3,638,864 |
def find_min_cost_thresholds(roc_curves, base_rates, proportions, cost_matrix):
"""Compute thresholds by attribute values that minimize cost.
:param roc_curves: Receiver operating characteristic (ROC)
by attribute.
:type roc_curves: dict
:param base_rates: Base rate by attribute.... | fc17b2f8ef404a199798b522461c508cb57fb3bd | 3,638,865 |
def get_content_type_encoding(curi):
"""
Determine the content encoding based on the `Content-Type` Header.
`curi` is the :class:`CrawlUri`.
"""
content_type = "text/plain"
charset = ""
if curi.rep_header and "Content-Type" in curi.rep_header:
(content_type, charset) = extract_cont... | 9cf683eb8eceb9d27f374b3a135f2aac2d2c4b8e | 3,638,866 |
def truncate_errors(install_stdout, install_errors, language_detection_errors,
compile_errors, max_error_len=10*1024):
"""
Combine lists of errors into a single list under a maximum length.
"""
install_stdout = install_stdout or []
install_errors = install_errors or []
langua... | b807cea3c5cb7c0fc73c464d4d0205fd60f80504 | 3,638,867 |
from typing import List
def is_balanced(expression: str) -> bool:
"""
Checks if a string is balanced.
A string is balanced if the types of brackets line up.
:param expression: is the expression to evaluate.
:raise AttributeError: if the expression is None.
:return: a boolean value determining... | 124e5e61aec81b16c2f7457da4ba5d43219ccae1 | 3,638,868 |
from typing import Optional
from typing import Tuple
from typing import Sequence
def get_committee_assignment(state: BeaconState,
epoch: Epoch,
validator_index: ValidatorIndex
) -> Optional[Tuple[Sequence[ValidatorIndex], Committee... | ce9f0ab9e4b643a0ab9c87cf8b46fca5f9c0966a | 3,638,869 |
def is_custfmt0(*args):
"""
is_custfmt0(F) -> bool
Does the first operand use a custom data representation?
@param F (C++: flags_t)
"""
return _ida_bytes.is_custfmt0(*args) | c836ded70576a4e7d2b6d21dff5c649e22b6229e | 3,638,870 |
from typing import Set
def get_nfa_by_graph(
graph: nx.MultiDiGraph, start_nodes: Set[int] = None, final_nodes: Set[int] = None
) -> NondeterministicFiniteAutomaton:
"""
Creates a Nondeterministic Finite Automaton for a specified graph.
If start_nodes and final_nodes are not specified, all nodes are c... | 446d75dce1e9f305c4fd2ac39ba0f0efec67fa22 | 3,638,872 |
import math
def print_key_val(init, value, pre_indent=0, end=','):
"""Print the key and value and insert it into the code list.
:param init: string to initialize value e.g.
"'key': " or "url = "
:param value: value to print in the dictionary
:param pre_indent: optional param to set t... | 3def14ce63cdfb1ef797172efcac10dcfacb02e7 | 3,638,873 |
def not_found_error(e):
"""HTTP 404 view"""
# Ignore unused arguments
# pylint: disable=W0613
return render_template("errors/404.html"), 404 | c60941ee8e9ff1959b7a5968376501fb50def62c | 3,638,874 |
def rel_error(model, X, Y, meanY =0):
"""function to compute the relative error
model : trained neural network to compute the predicted data
X : input data
Y : reference output data
meanY : the mean of the of the untreated Y """
Yhat = model.predict(X)
dY = Yhat - Y
axis = tuple(... | 51c49f13f59b22a37dadd28d7e0aefdca4598ac7 | 3,638,875 |
def read_data(vocab, path):
"""Reads a bAbI dataset.
Args:
vocab (collections.defaultdict): A dictionary storing word IDs.
path (str): Path to bAbI data file.
Returns:
list of Query of Sentence: Parsed lines.
"""
data = []
all_data = []
with open(path) as f:
... | ada97a2c94ec832af45aa91531f7f1e137522cb1 | 3,638,876 |
from typing import Type
from typing import Optional
import time
def get_dataset(cfg: DatasetConfig,
shard_id: int,
num_shards: int,
feature_converter_cls: Type[seqio.FeatureConverter],
num_epochs: Optional[int] = None,
continue_from_last_... | 66569296980136b1eba8f577ad876e30fb66f50b | 3,638,877 |
def contour_distances_2d(image1, image2, dx=1):
"""
Calculate contour distances between binary masks.
The region of interest must be encoded by 1
Args:
image1: 2D binary mask 1
image2: 2D binary mask 2
dx: physical size of a pixel (e.g. 1.8 (mm) for UKBB)
Returns:
mea... | 14ebed56942c6dbbd674e08af1743e443c9b1267 | 3,638,878 |
def weighted_sequence_identity(a, b, weights, gaps='y'):
"""Compute the sequence identity between two sequences, different positions differently
The definition of sequence_identity is ambyguous as it depends on how gaps are treated,
here defined by the *gaps* argument. For details and examples, see
`... | 8face090454e984d0d4b9ea5fe78b6600a6e6b03 | 3,638,879 |
def loss_fd(batch,model,reconv_psf_image,step=0.01):
"""
Defines a loss respective to unit shear response
Args:
batch: tf batch
Image stamps as ['obs_image'] and psf models as ['psf_image']
reconv_psf_image: tf tensor
Synthetic reconvolution psf
step: float
Step size for the f... | 910db625562a4b882a1205e3235cdf375b0e9788 | 3,638,880 |
from typing import List
import math
def batch_tokenize(sentences: List[str],
tokenizer: yttm.BPE,
batch_size: int = 256,
bos: bool = True,
eos: bool = True) -> List[List[int]]:
"""
Tokenize input sentences in batches.
:param sente... | 69a5995d52b255bbdbe5a8c9d9ac3c2bf0bbbee8 | 3,638,881 |
def blog_index(request):
"""The index of all blog posts"""
ctx = {}
entries = Page.objects.filter(blog_entry=True).order_by(
'-pinned', '-date_created')
paginator = Paginator(entries, 10)
page_num = request.GET.get('page')
ctx['BASE_URL'] = settings.BASE_URL
try:
entries = ... | ddc52e4d58adc5857d9f47345f8a80e472f68f81 | 3,638,882 |
def pair_time(pos_k, pos_l, vel_k, vel_l, radius):
""" pos_k, pos_l, vel_k, vel_l all have two elements as a list """
t_0=0.0
pos_x=pos_l[0]-pos_k[0]
pos_y=pos_l[1]-pos_k[1]
Delta_pos=np.array([pos_x, pos_y])
vel_x=vel_l[0]-vel_k[0]
vel_y=vel_l[1]-vel_k[1... | 9c751d7937bcbd71e6e1243ddff809c4d42113f2 | 3,638,884 |
from typing import Union
from pathlib import Path
from typing import List
from typing import Dict
def coco_to_shapely(inpath_json: Union[Path, str],
categories: List[int] = None) -> Dict:
"""Transforms COCO annotations to shapely geometry format.
Args:
inpath_json: Input filepath ... | 0762cebe554336080fcf2f4f31b37db0ee991b15 | 3,638,885 |
def create_activity_specific_breathing_rate_df(
person_breathing_in,
time,
event,
breathing_rate_key,
rounding=5
):
"""
Generate breathing rates taking into account age and activity intensity.
Parameters:
person_breathing_in: string
E.g. "person 1"
time: stri... | 953145a13166a0a6b84ed173a72213820d7b48b6 | 3,638,886 |
def find_valid_imported_name(name):
"""return a name preceding an import op, or False if there isn't one"""
return name.endswith(MARKER) and remove_import_op(name) | cd7473a8852ff3962fedf970d63564929911a808 | 3,638,887 |
def parseText(text1, nlp):
"""Run the Spacy parser on the input text that is converted to unicode."""
doc = nlp(text1)
return doc | 99d6a585358a700f8fc48c5dc4fc761a03ab42a7 | 3,638,888 |
def view_pebbles_home(request):
"""Serve up the workspace, the current home page.
Include global js settings"""
app_config = AppConfiguration.get_config()
if app_config is None:
return HttpResponseRedirect(reverse('view_no_domain_config_error'))
# Is this D3M Mode? If so, make sure:
# ... | c19dc920c9d064b2294d0f92eb762197271ace2e | 3,638,891 |
from openpyxl import load_workbook
def multi_pretty(request):
""" 批量添加(Excel文件)"""
if request.method == "GET":
return render(request, 'multi_pretty.html')
file_object = request.FILES.get("exc")
wb = load_workbook(file_object)
sheet = wb.worksheets[0]
for row in sheet.iter_rows(min_row=... | 571ce48fb1b0c13d85687cfcaba556599d299b00 | 3,638,892 |
import socket
def is_port_open(host, port, timeout=5):
"""
verifies if a port is open in a remote host
:param host: IP of the remote host
:type host: str
:param port: port to check
:type port: int
:param timeout: timeout max to check
:type timeout: int
:return: True if the port... | 1805727a3bb007cd5686475de686cf7bceac83a1 | 3,638,893 |
def check_transport_reaction_gpr_presence(model):
"""Return the list of transport reactions that have no associated gpr."""
return [
rxn
for rxn in helpers.find_transport_reactions(model)
if not rxn.gene_reaction_rule
] | 2bce7a49ce46a7dcd4b756cd9bc115f7bb227b36 | 3,638,894 |
def get_RSA_modulus(b, num):
"""
Generates a list of RSA modulus' of bit length b
such that each modulus, n = pq, where p and q are
both primes.
:param b: bit length of the modulus
:param num: number of modulus' you want
:returns: a list of RSA modulus'
"""
p_lst = []
# genera... | 5238f840ab6c732e852e195c75cd39ad35e709f1 | 3,638,895 |
from multiprocessing import cpu_count
def use_processors(n_processes):
"""
This routine finds the number of available processors in your machine
"""
available_processors = cpu_count()
n_processes = n_processes % (available_processors+1)
if n_processes == 0:
n_processes = 1
print(... | 73877393aac6b4da68fb0216bf046601ce1fa99e | 3,638,896 |
import json
def climate_radio_thermostat_ct101_multiple_temp_units_state_fixture():
"""Load the climate multiple temp units node state fixture data."""
return json.loads(
load_fixture(
"zwave_js/climate_radio_thermostat_ct101_multiple_temp_units_state.json"
)
) | 7a3493b8d065752b21e93d7fd2750b59f6079db8 | 3,638,897 |
def GetPseudoAAC1(ProteinSequence, lamda=30, weight=0.05, AAP=[]):
"""
#######################################################################################
Computing the first 20 of type I pseudo-amino acid compostion descriptors based on the given
properties.
####################################... | d451a5a2f9674a84a4a114d58a427e271721bfb9 | 3,638,899 |
def reversedict(dct):
""" Reverse the {key:val} in dct to
{val:key}
"""
# print labelmap
newmap = {}
for (key, val) in dct.iteritems():
newmap[val] = key
return newmap | f7a5a102546270a2e6aa7fb52d4fa6dd5e826753 | 3,638,900 |
def mock_graph_literal():
"""Creates a mock tree
Metasyntactic variables: https://www.ietf.org/rfc/rfc3092.txt
"""
graph_dict = [
{
"frame": {"name": "foo", "type": "function"},
"metrics": {"time (inc)": 130.0, "time": 0.0},
"children": [
{
... | 4b65f0dfffe705963c1041fbbef65d85af306f4f | 3,638,903 |
def parse_ADD_ins(tokens):
"""Attempts to parse an ADD instruction."""
failure = None
assert len(tokens) > 0
if tokens[0].text.upper() != 'ADD':
return failure
statement = Obj()
statement.type = 'STATEMENT'
statement.statement_type = 'INSTRUCTION'
statement.instruction = 'ADD'
... | ffc515d0079dbaf860a10de675542e798abfd4a3 | 3,638,904 |
import re
def commonIntegerPredicate(field):
""""return any integers"""
return tuple(re.findall("\d+", field)) | 955dc61fa4293f21c707b538ea218b15d5a95fb2 | 3,638,905 |
def spatialft(image, cosine_window=True, rmdc=True):
"""Take the fourier transform of an image (or flow field).
shift the quadrants around so that low spatial frequencies are in
the center of the 2D fourier transformed image"""
#raised cosyne window on image to avoid border artifacts
(dim1,dim2) = ... | cafca20ec79dcaca6d6dfb11c18156077b172ab0 | 3,638,906 |
def _get_instrument_parameters(ufile, filemetadata):
""" Return a dictionary containing instrument parameters. """
# pulse width
pulse_width = filemetadata('pulse_width')
pulse_width['data'] = ufile.get_pulse_widths() / _LIGHT_SPEED # m->sec
# assume that the parameters in the first ray represent... | af6ee2097848a672ec18c2199faece072f3990f1 | 3,638,907 |
import re
def split_reaction(reac):
""" split a CHEMKIN reaction into reactants and products
:param reac: reaction string
:type reac: str
:returns: reactants and products
:rtype: (tuple of strings, tuple of strings)
"""
em_pattern = one_of_these([PAREN_PLUS_EM + STRING_END,
... | d9ccbf02bd8f037d42f9de5f30612a99a1d7d918 | 3,638,909 |
def bond_stereo_parities(sgr):
""" bond parities, as a dictionary
"""
return mdict.by_key_by_position(bonds(sgr), bond_keys(sgr),
BND_STE_PAR_POS) | 7b80fdb861530e4389a83db1ef55f9552baf758d | 3,638,910 |
def encode(text):
"""
Encode to base64
"""
return [int(x) for x in text.encode('utf8')] | af51272d8edc25d46695ea3b35fd395ad26321b5 | 3,638,911 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.