content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def feedforward(
inputs,
input_dim,
hidden_dim,
output_dim,
num_hidden_layers,
hidden_activation=None,
output_activation=None):
"""
Creates a dense feedforward network with num_hidden_layers layers where each layer
has hidden_dim number of units except... | bbf6559d27e68ff4642d8842af50ff0d292bd1c8 | 14,700 |
import doctest
def _test():
"""
>>> solve("axyb", "abyxb")
axb
"""
global chr
def chr(x): return x
doctest.testmod() | 1ba052fbf066cee92ad2088b9562443c727292df | 14,701 |
from typing import Optional
def _basic_rebuild_chain(target: database.Target) -> RebuildChain:
"""
Get a rebuild chain based purely on 'rebuild info' from Jam.
"""
chain: RebuildChain = [(target, None)]
current: Optional[database.Target] = target
assert current is not None
while True:
... | 966864ac71eafb982c2dff0f74e383e207127b32 | 14,702 |
def ravel_group_params(parameters_group):
"""Take a dict(group -> {k->p}) and return a dict('group:k'-> p)
"""
return {f'{group_name}:{k}': p
for group_name, group_params in parameters_group.items()
for k, p in group_params.items()} | 4a768e89cd70b39bea4f658600690dcb3992a710 | 14,703 |
def decode_orders(game, power_name, dest_unit_value, factors):
""" Decode orders from computed factors
:param game: An instance of `diplomacy.Game`
:param power_name: The name of the power we are playing
:param dest_unit_value: A dict with unit as key, and unit value as value
:param ... | ac1e9b59d792158bb0b903709344b8535b330e73 | 14,704 |
from typing import Type
def _convert_to_type(se, allow_any=False, allow_implicit_tuple=False):
""" Converts an S-Expression representing a type, like (Vec Float) or (Tuple Float (Vec Float)),
into a Type object, e.g. Type.Tensor(1,Type.Float) or Type.Tuple(Type.Float, Type.Tensor(1,Type.Float)).
... | f615244363fa7fcdc67c4d68580860b3145bd94f | 14,705 |
def index():
"""Returns a 200, that's about it!!!!!!!"""
return 'Wow!!!!!' | f6d8a765556d2d6a1c343bb0ab1a9d4a6c5fd6ba | 14,706 |
import os
def file_sort_key(file):
"""Calculate the sort key for ``file``.
:param file: The file to calculate the sort key for
:type file: :class:`~digi_edit.models.file.File`
:return: The sort key
:rtype: ``tuple``
"""
path = file.attributes['filename'].split(os.path.sep)
path_len = ... | 1997e48c2355816d88e930e9fb3369096a227b63 | 14,707 |
def merge_tables(pulse_data, trial_data, merge_keys=TRIAL_GROUPER):
"""Add trial-wise information to the pulse-wise table."""
pulse_data = pulse_data.merge(trial_data, on=merge_keys)
add_kernel_data(pulse_data)
return pulse_data | 1c5eafa44b50d05c8d23af7d290d0b40c2643ef9 | 14,708 |
def eos_deriv(beta, g):
""" compute d E_os(beta)/d beta from polynomial expression"""
x = np.tan(beta/2.0)
y = g[4] + x * g[3] + x*x * g[2] + x*x*x*g[1] + x*x*x*x*g[0]
y = y / ((1.0 + x*x)*(1.0 + x*x)*(1.0 + x*x))
return y | 2e1055bc48364abfe5bb07a1d9eafd32fefb7031 | 14,709 |
def optimizeAngle(angle):
"""
Because any rotation can be expressed within 360 degrees
of any given number, and since negative angles sometimes
are one character longer than corresponding positive angle,
we shorten the number to one in the range to [-90, 270[.
"""
# First, we put the new ang... | 8abcaba2542b59715ced1c0acec94194f6e357d7 | 14,710 |
def process_one_name(stove_name):
"""
Translates a single PokerStove-style name of holecards into an
expanded list of pokertools-style names.
For example:
"AKs" -> ["Ac Kc", "Ad Kd", "Ah Kh", "As Ks"]
"66" -> ["6c 6d", "6c 6h", "6c 6s", "6d 6h", "6d 6s", "6c 6d"]
"""
if len(stov... | 5a824df9ae1a723c350b635a6b3096b795d4c58e | 14,711 |
def job_dispatch(results, job_id, batches):
"""
Process the job batches one at a time
When there is more than one batch to process, a chord is used to delay the
execution of remaining batches.
"""
batch = batches.pop(0)
info('dispatching job_id: {0}, batch: {1}, results: {2}'.format(job_i... | d6107c11bf350aedc1103e0e182f2808041abb5b | 14,712 |
import logging
import sqlite3
def get_temperature():
"""
Serves temperature data from the database, in a simple html format
"""
logger = logging.getLogger("logger")
#sqlite handler
sql_handler = SQLiteHandler()
logger.addHandler(sql_handler)
logger.setLevel(logging.INFO)
con ... | 3f2400c823ff2bc11a2b1910ce6cc39d90614178 | 14,713 |
def command_result_processor_category_empty(command_category):
"""
Command result message processor if a command category is empty.
Parameters
----------
command_category : ``CommandLineCommandCategory``
Respective command category.
Returns
-------
message : `str`
"... | 10da547a922bfd538a4241976385210969bf752a | 14,714 |
def _parse_path(**kw):
"""
Parse leaflet `Path` options.
http://leafletjs.com/reference-1.2.0.html#path
"""
color = kw.pop('color', '#3388ff')
return {
'stroke': kw.pop('stroke', True),
'color': color,
'weight': kw.pop('weight', 3),
'opacity': kw.pop('opacity', 1... | 02d3810ad69a1a0b8f16d61e661e246aea5c09cc | 14,715 |
def random_rotation(x, rg, row_axis=1, col_axis=2, channel_axis=0,
fill_mode='nearest', cval=0., interpolation_order=1):
"""Performs a random rotation of a Numpy image tensor.
# Arguments
x: Input tensor. Must be 3D.
rg: Rotation range, in degrees.
row_axis: Index of... | 57f263f1bee9fb323205543cba9c14c9a86ba431 | 14,716 |
from app.config import config_by_name
from app.models import User
from app.controllers import user_api, iris_api
def create_app(config_name: str) -> Flask:
"""Create the Flask application
Args:
config_name (str): Config name mapping to Config Class
Returns:
[Flask]: Flask Applica... | 355b4f0ee97441eb8309c485f234b07418c24378 | 14,717 |
import subprocess
def load_module():
"""This function loads the module and returns any errors that occur in the process."""
proc = subprocess.Popen(["pactl", "load-module", "module-suspend-on-idle"], stderr=subprocess.PIPE)
stderr = proc.communicate()[1].decode("UTF-8")
return stderr | f95eefb380d0be6a65d4a3a044a33f13a96e190c | 14,718 |
from typing import Optional
import time
from datetime import datetime
def time_struct_2_datetime(
time_struct: Optional[time.struct_time],
) -> Optional[datetime]:
"""Convert struct_time to datetime.
Args:
time_struct (Optional[time.struct_time]): A time struct to convert.
Returns:
O... | 705b09428d218e8a47961e247b62b9dfd631a41f | 14,719 |
import argparse
def _parse_input():
"""
A function for handling terminal commands.
:return: The path to the experiment configuration file.
"""
parser = argparse.ArgumentParser(description='Performs CNN analysis according to the input config.')
parser.add_argument('-i', '--experiments_file', d... | 5486a1fee5eeb6b69f857d45f9e3e1a7f924ae5b | 14,720 |
def independent_interdomain_conditional(Kmn, Kmm, Knn, f, *, full_cov=False, full_output_cov=False,
q_sqrt=None, white=False):
"""
The inducing outputs live in the g-space (R^L).
Interdomain conditional calculation.
:param Kmn: M x L x N x P
:param Kmm: L x M... | e886fb4cbfc549cb02e728bba20ecad92dbfb135 | 14,721 |
def we_are_buying(account_from, account_to):
"""
Are we buying? (not buying == selling)
"""
buy = False
sell = False
for value in TRADING_ACCOUNTS:
if (value.lower() in account_from):
buy = True
sell = False
elif (value.lower() in account_to):
... | a5748ad756f472e0e2c39b5dc5239265fbf3d1f4 | 14,722 |
import os
def register(param, file_src, file_dest, file_mat, file_out, im_mask=None):
"""
Register two images by estimating slice-wise Tx and Ty transformations, which are regularized along Z. This function
uses ANTs' isct_antsSliceRegularizedRegistration.
:param param:
:param file_src:
:param... | c1c90b411a70d6c6ea5975e499b98b919675956f | 14,723 |
import os
import csv
def parse_geoname_table_file(fpath, delimiter='\t'):
"""
Parse the table given in a file
:param fpath: string - path to the file
:param delimiter: string - delimiter between columns in the file
:returns: list of dict
"""
if not os.path.isfile(fpath):
fstr = "p... | 9a907da6c1ec331418b1be340bb798855888c633 | 14,724 |
import time
def wait_for_compute_jobs(nevermined, account, jobs):
"""Monitor and wait for compute jobs to finish.
Args:
nevermined (:py:class:`nevermined_sdk_py.Nevermined`): A nevermined instance.
account (:py:class:`contracts_lib_py.account.Account`): Account that published
the ... | 98370b8d596f304630199578a360a639507ae3c3 | 14,725 |
def f1_score_loss(predicted_probs: tf.Tensor, labels: tf.Tensor) -> tf.Tensor:
"""
Computes a loss function based on F1 scores (harmonic mean of precision an recall).
Args:
predicted_probs: A [B, L] tensor of predicted probabilities
labels: A [B, 1] tensor of expected labels
Returns:
... | df4f35516230a7c57b0c6b3e8b7e958feae900f8 | 14,726 |
def get_alarm_historys_logic(starttime, endtime, page, limit):
"""
GET 请求历史告警记录信息
:return: resp, status
resp: json格式的响应数据
status: 响应码
"""
data = {'alarm_total': 0, "alarms": []}
status = ''
message = ''
resp = {"status": status, "data": data, "message": messag... | bc273cf8e6d022374f92b7c3da86552a9dbbed2a | 14,727 |
def showCities():
"""
Shows all cities in the database
"""
if 'access_token' not in login_session:
return redirect(url_for('showLogin'))
cities = session.query(City).order_by(City.id)
return render_template('cities.html', cities=cities) | 558b2a8639f810cf105777ce89acc368e4441bbd | 14,728 |
def symb_to_num(symbolic):
"""
Convert symbolic permission notation to numeric notation.
"""
if len(symbolic) == 9:
group = (symbolic[:-6], symbolic[3:-3], symbolic[6:])
try:
numeric = notation[group[0]] + notation[group[1]] + notation[group[2]]
except:
n... | c2c11697658322ad972e87ec1eb55d08eaa91e0e | 14,729 |
def round_vector(v, fraction):
""" ベクトルの各要素をそれぞれ round する
Args:
v (list[float, float, float]):
Returns:
list[float, float, float]:
"""
v = [round(x, fraction) for x in v]
return v | 47c10d23d9f2caa319f4f3fa97c85cf226752bab | 14,730 |
def accept(model):
"""Return True if more than 20% of the validation data is being
correctly classified. Used to avoid including nets which haven't
learnt anything in the ensemble.
"""
accuracy = 0
for data, target in validation_data[:(500/100)]:
if use_gpu:
data, target = ... | c2921fb6dc0226b88fe7dd8219264cb5908feb6b | 14,731 |
import struct
def parse_tcp_packet(tcp_packet):
"""read tcp data.http only build on tcp, so we do not need to support other protocols."""
tcp_base_header_len = 20
# tcp header
tcp_header = tcp_packet[0:tcp_base_header_len]
source_port, dest_port, seq, ack_seq, t_f, flags = struct.unpack(b'!HHIIBB6... | fa1b1050609cce8ca23ca5bac6276a681f560659 | 14,732 |
def find_balanced(text, start=0, start_sep='(', end_sep=')'):
""" Finds balanced ``start_sep`` with ``end_sep`` assuming
that ``start`` is pointing to ``start_sep`` in ``text``.
"""
if start >= len(text) or start_sep != text[start]:
return start
balanced = 1
pos = start + 1
while... | 15c17a216405028b480efa9d12846905a1eb56d4 | 14,733 |
from datetime import datetime
import requests
import io
import re
def get_jhu_counts():
"""
Get latest case count .csv from JHU.
Return aggregated counts by country as Series.
"""
now = datetime.datetime.now().strftime("%m-%d-%Y")
url = f"https://raw.githubusercontent.com/CSSEGISandData/COVI... | 6a3fb69cce6f8976178afd3ff81ab2381b89abc5 | 14,734 |
def sectionsToMarkdown(root):
"""
Converts a list of Demisto JSON tables to markdown string of tables
:type root: ``dict`` or ``list``
:param root: The JSON table - List of dictionaries with the same keys or a single dictionary (required)
:return: A string representation of the markdow... | 3f916544cc5a9dc7e4d094d82834382d377948f1 | 14,735 |
import numpy
def VonMisesFisher_sample(phi0, theta0, sigma0, size=None):
""" Draw a sample from the Von-Mises Fisher distribution.
Parameters
----------
phi0, theta0 : float or array-like
Spherical-polar coordinates of the center of the distribution.
sigma0 : float
Width of the d... | 440029bb9c3455dce22ff2d078068f9b7c404a7b | 14,736 |
from typing import Optional
from typing import Dict
from typing import Any
from unittest.mock import patch
async def async_init_flow(
hass: HomeAssistantType,
handler: str = DOMAIN,
context: Optional[Dict] = None,
data: Any = None,
) -> Any:
"""Set up mock Roku integration flow."""
with patch(... | 2147f18b6b26e57e84d21aff321e8464710de653 | 14,737 |
import logging
def _get_filtered_topics(topics, include, exclude):
"""
Filter the topics.
:param topics: Topics to filter
:param include: Topics to include if != None
:param exclude: Topics to exclude if != and include == None
:return: filtered topics
"""
logging.debug("Filtering topic... | ec353ecc57015d10641562dd66dd30ba046a0a97 | 14,738 |
import inspect
def create_cell(cell_classname, cell_params):
""" Creates RNN cell.
Args:
cell_classname: The name of the cell class,
e.g. "LSTMCell", "GRUCell" and so on.
cell_params: A dictionary of parameters to pass
to the cell constructor.
Returns:
A `tf.c... | 64eed878f950499b599f992dbb50f2f05e8fbff9 | 14,739 |
def get_myia_tag(rtag):
"""Return the myia tag for a constructor.
This will fail if you haven't properly called fill_reverse_tag_map().
"""
return rev_tag_map[rtag] | 95e7afb73ce15bbfe7a75c4708f5c81a9c9e22df | 14,740 |
def get_priority(gene, phenotype):
"""
Get matched priority from the phenotype table.
Parameters
----------
gene : str
Gene name.
phenotype : str
Phenotype name.
Returns
-------
str
EHR priority.
Examples
--------
>>> import pypgx
>>> pypgx... | 5520d8df0b79834227f059e98d66109134e84439 | 14,741 |
import tqdm
from datetime import datetime
def _generator3(path):
"""
Args:
path: path of the dataframe
Returns:
yield outputs of X and Y pairs
"""
args = init_args()
catalog = load_catalog(path)
def preprocess(x, y=None):
zero = False
if not np.any(x):
... | 3d26d9cab1777b3b72d85584c6ff95b39c725e47 | 14,742 |
def _extract_gsi(name):
"""
Extract a normalised groundstation if available.
:param name:
:rtype: str
>>> _extract_gsi('LANDSAT-7.76773.S3A1C2D2R2')
>>> _extract_gsi('AQUA.60724.S1A1C2D2R2')
>>> _extract_gsi('TERRA.73100.S1A2C2D4R4')
>>> _extract_gsi('LANDSAT-8.3108')
>>> _extract_g... | b101b79df21b9d0bbb633dbca14ff6a5b207b91d | 14,743 |
def array_at_verts_basic2d(a):
"""
Computes values at cell vertices on 2d array using neighbor averaging.
Parameters
----------
a : ndarray
Array values at cell centers, could be a slice in any orientation.
Returns
-------
averts : ndarray
Array values at cell vertices,... | e1f9ab5abbed6d4837daec01b8cd865d15cddde6 | 14,744 |
def get_subquestion_answer(response, questions, subquestion):
"""
Return the answer to a subquestion from ``response``.
"""
question_id = subquestion[0]
answers = response[question_id]
dim = len(subquestion) - 1
for answer in answers:
matched = True
if subquestion[1] != answe... | e0b89db06570e35d1fb9eba7b762ed96bf7c16b8 | 14,745 |
def uniform_centroids(dist_map, n_centroids):
"""
Uniformly space `n_centroids` seeds in a naive way
:param dist_map: sparse distance map
:param n_centroids: number of seeds to place
:return: (n_centroids, ) integer arrays with the indices of the seeds
"""
def get_dist(idx_vertex):
... | 437eaf8b70b56379d5529ea30026176fda9049a9 | 14,746 |
import collections
import itertools
def collate_custom(batch,key=None):
""" Custom collate function for the Dataset class
* It doesn't convert numpy arrays to stacked-tensors, but rather combines them in a list
* This is useful for processing annotations of different sizes
"""
# this ca... | b692252cb27aed68cb5af6cd5644913216a8dde7 | 14,747 |
def get_horizon(latitude, longitude, dem, ellipsoid=Ellipsoid("WGS84"), distance=0.5, precision=1):
""" Compute local get_horizon obstruction from Digital Elevation Model
This function is mainly based on a previous Matlab function
(see https://fr.mathworks.com/matlabcentral/fileexchange/59421-dem-based-top... | 342860c7320e009f4e32c8d610baeccef595460f | 14,748 |
def get_articles(language, no_words, max_no_articles, search, **kwargs):
""" Retrieve articles from Wikipedia """
wikipedia.set_rate_limiting(True) # be polite
wikipedia.set_lang(language)
if search is not None:
titles = wikipedia.search(search, results = max_no_articles)
else:
titl... | d6f2216a0800f6d9627d47ae1acda9e327583841 | 14,749 |
def gen_urdf_material(color_rgba):
"""
:param color_rgba: Four element sequence (0 to 1) encoding an rgba colour tuple, ``seq(float)``
:returns: urdf element sequence for an anonymous material definition containing just a color element, ``str``
"""
return '<material name=""><color rgba="{0} {1} {2} ... | d0fe1a706c932ad1a6f14aa3a9d9471de70650b9 | 14,750 |
import logging
def plot(self, class_=None, show_plot=True, plot_3D=True, plot_probs=True,
plot_dominant_classes=True, plot_poly=False, plot_normals=False,
plot_subclasses=False, plot_legend=True, fig=None, ax=None,
title='Softmax Classification',
**kwargs):
"""Display the class... | 6b0c760b35ddd8df30b817e702fbee209c5bc2d3 | 14,751 |
def roll_timeseries(arr, timezones):
"""
Roll timeseries from UTC to local time. Automatically compute time-shift
from UTC offset (timezone) and time-series length.
Parameters
----------
arr : ndarray
Input timeseries array of form (time, sites)
timezones : ndarray | list
Ve... | 4715425ea048a1ccb9c5fe2a1dc9e2ea1ecea085 | 14,752 |
def is_linear(a, eps=1e-3):
"""Check if array of numbers is approximately linear."""
x = np.diff(a[1:-1]).std() / np.diff(a[1:-1]).mean()
return x < eps | 0efa5c923012527d4973d24d67871a41ee2e3e91 | 14,753 |
def faces_sphere(src, show_path):
"""
Compute vertices and faces of Sphere input for plotting.
Parameters
----------
- src (source object)
- show_path (bool or int)
Returns
-------
vert, faces (returns all faces when show_path=int)
"""
# pylint: disable=protected-access
... | eb454e55a932aae2f6b0f15587d1aa0be6da80f7 | 14,754 |
import itertools
def pronto_signals_to_iguana_signals(carrier_frequency, signals):
"""Convert the pronto format into iguana format, where the pulses and spaces
are represented in number of microseconds.
"""
return [carrier_cycles_to_microseconds(carrier_frequency, signal) | command
for signal,... | b8ddaf9f573abfe207d2ca2009904a3d93e360a4 | 14,755 |
import collections
import itertools
import pandas
def stack_xarray_repdim(da, **dims):
"""Like xarrays stack, but with partial support for repeated dimensions
The xarray.DataArray.stack method fails when any dimension occurs
multiple times, as repeated dimensions are not currently very well
supported... | 5f0617ccd054c6d11573b00f659308780db4d0d7 | 14,756 |
import math
def compute_pnorm(model: nn.Module) -> float:
"""
Computes the norm of the parameters of a model.
:param model: A PyTorch model.
:return: The norm of the parameters of the model.
"""
return math.sqrt(sum([p.norm().item() ** 2 for p in model.parameters()])) | 610c640902f411221f90c5c7b48d3b3246a60124 | 14,757 |
def atomic_brute_cast(tree: Element) -> Element:
"""
Cast every node's text into an atomic string to prevent further processing on it.
Since we generate the final HTML with Jinja templates, we do not want other inline or tree processors
to keep modifying the data, so this function is used to mark the c... | 57d13b5e97b7f94593f925f745bdf833b15e03a1 | 14,758 |
def rsa_keys(p: int = None, q: int = None, e: int = 3) -> RSA_Keys:
"""
Generate a new set of RSA keys.
If p and q are not provided (<= 1),
then they will be generated.
:param p: A big prime.
:param q: A big prime.
:param e: The default public key.
:return: The RSA private and public ke... | b09fea8b6c23e4709c0f49faf2cb9b20463a2db9 | 14,759 |
import math
import contextlib
import os
def chunk_file(file_path, chunks, work_dir):
"""Splits a large file by line into number of chunks and writes them into work_dir"""
with open(file_path) as fin:
num_lines = sum(1 for line in fin)
chunk_size = math.ceil(num_lines / chunks)
output_file_pat... | 290ce02a4c6767374ced10fbf28d2c1ed1d5b69a | 14,760 |
def _get_closest_station_by_zcta_ranked(zcta):
""" Selects the nth ranked station from a list of ranked stations
Parameters
----------
zcta : string
ZIP Code Tabulation Area (ZCTA)
Returns
-------
station : string
Station that was found
warnings : list
List of w... | b9cbd7ccc4a22c3069e11bc0542700b8ee087a1c | 14,761 |
def label_matrix(y_true, y_pred, classes,
normalize=False,
title=None,
cmap=plt.cm.Blues):
"""
This function prints and plots the confusion matrix.
Normalization can be applied by setting `normalize=True`.
"""
if not title:
... | 0a1dc4665de4c2b876a0a40d5aa1fcfb1a9113d9 | 14,762 |
import warnings
def lowpass(data,in_t=None,cutoff=None,order=4,dt=None,axis=-1,causal=False):
"""
data: vector of data
in_t: sample times
cutoff: cutoff period in the same units as in_t
returns vector same as data, but with high frequencies removed
"""
# Step 1: Determine dt from dat... | f182fdb912be827d0d8e4fd788cc2cadca453b5a | 14,763 |
def gather_along_dim_with_dim_single(x, target_dim, source_dim, indices):
"""
This function indexes out a target dimension of a tensor in a structured way,
by allowing a different value to be selected for each member of a flat index
tensor (@indices) corresponding to a source dimension. This can be int... | 06fbba5478ddb21cda9a555c41c94c809244537c | 14,764 |
import os
import sys
def resolve_parallelism(parallel):
"""Decide what level of parallelism to use.
Parameters
----------
parallel : integer or None
The user's specification
Returns
-------
A positive integer giving the parallelization level.
"""
if parallel is None:
... | 0de01d63039162c3fd0afc4889dc9c733a8489b8 | 14,765 |
def get_queue(launcher=None):
"""Get the name of the queue used in an allocation.
:param launcher: Name of the WLM to use to collect allocation info. If no launcher
is provided ``detect_launcher`` is used to select a launcher.
:type launcher: str | None
:returns: Name of the queue
... | 56fd4e59877363fd6e889bae52a9b5abf77230f6 | 14,766 |
def get_openmc_geometry(openmoc_geometry):
"""Return an OpenMC geometry corresponding to an OpenMOC geometry.
Parameters
----------
openmoc_geometry : openmoc.Geometry
OpenMOC geometry
Returns
-------
openmc_geometry : openmc.Geometry
Equivalent OpenMC geometry
"""
... | af1eb3cbbcdb4122b28b544bc252f754758ababf | 14,767 |
def distinct(xs):
"""Get the list of distinct values with preserving order."""
# don't use collections.OrderedDict because we do support Python 2.6
seen = set()
return [x for x in xs if x not in seen and not seen.add(x)] | e5dafd942c8aa0314b7e9aa2ec09795796cac34a | 14,768 |
def get_price_to_free_cash_flow_ratio(equity, year=None, market_cap=None):
"""
This ratio can be found by dividing the current price of the stock by its free cash flow per share,
Easy way is to get it from the ratios object extracted from investing.
"""
try:
price_to_free_cash_flow = None
... | 80fd0441030d1310ceff89497196840cc2be870f | 14,769 |
import copy
def _parse_train_configs(train_config):
"""
check if user's train configs are valid.
Args:
train_config(dict): user's train config.
Return:
configs(dict): final configs will be used.
"""
configs = copy.deepcopy(_train_config_default)
configs.update(train_config... | 339539eac9a0463f4fd11d471cfa3f4971010969 | 14,770 |
def as_region(region):
"""
Convert string to :class:`~GenomicRegion`.
This function attempts to convert any string passed to it
to a :class:`~GenomicRegion`. Strings are expected to be
of the form <chromosome>[:<start>-<end>[:[strand]], e.g.
chr1:1-1000, 2:2mb-5mb:-, chrX:1.5kb-3mb, ...
Nu... | 863b1f982e9b411a023ab876661123b5565fae91 | 14,771 |
import re
def parse_user_next_stable(user):
"""
Parse the specified user-defined string containing the next stable version
numbers and returns the discretized matches in a dictionary.
"""
try:
data = re.match(user_version_matcher, user).groupdict()
if len(data) < 3:
rai... | 3d5de92fdb119a85bc6b5e87a8399cc07e6c9ee8 | 14,772 |
import tqdm
def interp_ADCP_2D(
sadcp,
mask,
depth,
lon,
lat,
time,
time_win=360.0,
rmax=15.0,
vmax=2.0,
range_min=4.0,
):
"""
This is essentially a loop over the interp_ADCP function with some additional NaN handling.
Assume data is of the form D[i, j] where each ... | ec092d203ef1cfee176bdf9ae05021fd876d444a | 14,773 |
def extract_p(path, dict_obj, default):
"""
try to extract dict value in key path, if key error provide default
:param path: the nested dict key path, separated by '.'
(therefore no dots in key names allowed)
:param dict_obj: the dictinary object from which to extract
:param default: a default r... | 1a563212e229e67751584885c5db5ac19157c37f | 14,774 |
def default_lscolors(env):
"""Gets a default instanse of LsColors"""
inherited_lscolors = os_environ.get("LS_COLORS", None)
if inherited_lscolors is None:
lsc = LsColors.fromdircolors()
else:
lsc = LsColors.fromstring(inherited_lscolors)
# have to place this in the env, so it is appl... | 0ad54d1220308a51194a464a2591be6edcc8d0ff | 14,775 |
import logging
def get_indices_by_sent(start, end, offsets, tokens):
"""
Get sentence index for textbounds
"""
# iterate over sentences
sent_start = None
sent_end = None
token_start = None
token_end = None
for i, sent in enumerate(offsets):
for j, (char_start, char_end) ... | 7ce90b69c63b18ee1c025970f5a645f5f4095d3b | 14,776 |
def get_server_object_by_id(nova, server_id):
"""
Returns a server with a given id
:param nova: the Nova client
:param server_id: the server's id
:return: an SNAPS-OO VmInst object or None if not found
"""
server = __get_latest_server_os_object_by_id(nova, server_id)
return __map_os_serv... | 384a5481c41937dfb7fcfdfdcc14bf0123db38a7 | 14,777 |
import os
def get_tasks(container_name):
"""Get the list of tasks in a container."""
file_name = tasks_path(container_name)
try:
tasks = [x.rstrip() for x in open(file_name).readlines()]
except IOError:
if os.path.exists(file_name):
raise
tasks = [] # container do... | 9b75eaf5dfea43dea2e8dbad302e5a0d0b975ebd | 14,778 |
import argparse
def get_args() -> argparse.Namespace:
"""Get script command line arguments."""
parser = argparse.ArgumentParser(description=__doc__.split("\n")[0])
parser.add_argument(
"-i",
"--input-files",
required=True,
nargs="+",
type=helpers.check_file_arg,
... | e9a015bfc9e9c73c9bc039206d355624174bd4e4 | 14,779 |
import os
def _get_archive(software, version):
"""
Gets the downloaded source archive for a software version.
:param software: software to get the downloaded source archive for
:type software: str
:param version: software release
:type version: str
"""
download_dir = get_download_loc... | 07e1269ae5adfe24b645dffb50b6a3ba66ed30a0 | 14,780 |
def make_odm(study_oid, environment, site_oid, subject_oid, mapping,
retrieved_datetime, transfer_user, transfer_identifier, freeze=True):
"""Receives a mapping like:
[
dict(folder_oid="SCRN", form_oid="DM", field_oid="SEX", value="M", cdash_domain="DM", cdash_element="SEX"),
... | b35728d1eef7ad2bb361e34826df574415737aa4 | 14,781 |
from xml.dom.minidom import parseString
import attr
def parse_string(xml):
""" Returns a slash-formatted string from the given XML representation.
The return value is a TokenString (see mbsp.py).
"""
string = ""
dom = parseString(xml)
# Traverse all the <sentence> elements in the XML.
... | e3ccf32bcc148b2c6b9b44259d881f336720fde5 | 14,782 |
def join_ad_domain_by_taking_over_existing_computer_using_session(
ad_session: ADSession, computer_name=None, computer_password=None, old_computer_password=None,
computer_key_file_path=DEFAULT_KRB5_KEYTAB_FILE_LOCATION) -> ManagedADComputer:
""" A fairly simple 'join a domain' function using pre-cre... | a9fea1126fd775c85cf9a354044315eef03a4ffb | 14,783 |
def peak_sound_pressure(pressure, axis=-1):
"""
Peak sound pressure :math:`p_{peak}` is the greatest absolute sound pressure during a certain time interval.
:param pressure: Instantaneous sound pressure :math:`p`.
:param axis: Axis.
.. math:: p_{peak} = \\mathrm{max}(|p|)
"""
return np.ab... | e3beb4d67dc414fa7aabdc7a9c4a06a5ddb371ab | 14,784 |
def field_filter_query(field, values):
"""Need to define work-around for full-text fields."""
values = ensure_list(values)
if not len(values):
return {'match_all': {}}
if field in ['_id', 'id']:
return {'ids': {'values': values}}
if len(values) == 1:
if field in ['names', 'ad... | 54d3b394e8dc38b2a0ead3b9d5a81da9f5f6915a | 14,785 |
import logging
def compute_investigation_stats(inv, exact=True, conf=0.95, correct=True):
"""
Compute all statistics for all protected features of an investigation
Parameters
----------
inv :
the investigation
exact :
whether exact tests should be used
conf :
ove... | 08bf8ab5c4e985c33fdb0bd0d9dfc1dc949f4d83 | 14,786 |
def group_bars(note_list):
"""
Returns a list of bars, where each bar is a list of notes. The
start and end times of each note are rescaled to units of bars, and
expressed relative to the beginning of the current bar.
Parameters
----------
note_list : list of tuples
List of not... | 3b12a7c7e2395caa3648abf152915ece4b325599 | 14,787 |
def get_vmexpire_id_from_ref(vmexpire_ref):
"""Parse a container reference and return the container ID
The container ID is the right-most element of the URL
:param container_ref: HTTP reference of container
:return: a string containing the ID of the container
"""
vmexpire_id = vmexpire_ref.rspl... | e90c34c8489d91fb582a4bf15f874bcb2feaea82 | 14,788 |
def create_A_and_B_state_ligand(line, A_B_state='vdwq_q'):
"""Create A and B state topology for a ligand.
Parameters
----------
line : str
'Atom line': with atomtype, mass, charge,...
A_B_state : str
Interactions in the A state and in the B state.
vdwq_vdwq: ligand fully inte... | 3ac16da60de68013b20ea3f1a6ce3173cd4871a1 | 14,789 |
def clean_params(estimator, n_jobs=None):
"""clean unwanted hyperparameter settings
If n_jobs is not None, set it into the estimator, if applicable
Return
------
Cleaned estimator object
"""
ALLOWED_CALLBACKS = (
"EarlyStopping",
"TerminateOnNaN",
"ReduceLROnPlateau... | da639b03ea7dec534130105571c1623128e99143 | 14,790 |
def getValidOauth2TxtCredentials(force_refresh=False, api=None):
"""Gets OAuth2 credentials which are guaranteed to be fresh and valid."""
try:
credentials = auth.get_admin_credentials(api)
except gam.auth.oauth.InvalidCredentialsFileError:
doRequestOAuth() # Make a new request which should... | ff29fe312fe6ca875e53c56482033ca5ccceb71c | 14,791 |
import itertools
def get_combinations_sar(products, aoi):
"""Get a dataframe with all possible combinations of products and calculate
their coverage of the AOI and the temporal distance between the products.
Parameters
----------
products : dataframe
Search results with product identifier... | 045fcf59e9dae17a17d77cb945d2fe63af01e7ae | 14,792 |
import re
def sample(s, n):
"""Show a sample of string s centered at position n"""
start = max(n - 8, 0)
finish = min(n + 24, len(s))
return re.escape(s[start:finish]) | 565f69224269ed7f5faa538d40ce277714144577 | 14,793 |
def getNeededLibraries(binary_filepath):
"""
Get all libraries given binary depends on.
"""
if False:
return getNeededLibrariesLDD(binary_filepath)
else:
return getNeededLibrariesOBJDUMP(binary_filepath) | 40fcb08fac7877f97cb9fa9f6f198e58c64fe492 | 14,794 |
from typing import List
def load_transformer(input_paths:List[str], input_type:str=None) -> Transformer:
"""
Creates a transformer for the appropriate file type and loads the data into
it from file.
"""
if input_type is None:
input_types = [get_type(i) for i in input_paths]
for t i... | 55eab62cdf5293ad03441fc91663383adcf12da7 | 14,795 |
from ocs_ci.ocs.platform_nodes import AWSNodes
def delete_and_create_osd_node_aws_upi(osd_node_name):
"""
Unschedule, drain and delete osd node, and creating a new osd node.
At the end of the function there should be the same number of osd nodes as
it was in the beginning, and also ceph health should ... | c376b8b499a9897723962e5af30984eb4d9f06fa | 14,796 |
import math
def encode_integer_compact(value: int) -> bytes:
"""Encode an integer with signed VLQ encoding.
:param int value: The value to encode.
:return: The encoded integer.
:rtype: bytes
"""
if value == 0:
return b"\0"
if value < 0:
sign_bit = 0x40
value = -v... | daf9ed4a794754a3cd402e8cc4c3e614857941fe | 14,797 |
def kin_phos_query(kin_accession):
"""
Query to pull related phosphosites using kinase accession
:param kin_accession: string kinase accession
:return: Flask_Table Phosphosite_results object
"""
session = create_sqlsession()
q = session.query(Kinase).filter_by(kin_accession= kin_accession)
... | 94f5f7d987dface90ff5d061525d2277173ed271 | 14,798 |
def max_surplus(redemptions, costs, traders):
"""
Calculates the maximum possible surplus
"""
surplus = 0
transactions = 0.5 * traders
for redemption, cost in zip(redemptions, costs):
if redemption >= cost:
surplus += ((redemption - cost) * transactions)
return surplus | 6dd452de1b8726c475c9b95d8c24a2f57fe71516 | 14,799 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.