content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def isempty(s):
"""
return if input object(string) is empty
"""
if s in (None, "", "-", []):
return True
return False | 9c3ffd6ab818e803c1c0129588c345361c58807f | 21,200 |
import sys
def get_client(host, port=None, username=None,
password=None, tenant=None,
auth_url=None, auth_strategy=None,
auth_token=None, region=None,
is_silent_upload=False, insecure=True,
aws_access_key=None, aws_secret_key=None):
"""
... | b1b7068787aebeaa5087e5f1d5334ad68debac3d | 21,201 |
def raw(text):
"""Returns a raw string representation of text"""
new_str = ''
for char in text:
try:
new_str += trans_map[char]
except KeyError:
new_str += char
return new_str | 528e88837bba76411b44044b566e2a645db4433e | 21,202 |
def airtovac(wave_air):
"""
taken from idl astrolib
;+
; NAME:
; AIRTOVAC
; PURPOSE:
; Convert air wavelengths to vacuum wavelengths
; EXPLANATION:
; Wavelengths are corrected for the index of refraction of air under
; standard conditions. Wavelength values below... | 68d71855f0fa8256acc23bfd24d68985cfc1f3a7 | 21,203 |
def clamp(val, min_, max_):
"""clamp val to between min_ and max_ inclusive"""
if val < min_:
return min_
if val > max_:
return max_
return val | 31f2441ba03cf765138a7ba9b41acbfe21b7bda7 | 21,204 |
def GetUserLink(provider, email):
"""Retrieves a url to the profile of the specified user on the given provider.
Args:
provider: The name of the provider
email: The email alias of the user.
Returns:
Str of the url to the profile of the user.
"""
user_link = ''
if email and provider == Provider.... | ad5f30e7e04000369d45d242b18afc59922da9bc | 21,205 |
def _as_bytes0(path):
"""Crashes translation if the path contains NUL characters."""
res = _as_bytes(path)
rstring.check_str0(res)
return res | 76c9c130d1a74f9cacb34e30141db74400f6ea33 | 21,206 |
def get_ip(request):
"""Determines user IP address
Args:
request: resquest object
Return:
ip_address: requesting machine's ip address (PUBLIC)
"""
ip_address = request.remote_addr
return ip_address | 84e1540bc8b79fd2043a8fb6f107f7bcd8d7cc8c | 21,207 |
def _is_valid_new_style_arxiv_id(identifier):
"""Determine if the given identifier is a valid new style arXiv ID."""
split_identifier = identifier.split('v')
if len(split_identifier) > 2:
return False
elif len(split_identifier) == 2:
identifier, version = split_identifier
if not... | 71171984ad1497fa45e109b9657352c20bfe7682 | 21,208 |
def download_suite(request, domain, app_id):
"""
See Application.create_suite
"""
if not request.app.copy_of:
request.app.set_form_versions(None)
return HttpResponse(
request.app.create_suite()
) | 382817e3a790d59c33c69eb5334841d2d9a1a7af | 21,209 |
def get_graph(mol):
""" Converts `rdkit.Chem.Mol` object to `PreprocessingGraph`.
"""
if mol is not None:
if not C.use_aromatic_bonds:
rdkit.Chem.Kekulize(mol, clearAromaticFlags=True)
molecular_graph = PreprocessingGraph(molecule=mol, constants=C)
return molecular_graph | 3d105de313ab1aed6ed0fff598e791cd903e94de | 21,210 |
def dict_fetchall(cursor):
"""
Returns all rows from a cursor as a dict
"""
desc = cursor.description
return [
dict(zip([col[0] for col in desc], row))
for row in cursor.fetchall()
] | 6d5e6621ac2cb6229f7caf6714cbc0124a33c271 | 21,211 |
def count_vowels(s):
"""Used to count the vowels in the sequence"""
s = s.lower()
counter=0
for x in s:
if(x in ['a','e','i','o','u']):
counter+=1
return counter | 236500c76b22510e6f0d97a4200865e2a18b47c3 | 21,212 |
def _is_valid_dtype(matrix, complex_dtype=False, all_dtype=False):
""" Check to see if it's a usable float dtype """
if all_dtype:
return matrix.dtype in NUMPY_FLOAT_DTYPES + NUMPY_COMPLEX_DTYPES
elif complex_dtype:
return matrix.dtype in NUMPY_COMPLEX_DTYPES
else:
return matrix.... | 1ca4a79082f170f53a905773b42fa8cb833e4016 | 21,213 |
def assess_edge(self, edge, fsmStack, request, **kwargs):
"""
Try to transition to ASSESS, or WAIT_ASSESS if not ready,
or jump to ASK if a new question is being asked.
"""
fsm = edge.fromNode.fsm
if not fsmStack.state.linkState: # instructor detached
return fsm.get_node('END')
elif... | e09d07afbc37c73188bbb5e6fa3436c88fce9bd7 | 21,214 |
def viable_source_types_for_generator_real (generator):
""" Returns the list of source types, which, when passed to 'run'
method of 'generator', has some change of being eventually used
(probably after conversion by other generators)
"""
source_types = generator.source_types ()
if not s... | e946663241fb77d3632f88b2f879d650e65f6d73 | 21,215 |
def negSamplingCostAndGradient(predicted, target, outputVectors, dataset,
K=10):
""" Negative sampling cost function for word2vec models
Implement the cost and gradients for one predicted word vector
and one target word vector as a building block for word2vec
models, usin... | d4b8a16166406f9e13296b8b5c53c56f95ff9d6b | 21,216 |
def get_start_block(block):
"""
Gets the deepest block to use as the starting block.
"""
if not block.get('children'):
return block
first_child = block['children'][0]
return get_start_block(first_child) | e658954bb69f88f10c2f328c605d6da094ba065d | 21,217 |
def transform_rank_list(lam_ref, A, b, rank):
"""
A is a list here. We sum the first `rank` elements of it
to return a matrix with the desired rank.
"""
_A = sum(A[0:rank])
_b = b
_d = _A @ lam_ref + _b
assert np.linalg.matrix_rank(_A) == rank, "Unexpected rank mismatch"
return _A, _... | 2b77db3cb27ce3b66d0038042d649226e5a231d2 | 21,218 |
def FindWindowsWithTitle(title_to_search):
"""Finds windows with given title.
Args:
title_to_search: Window title substring to search, case-insensitive.
Returns:
A list of HWND that match the search condition.
"""
desktop_handle = None
return FindWindowsWithText(desktop_handle, title_to_search) | bcc75a4351969cfdbb475032d556e73a4b0ceb92 | 21,219 |
import time
def main_update(next_image_step):
"""
This includes some functionality for image / file writing at a specified frequency,
Assumes global variables:
time, step, files_freq, next_image_step
if numerical dt exceeds next specified writing point
override dt make sure we hi... | 6a402c70948dc90aade783b94b054ef5abf8225c | 21,220 |
from typing import Iterable
import time
import os
def record(packets: Iterable[Packet],
pcap_path: str,
*,
src_ip: str = "127.0.0.1",
dst_ip: str = "127.0.0.1",
lidar_port: int = 7502,
imu_port: int = 7503,
use_sll_encapsulation: bool = Fals... | 0a02f7d919352e1b75c8af59cd807706ee0d131e | 21,221 |
def assemble_batches(inputs, crop_mode='center_only'):
"""
Assemble DataFrame of image crops for feature computation.
Input:
inputs: list of filenames (center_only, corners, and selective_search mode)
OR input DataFrame (list mode)
mode: string
'list': take the image windows from the input as... | f22f3ed33b339a4375a1e3319d26cb2946762978 | 21,222 |
def __VF2_feasible(graph1, graph2, vertex1, vertex2, map21, map12, terminals1,
terminals2, subgraph):
"""
Returns :data:`True` if two vertices `vertex1` and `vertex2` from graphs
`graph1` and `graph2`, respectively, are feasible matches. `mapping21` and
`mapping12` are the current state of the mappi... | f3ebfa379d710f5e1c6651713c15e9c6148d576d | 21,223 |
async def place_rectangle(
interface, element, x, y, width, height, include_all_sides=True, variant=None
):
"""Place a rectangle of an element.
Parameters
----------
interface
The editor interface.
x
X coordinate of the upper left corner.
y
Y coordinate of the upper ... | e9b2c16e77627dc3e0cac5f0abfcdce23db5eb29 | 21,224 |
def rainbow_strokes(strokes: bpy.types.GPencilStrokes):
"""
strokesのインデックスに合せて頂点カラーを設定します
"""
n = [colorize_stroke(stroke, i, True) for i, stroke in enumerate(strokes)]
return n
# logger.debug(f"update:{sum(n)}")
# logger.debug(rainbow.cache_info()) | 2ad0f0811e7b3c4f925a1cb21c2d0cfa374bdcf0 | 21,225 |
def calc_Q_hat_hs_d_t(Q, A_A, V_vent_l_d_t, V_vent_g_i, mu_H, mu_C, J_d_t, q_gen_d_t, n_p_d_t, q_p_H, q_p_CS, q_p_CL, X_ex_d_t, w_gen_d_t, Theta_ex_d_t, L_wtr, region):
"""(40-1a)(40-1b)(40-2a)(40-2b)(40-2c)(40-3)
Args:
Q: 当該住戸の熱損失係数(W/(m2・K))
A_A: 床面積の合計(m2)
V_vent_l_d_t: 日付dの時刻tにおける局所換気量(m3... | 64dd272673507b15a2d2c1782a0c3db88c3f8d76 | 21,226 |
def get_all_infoproviders():
"""
Endpunkt `/infoproviders`.
Response enthält Informationen über alle, in der Datenbank enthaltenen, Infoprovider.
"""
try:
return flask.jsonify(queries.get_infoprovider_list())
except Exception:
logger.exception("An error occurred: ")
err ... | 73966c2a5b171baead9edccec27f6380f61fb2ab | 21,227 |
import math
def maidenhead(dec_lat, dec_lon):
"""Convert latitude and longitude to Maidenhead grid locators."""
try:
dec_lat = float(dec_lat)
dec_lon = float(dec_lon)
except ValueError:
return ''
if _non_finite(dec_lat) or _non_finite(dec_lon):
return ''
if 90 < ma... | 63e44fffbf113f7c8a195b58556eef80a66690f7 | 21,228 |
def parse_worker_string(miner, worker):
"""
Parses a worker string and returns the coin address and worker ID
Returns:
String, String
"""
worker_part_count = worker.count(".") + 1
if worker_part_count > 1:
if worker_part_count == 2:
coin_address, worker = worker.s... | 3492716fc9f5290a161de0b46e7af87afbe6b348 | 21,229 |
import json
def get_inference_sequence(file_path):
"""
:param file_path: path of 2D bounding boxes
:return:
"""
with open(file_path + '.json', 'r') as f:
detected_bdbs = json.load(f)
f.close()
boxes = list()
for j, bdb2d in enumerate(detected_bdbs):
box = bdb2d['bbo... | a77b5f24004acf9839881cd52ce06b6f785f9bfb | 21,230 |
def _DC_GetBoundingBox(self):
"""
GetBoundingBox() -> (x1,y1, x2,y2)
Returns the min and max points used in drawing commands so far.
"""
return (self.MinX(), self.MinY(), self.MaxX(), self.MaxY()) | 47dc9e8bbc429dbd079695844c9bbcfc79b26229 | 21,231 |
from typing import Union
from typing import Iterable
from typing import List
def map_text(
text: Union[str, Text, Iterable[str], Iterable[Text]],
mapping: StringMapper
) -> Union[str, List[str]]:
"""
Replace text if it matches one of the dictionary keys.
:param text: Text instance(s) to m... | 63c9dc6803d1aad572e76cb2a6554363ae358e9c | 21,232 |
def _load_components(config: ConfigType) -> ConfigType:
"""Load the different componenets in a config
Args:
config (ConfigType)
Returns:
ConfigType
"""
special_key = "_load"
if config is not None and special_key in config:
loaded_config = read_config_file(config.pop(spe... | b00e2225df4d493636c509380c3c19c107ad32e6 | 21,233 |
import typing
def _value_to_variant(value: typing.Union[bytes, int, float, str]) -> GLib.Variant:
"""
Automatically convert a Python value to a GLib.Variant by guessing the
matching variant type.
"""
if isinstance(value, bool):
return GLib.Variant("b", value)
elif isinstance(value, by... | 8b16bad781954238174a160df5239c0b8cb88e2e | 21,234 |
import math
def ha_rise_set(el_limit, lat, dec):
"""
Hour angle from transit for rising and setting.
Returns pi for a source that never sets and 0 for a source always below
the horizon.
@param el_limit : the elevation limit in radians
@type el_limit : float
@param lat : the observatory latitude in r... | 648de7a69039d73f3947706ecc4ee90e1d05597e | 21,235 |
def create(transactions, user=None):
"""# Create Transactions
Send a list of Transaction objects for creation in the Stark Bank API
## Parameters (required):
- transactions [list of Transaction objects]: list of Transaction objects to be created in the API
## Parameters (optional):
- user [Proje... | 32573a0e569fde73c6eaf228ad6a07849297c7b9 | 21,236 |
def get_quote(symbol):
"""
Returns today's stock price
"""
contents = get_content(symbol)
return contents('.time_rtq_ticker span').text() | 546ac10e5f7d5b3cc661dde5dceec8c4a8b0fae0 | 21,237 |
def load_pil(data, is_file = False):
""" Parses a string or file written in PIL notation! """
# We only assign reactions in a postprocessing step,
# because there are no macrostates in nuskell.
set_io_objects(D = NuskellDomain, C = NuskellComplex)
out = dsd_read_pil(data, is_file)
clear_io_objec... | 0fe0b507d19595f71d18d24e1f003fbaa59485fc | 21,238 |
def get(obj, key, default=None, pattern_default=(), apply_transforms=True):
"""
Get a value specified by the dotted key. If dotted is a pattern,
return a tuple of all matches
>>> d = {'hello': {'there': [1, '2', 3]}}
>>> get(d, 'hello.there[1]|int')
2
>>> get(d, 'hello.there[1:]')
['2', ... | b6b84a357e18fa0e78d6520ba50ff5668a97067c | 21,239 |
def str_view(request):
"""
A simple test view that returns a string.
"""
return '<Response><Message>Hi!</Message></Response>' | fd9d150afdf0589cdb4036bcb31243b2e22ef1e2 | 21,240 |
import atexit
def _run_script(script, start_with_ctty, args, kwargs):
"""
Meant to be called inside a python subprocess, do NOT call directly.
"""
enter_pty(start_with_ctty)
result = script(*args, **kwargs)
# Python-spawned subprocesses do not call exit funcs - https://stackoverflow.com/q/3450... | 15507307bb85013d9354b7506569b69806bdf06a | 21,241 |
def get_feed_list(feeds):
""" Return List of Proto Feed Object
"""
feeds_pb_list = [feeds_pb2.Feed(**_get_valid_fields_feed(feed)) for feed in feeds]
return feeds_pb2.FeedList(data=feeds_pb_list) | 6e79c563649aef60396f0c8944d3532fabc17bc0 | 21,242 |
def group_interpellet_interval_plot(FEDs, groups, kde, logx, **kwargs):
"""
FED3 Viz: Plot the interpellet intervals as a histogram, first aggregating
the values for devices in a Groups.
Parameters
----------
FEDs : list of FED3_File objects
FED3 files (loaded by load.FED3_File)
gro... | 5c0ada4fdf71af7cfed8ffe7ec8b656c8984de9b | 21,243 |
def _beta(x, p):
"""Helper function for `pdf_a`, beta = pi * d(1 - omega(x), omega(p))."""
omega = _amplitude_to_angle
return np.pi * _circ_dist(1 - omega(x), omega(p)) | 9f0defbff0567ba8c181a9565570d0c7444ddc94 | 21,244 |
def set_reporting_max_width(w):
"""
Set the max width for reported parameters. This is used to that failures don't overflow
terminals in the event arguments are dumped.
:param w: The new max width to enforce for the module
:type w: int
:return: True
"""
_REPR_MAX_WIDTH[0] = int(w)
r... | 5da03b359fc823919bf2782907a0717c1d303a31 | 21,245 |
import re
def get_version():
"""Get LanguageTool version."""
version = _get_attrib().get('version')
if not version:
match = re.search(r"LanguageTool-?.*?(\S+)$", get_directory())
if match:
version = match.group(1)
return version | 1223b13b23eb4dadafbc5a3e8bf3b6e7f521ab5b | 21,246 |
def get_mnsp_offer_index(data) -> list:
"""Get MNSP offer index"""
interconnectors = (data.get('NEMSPDCaseFile').get('NemSpdInputs')
.get('PeriodCollection').get('Period')
.get('InterconnectorPeriodCollection')
.get('InterconnectorPeriod'))
... | 46211e9a29f1fd1fd3148deaaaa064b6d6b05ca7 | 21,247 |
from typing import Tuple
def _find_clusters(
data,
cluster_range: Tuple[int, int] = None,
metric: str = "silhouette_score",
target=None,
**kwargs,
):
"""Finds the optimal number of clusters for K-Means clustering using the selected metric.
Args:
data: The data.
cluster_ran... | a73afd74a6401799b6418e45372aee04cf353cb3 | 21,248 |
def _gate_objectives_li_pe(basis_states, gate, H, c_ops):
"""Objectives for two-qubit local-invariants or perfect-entangler
optimizaton"""
if len(basis_states) != 4:
raise ValueError(
"Optimization towards a two-qubit gate requires 4 basis_states"
)
# Bell states as in "Theor... | 76be659f97396384102706fe0bc101a7d85d6521 | 21,249 |
from typing import Generator
import pkg_resources
def get_pip_package_list(path: str) -> Generator[pkg_resources.Distribution, None, None]:
"""Get the Pip package list of a Python virtual environment.
Must be a path like: /project/venv/lib/python3.9/site-packages
"""
packages = pkg_resources.find_dis... | 9e73e27c2b50186dedeedd1240c28ef4f4d50e03 | 21,250 |
from OpenGL.GLU import gluGetString, GLU_EXTENSIONS
def hasGLUExtension( specifier ):
"""Given a string specifier, check for extension being available"""
if not AVAILABLE_GLU_EXTENSIONS:
AVAILABLE_GLU_EXTENSIONS[:] = gluGetString( GLU_EXTENSIONS )
return specifier.replace(as_8_bit('.'),as_8_bit('_... | cf938ec4d0ec16ae96faa10c50ac5b4bc541a062 | 21,251 |
def do_slots_information(parser, token):
"""Calculates some context variables based on displayed slots.
"""
bits = token.contents.split()
len_bits = len(bits)
if len_bits != 1:
raise TemplateSyntaxError(_('%s tag needs no argument') % bits[0])
return SlotsInformationNode() | e52d724abb435c1b8cba68c352977a1d6c1e1c12 | 21,252 |
def get_region_of_interest(img, sx=0.23, sy=0.15, delta=200, return_vertices=False):
"""
:param img: image to extract ROI from
:param sx: X-axis factor for ROI bottom base
:param sy: Y-axis factor for ROI top base
:param delta: ROI top base length
:param return_vertices: whether to return the RO... | 932588f34ba9cd7e4e71b35df60cf03f40574fad | 21,253 |
from typing import Counter
import json
def load_search_freq(fp=SEARCH_FREQ_JSON):
"""
Load the search_freq from JSON file
"""
try:
with open(fp, encoding="utf-8") as f:
return Counter(json.load(f))
except FileNotFoundError:
return Counter() | 5d5e1d1106a88379eab43ce1e533a7cbb5da7eb6 | 21,254 |
def _sum_of_squares(a, axis=0):
"""
Square each element of the input array, and return the sum(s) of that.
Parameters
----------
a : array_like
Input array.
axis : int or None, optional
Axis along which to calculate. Default is 0. If None, compute over
the whole array `a... | 5271d40b096e4f6f47e010bf0974bc77804a3108 | 21,255 |
import logging
def get_preprocess_fn(pp_pipeline, remove_tpu_dtypes=True):
"""Transform an input string into the preprocessing function.
The minilanguage is as follows:
fn1|fn2(arg, arg2,...)|...
And describes the successive application of the various `fn`s to the input,
where each function can optiona... | ef3065252b3aa67cebc6a041eba33711e7a17f82 | 21,256 |
def nodeset(v):
"""Convert a value to a nodeset."""
if not nodesetp(v):
raise XPathTypeError, "value is not a node-set"
return v | ccaada2ad8610e0b3561663aab8e90665f6c23de | 21,257 |
import tqdm
def get_char_embs(char_emb_path, char_emb_size, alphabet_size=1422):
"""Get pretrained character embeddings and a dictionary mapping characters to their IDs.
Skips IDs 0 and 1, since these are reserved for PAD and UNK, respectively.
Input:
char_emb_path: path to glove.840B.{char_embeddi... | d4be3ed7780efb3ca378c18d805ff7c5550d98d7 | 21,258 |
def _get_reverse_complement(seq):
"""
Get the reverse compliment of a DNA sequence.
Parameters:
-----------
seq
Returns:
--------
reverse_complement_seq
Notes:
------
(1) No dependencies required. Pure python.
"""
complement_seq = ""
for i in seq... | 31408767c628ab7b0e6e63867e37f11eb6e19560 | 21,259 |
def wave_reduce_min_all(val):
"""
All threads get the result
"""
res = wave_reduce_min(val)
return broadcast(res, 0) | dfac75ecd9aeb75dc37cbaa7d04ce2a2732b9ce9 | 21,260 |
def predict_class(all_headlines):
"""
Predict whether each headline is negative or positive.
:param all_headlines: all headlines
:return: headlines with predictions
"""
clf, v = load_classifier("SVM")
headlines = []
for h in all_headlines:
headlines.append(h.to_array())
df... | 38839eba678659529b7fe83d6dc09ffd3cf87e48 | 21,261 |
def find_tickets_for_seat_manager(
user_id: UserID, party_id: PartyID
) -> list[DbTicket]:
"""Return the tickets for that party whose respective seats the user
is entitled to manage.
"""
return db.session \
.query(DbTicket) \
.filter(DbTicket.party_id == party_id) \
.filter(D... | c59af6629a402f3844e01c5dd86553b8e5d33d64 | 21,262 |
import inspect
from typing import Counter
def insert_features_from_iters(dataset_path, insert_features, field_names, **kwargs):
"""Insert features into dataset from iterables.
Args:
dataset_path (str): Path of the dataset.
insert_features (iter of iter): Collection of iterables representing
... | d6f4547b33a09391188beb96cf408f3148ef643e | 21,263 |
def check_table(conn, table, interconnect):
"""
searches if Interconnect exists in table in database
:param conn: connect instance for database
:param table: name of table you want to check
:param interconnect: name of the Interconnect you are looking for
:return: results of SQL query searching... | 0888146d5dfe20e7bdfbfe078c58e86fda43d6a5 | 21,264 |
import tarfile
def get_host_config_tar_response(host):
"""
Build the tar.gz attachment response for the GetHostConfig view.
Note: This is re-used to download host config from the admin interface.
:returns: HttpResponseAttachment
"""
filename = '{host}_v{version}.tar.gz'.format(
... | 8a968885bb197f781faf65abf100aa40568f6354 | 21,265 |
async def update_product_remove_tag_by_id(
*,
product_id: int,
session: Session = Depends(get_session),
db_product: Product = Depends(get_product_or_404),
db_tag: Tag = Depends(get_tag_or_404),
):
"""
Remove tag from product
"""
existing_product = db_product["db_product"]
existin... | 41893e64fa02f24df26ed39128657218cbc87231 | 21,266 |
def aggregate_results_data(results, include_raw=False):
"""This function aggregates the results of an archive/unarchive operation into an easy-to-parse dictionary.
.. versionchanged:: 4.1.1
This function can now properly handle the ``ARCHIVED`` status when returned.
.. versionadded:: 4.1.0
:pa... | 5d5a48ad054fc61ebbc6b68530d51ac865fa6f6a | 21,267 |
def hard_sigmoid(x: tf.Tensor) -> tf.Tensor:
"""Hard sigmoid activation function.
```plot-activation
activations.hard_sigmoid
```
# Arguments
x: Input tensor.
# Returns
Hard sigmoid activation.
"""
return tf.clip_by_value(x+0.5, 0.0, 1.0) | 203a41d52888b42b643df84986c5fbc8967222c6 | 21,268 |
def get_image_as_np_array(filename: str):
"""Returns an image as an numpy array
"""
img = Image.open(filename)
return np.asarray(img) | 8d3cc1c5311e675c6c710cbd7633a66748308e7d | 21,269 |
def unreduced_coboundary(morse_complex, akq, cell_ix):
""" Helper """
return unreduced_cells(akq, morse_complex.get_coboundary(cell_ix)) | c074a9b7df35f961e66e31a88c8a7f95f48912c7 | 21,270 |
from typing import Union
def __align(obj: Union[Trace, EventLog], pt: ProcessTree, max_trace_length: int = 1,
max_process_tree_height: int = 1, parameters=None):
"""
this function approximates alignments for a given event log or trace and a process tree
:param obj: event log or single trace
... | 0f684403bb70a158c463b4babcada115e908ee88 | 21,271 |
import resource
def scanProgramTransfersCount(program, transfersCount=None, address=None, args={}):
"""
Scan pools by active program, sort by transfersCount
"""
return resource.scan(**{**{
'type': 'pool',
'index': 'activeProgram',
'indexValue': program,
'sort': 'transfe... | b40a0ff2ea62f840a6c2fd858516dc8998aac30b | 21,272 |
from pedal.tifa.commands import get_issues
from pedal.tifa.feedbacks import initialization_problem
def def_use_error(node, report=MAIN_REPORT):
"""
Checks if node is a name and has a def_use_error
Args:
node (str or AstNode or CaitNode): The Name node to look up.
report (Report): The repo... | 6e0113c451a2c09fdb84392060b672ffb3bc19d3 | 21,273 |
def get_ref_inst(ref):
"""
If value is part of a port on an instance, return that instance,
otherwise None.
"""
root = ref.root()
if not isinstance(root, InstRef):
return None
return root.inst | 55f1a84131451a2032b7012b00f9336f12fee554 | 21,274 |
def not_found(error):
"""
Renders 404 page
:returns: HTML
:rtype: flask.Response
"""
view_args["title"] = "Not found"
return render_template("404.html", args=view_args), 404 | 8882f171c5e68f3b24a1a7bd57dbd025a4b3a070 | 21,275 |
def xml_escape(x):
"""Paranoid XML escaping suitable for content and attributes."""
res = ''
for i in x:
o = ord(i)
if ((o >= ord('a')) and (o <= ord('z'))) or \
((o >= ord('A')) and (o <= ord('Z'))) or \
((o >= ord('0')) and (o <= ord('9'))) or \
... | 018dc7d1ca050641b4dd7198e17911b8d17ce5fc | 21,276 |
def read_tab(filename):
"""Read information from a TAB file and return a list.
Parameters
----------
filename : str
Full path and name for the tab file.
Returns
-------
list
"""
with open(filename) as my_file:
lines = my_file.readlines()
return lines | 8a6a6b0ec693130da7f036f4673c89f786dfb230 | 21,277 |
def build_model(stage_id, batch_size, real_images, **kwargs):
"""Builds progressive GAN model.
Args:
stage_id: An integer of training stage index.
batch_size: Number of training images in each minibatch.
real_images: A 4D `Tensor` of NHWC format.
**kwargs: A dictionary of
'start_height': An... | d188ef5672e928b1935a97ade3d26614eb700681 | 21,278 |
def int2(c):
""" Parse a string as a binary number """
return int(c, 2) | dd1fb1f4c194e159b227c77c4246136863646707 | 21,279 |
from typing import Any
from typing import Type
from typing import List
from typing import Dict
def from_serializer(
serializer: serializers.Serializer,
api_type: str,
*,
id_field: str = "",
**kwargs: Any,
) -> Type[ResourceObject]:
"""
Generate a schema from a DRF serializer.
:param s... | 4fb2c0fb83c26d412de5582a8ebfeb4c72ac7add | 21,280 |
def inv_rotate_pixpts(pixpts_rot, angle):
"""
Inverse rotate rotated pixel points to their original positions.
Keyword arguments:
pixpts_rot -- namedtuple of numpy arrays of x,y pixel points rotated
angle -- rotation angle in degrees
Return value:
pixpts -- namedtuple of numpy arrays of pi... | 793b148a0c37d321065dc590343de0f4093abcff | 21,281 |
import logging
import functools
import time
def logged(func=None, level=logging.DEBUG, name=None, msg=None):
"""Decorator to log the function, with the duration.
Args:
-----
func (function): the function to log
level (logging.OBJECT): INFO, DEBUG, WARNING ...
n... | 3110b7744618c56a42516409dc73c590e97c9d18 | 21,282 |
def properties(classes):
"""get all property (p-*, u-*, e-*, dt-*) classnames
"""
return [c.partition("-")[2] for c in classes if c.startswith("p-")
or c.startswith("u-") or c.startswith("e-") or c.startswith("dt-")] | 417562d19043f4b98068ec38cc010061b612fef3 | 21,283 |
import array
def adapt_p3_histogram(codon_usages, purge_unwanted=True):
"""Returns P3 from each set of codon usage for feeding to hist()."""
return [array([c.positionalGC(purge_unwanted=True)[3] for c in curr])\
for curr in codon_usages] | d5b0b0b387c3a98f584ca82dad79effbb9aa7a31 | 21,284 |
def handle_logout_response(response):
"""
Handles saml2 logout response.
:param response: Saml2 logout response
"""
if len(response) > 1:
# Currently only one source is supported
return HttpResponseServerError("Logout from several sources not supported")
for entityid, logout_inf... | 18d8983a3e01905e1c7c6b41b65eb7e9191a4bf5 | 21,285 |
def get_value_beginning_of_year(idx, col, validate=False):
"""
Devuelve el valor de la serie determinada por df[col] del
primer día del año del índice de tiempo 'idx'.
"""
beggining_of_year_idx = date(year=idx.date().year, month=1, day=1)
return get_value(beggining_of_year_idx, col, validate) | b3a267620f19cabe1492aea671d34f1142580a5d | 21,286 |
from typing import List
def doc2vec_embedder(corpus: List[str], size: int = 100, window: int = 5) -> List[float]:
"""
Given a corpus of texts, returns an embedding (representation
of such texts) using a fine-tuned Doc2Vec embedder.
ref: https://radimrehurek.com/gensim/models/doc2vec.html
"""
... | e14eb3c1daca1c24f9ebeaa04f44091cc12b03ff | 21,287 |
def PremIncome(t):
"""Premium income"""
return SizePremium(t) * PolsIF_Beg1(t) | 1673f5a18171989e15bdfd7fa3e814f8732fd732 | 21,288 |
def _setter_name(getter_name):
""" Convert a getter name to a setter name.
"""
return 'set' + getter_name[0].upper() + getter_name[1:] | d4b55afc10c6d79a1432d2a8f3077eb308ab0f76 | 21,289 |
def get_bel_node_by_pathway_name():
"""Get Reactome related eBEL nodes by pathway name."""
pathway_name = request.args.get('pathway_name')
sql = f'''SELECT
@rid.asString() as rid,
namespace,
name,
bel,
reactome_pathways
FROM
pro... | 930bb79f70c050acaa052d684de389fc2eee9c36 | 21,290 |
def get_model(model_file, log=True):
"""Load a model from the specified model_file."""
model = load_model(model_file)
if log:
print('Model successfully loaded on rank ' + str(hvd.rank()))
return model | ad699c409588652ac98da0f29b2cb25c53216a46 | 21,291 |
def variable_op(shape, dtype, name="Variable", set_shape=True, container="",
shared_name=""):
"""Deprecated. Used variable_op_v2 instead."""
if not set_shape:
shape = tensor_shape.unknown_shape()
ret = gen_state_ops.variable(shape=shape, dtype=dtype, name=name,
c... | 3a799880ed22d6983906c72f939b46f404362288 | 21,292 |
def _sample_weight(kappa, dim, num_samples):
"""Rejection sampling scheme for sampling distance from center on
surface of the sphere.
"""
dim = dim - 1 # since S^{n-1}
b = dim / (np.sqrt(4.0 * kappa ** 2 + dim ** 2) + 2 * kappa)
x = (1.0 - b) / (1.0 + b)
c = kappa * x + dim * np.log(1 - x *... | 5760bfe205468e9d662ad0e8d8afa641fa45db2c | 21,293 |
import torch
def variable_time_collate_fn3(
batch,
args,
device=torch.device("cpu"),
data_type="train",
data_min=None,
data_max=None,
):
"""
Expects a batch of time series data in the form of (record_id, tt, vals, mask, labels) where
- record_id is a patient id
- tt is a 1-... | 5158f7ab642ab33100ec5fc1c044e20edd90687c | 21,294 |
import operator
def run_map_reduce(files, mapper, n):
"""Runner to execute a map-reduce reduction of cowrie log files using mapper and files
Args:
files (list of files): The cowrie log files to be used for map-reduce reduction.
mapper (MapReduce): The mapper processing the files using... | a46779fa5546c0e414a6dd4921f52c28cc80535e | 21,295 |
import select
def metadata_record_dictize(pkg, context):
"""
Based on ckan.lib.dictization.model_dictize.package_dictize
"""
model = context['model']
is_latest_revision = not(context.get('revision_id') or
context.get('revision_date'))
execute = _execute if is_lates... | f049faf30322d5d4da45e2a424a6977c894db67c | 21,296 |
def is_data_by_filename(fname):
"""
TODO
this is super adhoc. FIXME
"""
return "Run201" in fname | f6fd006809dff852b4acf8987aa09bafd28bf3e3 | 21,297 |
def colorbar_set_label_parallel(cbar,label_list,hpos=1.2,vpos=-0.3,
ha='left',va='center',
force_position=None,
**kwargs):
"""
This is to set colorbar label besie the colorbar.
Parameters:
-----------
cb... | 811358f254b05d7fa243c96d91c94ed3cb1d1fcd | 21,298 |
def read_csv(file, tz):
"""
Reads the file into a pandas dataframe, cleans data and rename columns
:param file: file to be read
:param tz: timezone
:return: pandas dataframe
"""
ctc_columns = {1: 'unknown_1',
2: 'Tank upper', # temperature [deg C]
3: 'u... | 9e9ed864dcba6878562ae8686dab1d1f2650f5b3 | 21,299 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.