content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def ap(a: Any, b: Any) -> Any:
"""approximately
the value for the parameter in the resource is approximately the same
to the provided value. Note that the recommended value for the approximation
is 10% of the stated value (or for a date, 10% of the gap between now and the date),
but systems may choo... | 58,600 |
def set_axes(ax: Axes, x_scale: str = 'linear', y_scale: str = 'linear', xlim: tuple = (), ylim: tuple = (),
fontsize: int = 20, show_grid: bool = True,
hide_xticklabels: bool = False, hide_yticklabels: bool = False) -> Axes:
"""
Sets axes to an existing ax. The explanation of the argu... | 58,601 |
def readlinkabs(link: str) -> str:
"""Return an absolute path to symbolic link destination."""
# Adapted from code by Greg Smith.
assert os.path.islink(link)
path = os.readlink(link)
if os.path.isabs(path):
return path
return os.path.join(os.path.dirname(link), path) | 58,602 |
def parallel_run(tasks):
"""
Tasks is an iterable of bound functions. The wrapper makes it easy for us
to run a list of different functions, rather than one function over a list
of inputs.
"""
workers = max(1, len(tasks))
with Pool(processes=workers) as pool:
# As soon as any one ta... | 58,603 |
def bgr_to_hex(b, g, r):
"""Converts (blue, green, red) to a "#rrbbgg" string.
Args:
b, g, r: the BGR values
Returns:
a hex string
"""
return rgb_to_hex(r, g, b) | 58,604 |
def find_orphans():
"""
Print jobs that are running on non-service accounts on the nodes that squeue isn't aware of.
"""
# make a list of orphans
node_names = get_node_names()
running_user_node_names = set(get_running_user_node_names())
orphan_list = []
for node_name, user, pid, cmd in ... | 58,605 |
def check_job_io(infiles, outfiles, extra_params):
"""
cat input files content to output files
after writing out job parameters
"""
# dump parameters
params = (infiles, outfiles) + extra_params
if isinstance(infiles, str):
infiles = [infiles]
elif infiles is None:
in... | 58,606 |
def get_all_csv_files_in_folder(folder: str) -> List[str]:
"""Returns list of strings including path to folder for CSV files"""
return get_all_files_in_folder_ending_with(folder=folder, ending=OUTPUT_FILE_ENDING) | 58,607 |
def linear_correct_byte(image: numpy.ndarray, gamma: float = 2.2) -> numpy.ndarray:
"""
:param image:
:type image:
:param gamma:
:type gamma:
:return:
:rtype:"""
return gamma_correct_float_to_byte(image / 255, gamma) | 58,608 |
def is_authenticated(request, username, password):
"""Authenticate the request using HTTP Basic authorization"""
authenticated = False
if 'HTTP_AUTHORIZATION' in request.META:
auth = request.META['HTTP_AUTHORIZATION'].split()
if len(auth) == 2:
if auth[0].lower() == "basic":
... | 58,609 |
def open_file(value):
"""Receive a file_obj or filename, return a file_obj.
"""
if hasattr(value, 'read') or hasattr(value, 'write'):
yield value
else:
with open(value) as f:
yield f | 58,610 |
def inspect_object(object_: object):
"""Find all members of Python object.
Example:
def say_hi(name: str) -> str:
print(f"hi {name}")
print(inspect_object(say_hi))
>>> say_hi=>
type=<class 'function'>
parameters=>
name=>
annotation=<class 'str'>
default=None
kind=POSITIONAL_OR_KEYWORD
... | 58,611 |
def recall(prediction, ground_truth, average="macro"):
"""
Return the recall score evaluated between PREDICTION and GROUND_TRUTH
average - (default: "macro") mode of averaging for multi-class prediction
"""
return metrics.recall_score(
prediction,
ground_truth,
... | 58,612 |
def convert_json_last_probabilities(sql_fp, json_fp):
"""Get the last ranking from a json state and save it as the table
'last_probabilities' in the .sql file at the location of sql_fp.
Arguments
---------
sql_fp: str/path
Path where to save the record table. Should be a .sql file.
json... | 58,613 |
def tf_lipschitz_constant(M, G, phi, phiT, tol=1e-3, verbose=None):
"""Compute lipschitz constant for FISTA
It uses a power iteration method.
"""
n_times = M.shape[1]
n_points = G.shape[1]
iv = np.ones((n_points, n_times), dtype=np.float)
v = phi(iv)
L = 1e100
for it in range(100):
... | 58,614 |
def main():
"""
>>> array = range(0, 5)
>>> iterator = iter(array)
>>> for item in iterator:
... print(item, end='')
01234
>>> iterator = iter(array)
>>> next(iterator)
0
>>> next(iterator)
1
>>> next(iterator)
2
>>> next(iterator)
3
>>> next(iterator... | 58,615 |
def fourCornersSort(pts):
""" Sort corners: top-left, bot-left, bot-right, top-right """
# Difference and sum of x and y value
# Inspired by http://www.pyimagesearch.com
diff = np.diff(pts, axis=1)
summ = pts.sum(axis=1)
# Top-left point has smallest sum...
# np.argmin() returns INDEX o... | 58,616 |
def populate_user_output_from_schema_and_outputs(output_schema, output_names, outputs):
"""Follows the schema to generate an output that is expected by the user"""
def _replace_stub_with_tensor_value(user_output, outputs, output_idx):
# Recursively traverse across user_output and replace all _TensorStu... | 58,617 |
def get_current_mapset():
"""Return the current mapset
This is the fastest way to receive the current mapset.
The current mapset is set by init() and stored in a global variable.
This function provides access to this global variable.
"""
global current_mapset
return current_mapset | 58,618 |
def compress_image_to_file(path, terms, annotate, iterations=None, path_out=None):
"""
Compresses the image from `path` using singular value expansion.
The image is saved to an output file which name is chosen automatically,
unless `path_out` is specified.
Parameters
----------
path : path
... | 58,619 |
def merge_vocabs(vocabs, vocab_size=None):
"""
Merge individual vocabularies (assumed to be generated from disjoint
documents) into a larger vocabulary.
Args:
vocabs: `torchtext.vocab.Vocab` vocabularies to be merged
vocab_size: `int` the final vocabulary size. `None` for no limit.
... | 58,620 |
def nan_mode(input):
"""Mode value for tensor (ignoring NaNs)."""
return torch.mode(input[~torch.isnan(input)])[0] | 58,621 |
def event_values_block(
da: xarray.DataArray,
events: pandas.DataFrame,
offset: T.Union[T.Iterable[int], T.Dict[T.Hashable, int]],
load: bool = True,
):
"""
Gets the values from da where an event is active
"""
if load:
da = da.load()
event_id = numpy.atleast_1d(-1 * numpy.o... | 58,622 |
def run_select_genes(run_parameters):
""" Subset genes based on given gene set. Output is a spreadsheet with fewer rows
Args: run_parameters with keys:
"results_directory", "spreadsheet_file_name", "gene_list_file_name"
"""
results_directory = run_parameters['results_direc... | 58,623 |
def get_signing_pubkey(client, secret_url):
"""
Gets a PEM file from the vault, and returns one of RSAPublicKey, DSAPublicKey, or
EllipticCurvePublicKey depending on the contents of the secret.
"""
try:
raw_pubkey = client.get_secret(secret_url).value
return load_ssh_public_key(
... | 58,624 |
def generate_timestep_workflow(args):
"""
Generate a workload that models a multiple
"time-stepping" writers and multiple readers
:param args:
:return: time_schedule
"""
# -------- start creating the time_schedule ------------
creation_time = datetime.datetime.now().strftime("%Y-%m-%dT%... | 58,625 |
def validate_dandiset_yaml(filepath):
"""Validate dandiset.yaml"""
with open(filepath) as f:
meta = yaml_load(f, typ="safe")
return _check_required_fields(meta, _required_dandiset_metadata_fields) | 58,626 |
def test_thumbnail_no_cv2_no_pil(samples_path, monkeypatch):
"""Test generating a thumbnail from a reader without cv2 or Pillow installed.
This should fall back to scipy.ndimage.zoom.
"""
import cv2 as _cv2
# Monkeypatch cv2 and Pillow to not be installed
monkeypatch.setitem(sys.modules, "cv2"... | 58,627 |
def subscribe(client: mqtt_client):
"""
Subscribe client to topic.
Arguments:
client {mqtt_client} -- Client process id.
"""
def on_message(client, userdata, msg):
database_session = get_db_session()
try:
process_message(database_session, msg)
finally:
... | 58,628 |
async def test_get_ontology_type(http_service: Any, chrome_service: Any) -> None:
"""Should return 200 OK and a html-document with a list of ontologies for the given type."""
url = f"{http_service}/contract-test"
options = ChromeOptions()
options.headless = True
driver = webdriver.Chrome(
... | 58,629 |
def write_json_file(content: List[Dict[str, Any]] | Dict[str, Any], file: str, indent: int = 4, encoding: str = 'utf-8') -> None:
"""
Writes the content to targeted json file with indent.
:param content: Content that will be written to file
:param file: File path
:param indent: Indent value for jso... | 58,630 |
def get_grads(spike_stats, targets_frs, update_rule=0.0005):
"""Calculate gradients for updating the synaptic weights"""
mean_frs = spike_stats['firing_rate']['mean']
fr_diffs = {pop_name: (trg_fr - mean_frs.loc[pop_name]) for pop_name, trg_fr in targets_frs.items()}
mse = np.sum(np.power(list(fr_diffs.... | 58,631 |
def _im_to_blocks(im, width, roi=None, roi_method="all"):
"""
Converts image to list of square subimages called "blocks."
Parameters
----------
im: array_like
Image to convert to a list of blocks.
width: int
Width of square blocks in units of pixels.
roi: array_like, dtype b... | 58,632 |
def preprocess(docs: Dict[str,str], **kwargs):
"""
Takes as input a dictionary of the documents for clustering and transforms them into the compact data structures of corpus and Vocabulary in preperation for clustering.
This process turns each document from a string of words into a dictionary with (k, v) o... | 58,633 |
def videoTest():
""" Run the chip detector module by itself """
cap = cv2.VideoCapture(1)
cap.set(cv2.CAP_PROP_FRAME_WIDTH,9999)
cap.set(cv2.CAP_PROP_FRAME_HEIGHT,9999)
while(True):
# Get the next frame
flag, img = cap.read()
img_disp = copy.deepcopy(img)
... | 58,634 |
def print_comments_from_json_files(json_dir, comment_key):
"""print comments from all json files in a directory"""
#TODO generalize this. works with any string, not only comments
files = [os.path.join(json_dir, f) for f in os.listdir(json_dir) if f.endswith(".json")]
log.info(tools.get_colored_string("json files:... | 58,635 |
def activation(func_a):
"""Activation function wrapper
"""
return eval(func_a) | 58,636 |
def gravity(z, g0, r0):
"""Relates Earth gravity field magnitude with the geometric height.
Parameters
----------
z: float
Geometric height.
g0: float
Gravity value at sea level.
r0: float
Planet/Natural satellite radius.
Returns
-------
g: float
Gra... | 58,637 |
def tfunc(t, rdd):
"""
Transforming function. Converts our blank RDD to something usable
:param t: datetime
:param rdd: rdd
Current rdd we're mapping to
"""
return rdd.flatMap(lambda x: stream_twitter_data()) | 58,638 |
def quote_columns_data(data: str) -> str:
"""When projecting Queries using dot notation (f.e. inventory [ facts.osfamily ])
we need to quote the dot in such column name for the DataTables library or it will
interpret the dot a way to get into a nested results object.
See https://datatables.net/referenc... | 58,639 |
def daemon(path=".", address=None, port=None):
"""Run a daemon serving Git requests over TCP/IP.
:param path: Path to the directory to serve.
:param address: Optional address to listen on (defaults to ::)
:param port: Optional port to listen on (defaults to TCP_GIT_PORT)
"""
# TODO(user): Suppo... | 58,640 |
def svn_client_checkout2(*args):
"""svn_client_checkout2(char const * URL, char const * path, svn_opt_revision_t peg_revision, svn_opt_revision_t revision, svn_boolean_t recurse, svn_boolean_t ignore_externals, svn_client_ctx_t ctx, apr_pool_t pool) -> svn_error_t"""
return _client.svn_client_checkout2(*args) | 58,641 |
def sort_kv_pairs_by_value(d):
"""Turn a dict into a list of key-value pairs, sorted by value."""
return [
(k, v) for v, k in sorted([(v, k) for k, v in d.items()], reverse=True)
] | 58,642 |
def parsaCollettivi(file_collettivi):
""" Dato il csv genera lista di collettivi """
collettivi = []
with open(file_collettivi, 'r') as aulefile:
parsedCollettivi = csv.reader(aulefile, delimiter=';')
for row in parsedCollettivi:
flags = []
turni = []
nam... | 58,643 |
def rk4(derivs, y0, t, *args, **kwargs):
"""
Integrate 1D or ND system of ODEs using 4-th order Runge-Kutta.
This is a toy implementation which may be useful if you find
yourself stranded on a system w/o scipy. Otherwise use
:func:`scipy.integrate`.
Args:
derivs: the derivative of the sys... | 58,644 |
def hexEncode(value):
"""Some replaces."""
if isinstance(value, unicode):
value = value.encode('ascii', 'backslashreplace')
return value | 58,645 |
def get_logger(name=None, level=None, stream=DEFAULT_STREAM,
clobber_root_handler=True, logger_factory=None,
wrapper_class=None):
"""Configure and return a logger with structlog and stdlib."""
_configure_logger(
logger_factory=logger_factory,
wrapper_class=wrapper_c... | 58,646 |
def test_confirm_connections_blocked():
"""Confirm that socket connections are blocked during unit tests."""
with pytest.raises(ValueError) as cm_ex:
urllib.request.urlopen('http://example.com')
assert _BLOCKED_CONNECTION_MESSAGE == str(cm_ex.value) | 58,647 |
def main(**kwargs):
"""
Executes Apriori algorithm and print its result.
"""
# For tests.
_parse_args = kwargs.get('_parse_args', parse_args)
_load_transactions = kwargs.get('_load_transactions', load_transactions)
_apriori = kwargs.get('_apriori', apriori)
args = _parse_args(sys.argv[1... | 58,648 |
def log_likelihood(model,data) :
"""Return log10 (normalized) likelihood: P(3D astrometry | 3D phase space, Covariance)"""
functions = []
for s in data :
functions.append(imageLikelyhood(s))
images = getImages(model)
if(len(images)==len(functions)): # probably a very bad idea
re... | 58,649 |
def newcd(path):
"""DEPRICATE"""
cwd = os.getcwd()
os.chdir(path)
return cwd | 58,650 |
def yices_division(t1, t2):
"""Returns the term (t1 / t2) from the given terms, or NULL_TERM if there's an error.
division(t1, t2):
t1 and t2 must be arithmetic terms
NOTE: Until Yices 2.5.0, t2 was required to be a non-zero constant.
This is no longer the case: t2 can be any arithmetic term.
... | 58,651 |
def check_edge_count(context, count):
"""
Check the edge count in the graph object.
:param context: Context object share between all the setups.
:type context: :class:`behave.runner.Context`
:param count: Expected edge count.
:type count: :class:`int`
"""
assert_that(context.graph.edges... | 58,652 |
def is_string_formatted(s, return_parsed_list=False):
""" check if a string has formatted characters (with curly braces) """
l = list(string.Formatter().parse(s))
if len(l) == 1 and l[0][0] == s:
is_formatted = False
else:
is_formatted = True
if return_parsed_list:
return is... | 58,653 |
def test_list_unsigned_short_min_length_4_nistxml_sv_iv_list_unsigned_short_min_length_5_4(mode, save_output, output_format):
"""
Type list/unsignedShort is restricted by facet minLength with value
10.
"""
assert_bindings(
schema="nistData/list/unsignedShort/Schema+Instance/NISTSchema-SV-IV-... | 58,654 |
def extract_number(img):
"""Get the image number only"""
img=img.split('.fits')
nimg=int(img[0][-4:])
return nimg | 58,655 |
def sentiment_text(text):
"""Detects sentiment in the text."""
language_client = language.Client(api_version='v1beta2')
if isinstance(text, six.binary_type):
text = text.decode('utf-8')
# Instantiates a plain text document.
document = language_client.document_from_text(text)
# Detects... | 58,656 |
def cv_score_table(res_sprm_cv):
"""
Internal function reorganizing sklearn GridSearchCV results to pandas table.
The function adds the cv score table to the object as cv_score_table_
"""
n_settings = len(res_sprm_cv.cv_results_['params'])
etas = [res_sprm_cv.cv_results_['para... | 58,657 |
def calc_aridity(prec, pet, water_year):
"""Calculates the aridity as described in Knoben et al (2018)"""
prec = prepare_data(prec, water_year=water_year)
pet = prepare_data(pet, water_year=water_year)
prec_pet = pd.concat([prec[0],pet.iloc[:,0:2]],axis=1)
prec_pet.columns = ["prec", "pet", "water_... | 58,658 |
def load_info(path = None, eyes = False):
"""Load cascade classifier and DNN from paths in info.json file."""
if path:
assert os.path.exists(path), f"File {path} not found. "
json_file = path
else:
json_file = os.path.join(os.path.dirname(__file__), 'info.json')
# Load attributes from fil... | 58,659 |
def download_images(urls, num_workers=1, pbar=True):
""" Download multiples images
Arguments:
url (list of str): List of urls to download
Returns:
An iterator of PIL Images for the downloaded images
"""
with ThreadPool(num_workers) as pool:
images = pool.imap(download_image... | 58,660 |
def plotZ_Luminosity_Pdeg2(zz,lum,WW,name,ylab,pDir,flux_limit = 3e-17,line = "O2_3728", cmax = 1000):
"""
creates a figure with redshift, luminosity.
:param zz: column redshift
:param ew: column luminosity
:param name: name of the figure.
:param ylab : y axis label
:param pDir: where the figure will be saved.
... | 58,661 |
def group_reads_by_allele(allele_reads):
"""
Returns dictionary mapping each allele's nucleotide sequence to a list of
supporting AlleleRead objects.
"""
return groupby(allele_reads, lambda read: read.allele) | 58,662 |
def create_handler(
session: Optional[SessionProxy],
request: ResourceHandlerRequest,
callback_context: MutableMapping[str, Any], # pylint: disable=unused-argument
) -> ProgressEvent:
"""This function is triggered by the CloudFormation CREATE event
and will set the StepConcurrency level from the de... | 58,663 |
def get_buoy_metadata(db):
"""
Extracts the meta data from the buoy database.
Parameters
----------
db : str
Full path to the buoy data SQLite database.
Returns
-------
meta_info : list
List of dicts with keys based on the field names from the Stations
table. Re... | 58,664 |
def test_repoinfo_parse_valid():
"""Test RepoInfo parser's ability to parse valid repository paths."""
VALID_PATHS = [
"https://github.com/user/repo",
"HTTPS://GITHUB.COM/user/repo",
"https://www.github.com/user/repo",
"https://gitlab.com/user/repo",
"HTTPS://GITLAB.COM/u... | 58,665 |
def get_dist_args(dist):
"""Probe a scipy.stats distribution (or JMCtools distribution) for its
required arguments"""
has_args = False
try:
fargs = dist.args
has_args = True
except AttributeError:
has_args = False
if not has_args:
try:
func_args = g... | 58,666 |
def MobileNetV2(
input_shape,
alpha=0.35,
include_top=True,
pooling=None,
classes=1000,
classifier_activation='softmax',
last_block_filters=None,
**kwargs
):
"""Instantiates the MobileNetV2 architecture.
.. seealso::
* `MobileNetV2: Inverted Residuals and Linear Bottlenecks <https://arxiv.org/... | 58,667 |
def update_menu_item_linked_object(menu_item, linked_object):
"""Assign new linked object to a menu item. Clear other links."""
menu_item.category = None
menu_item.collection = None
menu_item.page = None
if isinstance(linked_object, Category):
menu_item.category = linked_object
elif isi... | 58,668 |
def _get_creation_date():
"""作成時刻を返す"""
return datetime.utcnow().strftime('%Y-%m-%d-T%H:%M:%SZ') | 58,669 |
def _param_with_axes_sow_reduce_fn(x, y):
"""Reduction function for sow() calls.
Args:
x: Existing value, or () if there was none.
y: New axis names sown.
Returns:
New axis names.
Raises:
TypeError: If the newly sown value is not an AxisMetadata.
ValueError: If the newly sown axis names d... | 58,670 |
def combine_similar_titles(extracted_strings):
"""Take a dictionary with titles and nested dicts with scores
and combine scores for titles which we decide are the same."""
# Iterate through each possible pair of title keys, including both
# permutations of each pair
for title_pair in permutation... | 58,671 |
def rkLeavesByK(hmat):
"""Sort the Rk leaves by descending compression ratio.
Args:
hmat: an instance of HMatrixStructure
Returns:
[(compression_ratio1, leaf1), ...]
"""
leaves = hmat.listRkLeaves()
ratio_leaves = [(x.k, x) for x in leaves]
ratio_leaves.sort(key=operator.itemge... | 58,672 |
def check_length(min_length: int,
max_length: int,
mode: str = 'and',
*args) -> bool:
"""
check items length is between min_length and max_length
:param min_length: minimum length
:param max_length: maximum length
:param mode: check mode, 'and': all... | 58,673 |
def save_sim_data_hdf5(data: SimData, hdf5_path: Path, compress: bool = True,
chunk_size_mb: int = 2, cache_size_mb: int = 20,
cache_modulus: int = 2341) -> None:
"""Saves the given MDArray as a HDF5 file.
The simulation environments are stored as fixed length byte... | 58,674 |
def _fix_estrs(estrs):
"""Add fitzpatrick colors, and remove emoji variation selectors.
1) The emoji ordering html page omits the skin color variants. Since
we want to display them, we have to add them. However, we don't add
them for sequences with multiple people, since we don't support
multiracial groups ... | 58,675 |
def dict_to_df(desired_type: Type[T], dict_obj: Dict, logger: Logger, orient: str = None, **kwargs) -> pd.DataFrame:
"""
Helper method to convert a dictionary into a dataframe. It supports both simple key-value dicts as well as true
table dicts. For this it uses pd.DataFrame constructor or pd.DataFrame.from... | 58,676 |
def update_schedule(schedule: models.ChargeSchedule, settings: Dict[str, Any]) -> None:
"""Update schedule."""
for day in DAYS_OF_WEEK:
if day in settings.keys():
day_settings = settings[day]
if day_settings: # pragma: no branch
start_time = day_settings["startT... | 58,677 |
def architecture_summary():
"""
Returns the text and image of architecture summary of the project.
"""
return html.Div(children=[
dcc.Markdown('''
# Project Architecture
This project uses MongoDB as the database. All data acquired are stored in raw form to the
... | 58,678 |
def chunk_str(msg, sep=(" ", ".", ",", "(")):
"""
chunk_str will take a string and a tuple of separators and recursively
split the string into Chunk objects that record which separator was
used to split it.
:param msg: The string that we want to break apart.
:type msg: str
:param sep... | 58,679 |
def excluded_path_misc_operation(sbox):
"""make sure other subcommands handle exclude"""
ign_a, ign_b, ign_c, wc_dir = set_up_depthy_working_copies(sbox,
infinity=True)
A_path = os.path.join(wc_dir, 'A')
B_path = os.path.join(A_path, 'B')
L_path = ... | 58,680 |
def l2_regularization(W, reg_strength):
"""
Computes L2 regularization loss on weights and its gradient
Arguments:
W, np array - weights
reg_strength - float value
Returns:
loss, single value - l2 regularization loss
gradient, np.array same shape as W - gradient of weight by l2... | 58,681 |
def build_shared_head(cfg):
"""Build shared head of detector."""
return build(cfg, SHARED_HEADS) | 58,682 |
def check_csrf(func):
"""Checks/removes a csrf_token from request.session's list of valid tokens."""
def _wrapper(request, *args, **kw):
valid_csrf_tokens = request.session.get('csrf_tokens')
request_csrf_token = request.REQUEST.get('csrf_token')
# Special easter-egg to get around the csrf token.
#... | 58,683 |
def get_connection_monitor(connection_monitor_name: Optional[str] = None,
network_watcher_name: Optional[str] = None,
resource_group_name: Optional[str] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetConnectionMonitorR... | 58,684 |
def ssh(host, user, passwd, log=LOG):
"""SSH to any host.
"""
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(host, username=user, password=passwd)
return ssh | 58,685 |
def _filter_deps(filter, deps):
"""Filters dep targets based on tags."""
if not filter:
return deps
kept_deps = []
for dep in deps:
info = None
if TulsiSourcesAspectInfo in dep:
info = dep[TulsiSourcesAspectInfo].filtering_info
# Only attempt to filter targe... | 58,686 |
def show_version(ctx, param, value):
"""print LNT version"""
import lnt
if not value or ctx.resilient_parsing:
return
if lnt.__version__:
print("LNT %s" % (lnt.__version__, ))
ctx.exit() | 58,687 |
def prepare_text_for_lda(text):
"""
:param text:
:return: list of filetered tokens
"""
tokens = tokenize(text)
tokens = [token for token in tokens if len(token) > 4]
tokens = [token for token in tokens if token not in stop_words_es]
tokens = [get_lemma(token) for token in tokens]
re... | 58,688 |
def back_test(strategy, seq_len, ticker, start_date, end_date, dim):
"""
A simple back test for a given date period
:param strategy: the chosen strategy. Note to have already formed the model, and fitted with training data.
:param seq_len: length of the days used for prediction
:param ticker: compan... | 58,689 |
def make_grammar(description, whitespace=r'\s*'):
"""Convert a description to a grammar. Each line is a rule for a
non-terminal symbol; it looks like this:
Symbol => A1 A2 ... | B1 B2 ... | C1 C2 ...
where the right-hand side is one or more alternatives, separated by
the '|' sign. Each altern... | 58,690 |
def repo_root() -> Path:
"""Repository root, 3 levels up from the resources root."""
return builtin_resources_root().parent.parent.parent | 58,691 |
def test_dcgm_embedded_metadata_exectime_get_all_fields_sane(handle):
"""
Sanity test for API that gets execution time of all fields together
"""
if not option_parser.options.developer_mode:
test_utils.skip_test("Skipping developer test.")
handle = pydcgm.DcgmHandle(handle)
system = pydc... | 58,692 |
def load_model_data(m, d, data_portal, scenario_directory, subproblem, stage):
""" """
data_portal.load(
filename=os.path.join(
scenario_directory, str(subproblem), str(stage), "inputs", "horizons.tab"
),
select=("balancing_type_horizon", "horizon", "boundary"),
index... | 58,693 |
def get_acl_token(accessor_id: Optional[str] = None,
description: Optional[str] = None,
local: Optional[bool] = None,
namespace: Optional[str] = None,
policies: Optional[Sequence[pulumi.InputType['GetAclTokenPolicyArgs']]] = None,
... | 58,694 |
def calc_code_churn(
repo: pygit2.Repository,
commit_a: pygit2.Commit,
commit_b: pygit2.Commit,
churn_config: tp.Optional[ChurnConfig] = None
) -> tp.Tuple[int, int, int]:
"""
Calculates churn between two commits.
Args:
repo: git repository
commit_a: base commit for diff cal... | 58,695 |
def test_preservation_derivatives(aip_contents):
"""Test that report template renders."""
with current_app.test_client() as test_client:
response = test_client.get("/reporter/preservation_derivatives/?amss_id=1")
assert response.status_code == 200 | 58,696 |
def utf8_to_vyxal(code: str) -> str:
"""Turn UTF-8 characters into bytes according to the codepage"""
return "".join(chr(codepage.index(char)) for char in code) | 58,697 |
def apply_chunk_id_maps(continuation_arr, chunk_id_maps):
""" Applies id maps to each set of continuations """
for (c_dict, id_map) in zip(continuation_arr.flat, chunk_id_maps.flat):
apply_id_map(c_dict, id_map)
return continuation_arr | 58,698 |
def find_system_symbol(img, instruction_addr, sdk_info=None, cpu_name=None):
"""Finds a system symbol."""
img_cpu_name = get_cpu_name(img['cpu_type'], img['cpu_subtype'])
cpu_name = img_cpu_name or cpu_name
return DSymSymbol.objects.lookup_symbol(
instruction_addr=instruction_addr,
image... | 58,699 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.