content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def close_up_to_column_sign(a, b, rtol=1e-05, atol=1e-08, equal_nan=False):
"""SVD can produce sign flips on a per-column basis."""
kwargs = dict(rtol=rtol, atol=atol, equal_nan=equal_nan)
if np.allclose(a, b, **kwargs):
return True
ret = True
for acol, bcol in zip(a.T, b.T):
ret &=... | 5,291,700 |
def postSync(content: str, *, url: str = None, retry: int = 5, find_fallback_on_unavailable: bool = True,
find_fallback_on_retry_runout: bool = False):
"""
Creates a new haste
:param content: Union[str, Iterable] - the content to post to hastebin. If this is a list, it will join with a newlin... | 5,291,701 |
def check_serialization_roundtrip(irs: Dict[str, ModuleIR]) -> None:
"""Check that we can serialize modules out and deserialize them to the same thing."""
serialized = {k: ir.serialize() for k, ir in irs.items()}
ctx = DeserMaps({}, {})
irs2 = deserialize_modules(serialized, ctx)
assert irs.keys() ... | 5,291,702 |
def sketch_2x1s(pixel_positions, mpl_axes=None):
"""
Draw a rough sketch of the layout of the CSPAD
Parameters
----------
pixel_positions : np.ndarray
The x,y,z coordinates of the pixels on the CSPAD
"""
if pixel_positions.shape not in [(4,8,185,388,3), (4,8,185,388,3), (4,8,185... | 5,291,703 |
def test_heartratecalc():
"""Test for the average heart rate calculator
This method applies the heart rate calculator to the data from the
above test and then also from a very short example data set of beats.
"""
from Processing import heartratecalc
from pytest import approx
beatcount, bea... | 5,291,704 |
def stack_fixture(stack_function_fixture) -> Tuple[str, str]:
"""
Fixture that creates a dummy stack with dummy resources.
:return: Tuple, where first element is stack name, and second element is stack id.
"""
return stack_function_fixture() | 5,291,705 |
def error(err):
"""Print error message and exit"""
print(err)
exit() | 5,291,706 |
def create_connection(db_file):
""" Create a database connection to the SQLite database specified by the db_file
db_file: database file
return: Connection cursor or None
"""
try:
c = sqlite3.connect(db_file)
conn = c.cursor()
return conn
except Error as e:
print(e)
return None | 5,291,707 |
def get_resource(x, fmt='text'):
"""Return contents of file or URL x
:param binary: Resource is binary. Return bytes instead of a string.
"""
is_binary = fmt != 'text'
# Try to retrieve from in-memory cache
if x in cache_dict:
return cache_dict[x]
if '://' in x:
# Web resou... | 5,291,708 |
def decode_logs(logs):
"""
Decode logs to events and enrich them with additional info.
"""
decoded = _decode_logs(logs)
for i, log in enumerate(logs):
setattr(decoded[i], "block_number", log["blockNumber"])
return decoded | 5,291,709 |
def check_lease():
"""
Goes through every transaction in pending transactions and removes all the assign/update
transactions that violate the lease duration
(This is mostly for multiple assign/updates that have yet to be included in the blockchain)
"""
pt_mutex.acquire()
current_update_leas... | 5,291,710 |
def assert_allclose(actual: numpy.float64, desired: numpy.ndarray, rtol: float):
"""
usage.statsmodels: 4
"""
... | 5,291,711 |
def make_decorator(func):
"""
Wraps a test decorator so as to properly replicate metadata
of the decorated function, including nose's additional stuff
(namely, setup and teardown).
"""
def decorate(newfunc):
if hasattr(func, 'compat_func_name'):
name = func.compat_func_name
... | 5,291,712 |
def calendar_from_alias(calendar_alias):
"""Get a Calendar object from its alias.
Parameters
----------
calendar_alias : str
Returns
-------
out : Calendar object
Notes
-----
This is mostly a mapping from the calendars of the CF conventions
to built-in calendars.
"""
... | 5,291,713 |
def edge_select_transform(data, edge):
"""
Data selection and transformation between tasks
Data transfer between tasks is handled by edges that define rich data
mapping and selection criteria to match input of the next tasks to the
output of the previous task.
Supported transformation options:... | 5,291,714 |
def add_allocation_config(config, cache):
"""
config["components"] maps Allocation name that can be found in csv to allocation_id
:param config:
:param cache:
:return:
"""
allocation_root = cache.get_xml_tree("allocation")
allocation_config = {}
for allocation in allocation_root.find... | 5,291,715 |
def plot_orthotopes(u, abx, axvars, fol, ax):
"""Plot a polytope for each orthotope in `u`.
@param axvars: `list` that defines which variable
spans each dimension of the plot.
"""
try:
import polytope as poly
except ImportError:
raise ImportError(
'`orthotopes` f... | 5,291,716 |
def model_training_earlystopping(
data_loader_train,
data_loader_valid,
ml_model_name,
ml_model,
loss_function,
nb_epochs,
is_cuda,
smiles_dictionary,
max_length_smiles,
device_to_use,
learning_rate,
path_to_parameters,
patience=10,
):
"""
Train the machine le... | 5,291,717 |
def set_setup_py_version(version, content):
"""
Replace version in setup.py file using regex,
g<1> contains the string left of version
g<3> contains the string right of version
:param version: string
:param content: content of setup.py as string
:return: content of setup.py file with 'versio... | 5,291,718 |
def tile(x: Tensor, n_tile: int):
"""Tiles Tensor x n_tile times in dimension 0.
:param x: [N x n] input to tile
:param n_tile: number of times x will be repeated in dim 0
:returns: [N * n_tile x n]
"""
assert x.dim() == 2
assert n_tile >= 1
return x.repeat(1, n_tile).view(-1, x.size(1)... | 5,291,719 |
def prepare_grant_uri(uri, client_id, response_type, redirect_uri=None,
scope=None, state=None, **kwargs):
"""Prepare the authorization grant request URI.
The client constructs the request URI by adding the following
parameters to the query component of the authorization endpoint URI
... | 5,291,720 |
def process_generate_message_notifications(payload):
"""
Generates notifications for a message sent to a group chat
"""
logger.info(f"Sending out notifications for message_id = {payload.message_id}")
with session_scope() as session:
message, group_chat = session.execute(
select(... | 5,291,721 |
def comprobar_Cliente_LLegando():
"""Compobar si ya llego un cliente."""
global num_Clientes
if t.tiempo_llegada == t.reloj:
c.cola += 1
num_Clientes += 1
c.listUsuario.append(Usuario(t.tll, t.tiempo_llegada, t.reloj))
st.wllegaUsuario(t.tll, t.reloj, c.cola)
anim.an_... | 5,291,722 |
def create_index():
"""Create a new relationships index with a timestamp suffix."""
# Get the mapping
mapping_path = current_search.mappings['relationships-v1.0.0']
# Create a timestamp-suffixed index
ts = str(time.time())
index_name = f'relationships-v1.0.0-{ts}'
es_client.indices.create(
... | 5,291,723 |
def find_downstroke_indexes(v, t, peak_indexes, trough_indexes, clipped=None, filter=10., dvdt=None):
"""Find indexes of minimum voltage (troughs) between spikes.
Parameters
----------
v : numpy array of voltage time series in mV
t : numpy array of times in seconds
peak_indexes : numpy array of... | 5,291,724 |
def train_model(base_model, training_generator, validation_generator, output_dir,
loss=None, batch_size=64, num_epochs=100, patience=20,
learning_rate=1e-4):
"""
Train a model with the given data.
Parameters
----------
model
X_train
y_train
output_dir
... | 5,291,725 |
def get_trace_component_for_trigger_instance(trigger_instance_db):
"""
Returns the trace_component compatible dict representation of a triggerinstance.
:param trigger_instance_db: The TriggerInstance to translate
:type trigger_instance_db: TriggerInstanceDB
:rtype: ``dict``
"""
trace_compo... | 5,291,726 |
def smart_merge(guesses):
"""First tries to merge well-known similar properties, and then merges
the rest with a merge_all call.
Should be the function to call in most cases, unless one wants to have more
control.
Warning: this function is destructive, ie: it will merge the list in-place.
"""
... | 5,291,727 |
def arrange_df(df, df_type, relevant_col_idx=None, items_to_delete=None, assembly_df=None, bom_trim=False):
"""
:param bom_trim:
:param df:
pandas.DataFrame object that contains the raw format that is read from the file.
:param df_type:
File type of
:param relevant_col_idx:
:param items_... | 5,291,728 |
def postvar(sum2, n, a, b):
"""
Parameters
----------
sum2
n
a
b
Returns
-------
out
"""
return (0.5 * sum2 + b) / (n / 2.0 + a - 1.0) | 5,291,729 |
def _handle_retry(exc, no_of_retries):
"""Handle errors which qualify for retry"""
retry = False
no_of_retries += 1
sleep_time = _get_sleep_time_seconds(no_of_retries)
msg = f"Got error: {exc} Retrying in {sleep_time} secs, attempt {no_of_retries}"
if isinstance(exc, httpx.HTTPStatusError):
... | 5,291,730 |
def get_sqrt_square_average(read_data_list):
"""
sqrt(x1^2 + x2^2 + ... + xn^2)
"""
tx_len = len(read_data_list[0])
rx_len = len(read_data_list[0][0])
sqrt_square_average = [([0.0] * rx_len) for i in range(tx_len)]
for i in range(len(read_data_list)):
for j in range(len(read_data_lis... | 5,291,731 |
def get_ols_url_prefix(prefix: str) -> Optional[str]:
"""Get the URL format for an OLS entry.
:param prefix: The prefix to lookup.
:returns: The OLS format string, if available.
.. warning:: This doesn't have a normal form, so it only works for OBO Foundry at the moment.
>>> import bioregistry
... | 5,291,732 |
def write_msg(msg):
"""
Add a new message to database
"""
if 200 in msg:
msg = json.loads(str(msg[200]))
for i in msg:
"""
insert each unique app into db
"""
msg = {"event_type": i['id'],
"event_description": i['name'],
... | 5,291,733 |
def create_trial_name(exp_name, exp_id=0, seed=0):
"""
Create a semi-unique experiment name that has a timestamp
:param exp_name:
:param exp_id:
:return:
"""
now = datetime.datetime.now(dateutil.tz.tzlocal())
timestamp = now.strftime('%Y_%m_%d_%H_%M_%S')
return "%s_%s_id%03d--s%d" % ... | 5,291,734 |
def move_to_rough_home(esp, rig_ax):
"""Move calibration rig to desired rough home position (i.e. "move to TSH +X UP or TSH -Y UP, etc.").
Parameters
----------
esp : ESP object
driver for Newport's ESP 301 motion controller.
rig_ax: str
designation for rough home position (+x, -... | 5,291,735 |
def new_case_study_from_file():
"""
Check that the user is authorized to submit a new case study
Open a reproducible session
Send the file to the service
Close the reproducible session
:return:
"""
# Check Interactive Session is Open. If not, open it
isess = deserialize_isession_and... | 5,291,736 |
def _extract_trend_params():
"""
Extract required parameters for tools task like forecast algorithm and
database path.
:return: parameter dict.
"""
return {'forecast_alg': config.get('forecast', 'forecast_alg'),
'database_dir': os.path.realpath(config.get('database', 'database_dir'))... | 5,291,737 |
def _make_decimal(n: str, b: int, pos: int) -> int:
"""Suppose we have a number n=xyz (represented as string) in base b.
The algorithm of converting it to a decimal representation is as follows.
b⁰ * decimal_value(z) + b¹ * decimal_value(y) + b² * decimal_value(x),
where decimal_value(z) is the d... | 5,291,738 |
def test_read_participants_data():
"""Test reading information from a BIDS sidecar.json file."""
bids_root = _TempDir()
raw = mne.io.read_raw_fif(raw_fname, verbose=False)
# if subject info was set, we don't roundtrip birthday
# due to possible anonymization in mne-bids
subject_info = {
... | 5,291,739 |
def seed_all(seed=1):
"""
fixes seeds everywhere
:param seed: random seed
"""
random.seed(seed)
os.environ['PYTHONHASHSEED'] = str(seed)
np.random.seed(seed)
torch.manual_seed(seed)
torch.cuda.manual_seed(seed)
torch.backends.cudnn.deterministic = True
n_gpu = torch.cuda.devi... | 5,291,740 |
def argmax(l,f=None):
"""http://stackoverflow.com/questions/5098580/implementing-argmax-in-python"""
if f:
l = [f(i) for i in l]
return max(enumerate(l), key=lambda x:x[1])[0] | 5,291,741 |
def IsEnabled(test, possible_browser):
"""Returns True iff |test| is enabled given the |possible_browser|.
Use to respect the @Enabled / @Disabled decorators.
Args:
test: A function or class that may contain _disabled_strings and/or
_enabled_strings attributes.
possible_browser: A PossibleBrow... | 5,291,742 |
def underline(s):
"""Print string S, double underlined in ASCII."""
print(s)
print("=" * len(s)) | 5,291,743 |
def flatten_list(a_list):
"""Given a list of sequences, return a flattened list
>>> flatten_list([['a', 'b', 'c'], ['e', 'f', 'j']])
['a', 'b', 'c', 'e', 'f', 'j']
>>> flatten_list([['aaaa', 'bbbb'], 'b', 'cc'])
['aaaa', 'bbbb', 'b', 'cc']
"""
# isinstance check to ensure we're not iteratin... | 5,291,744 |
def connected_double_edge_swap(G, nswap=1):
"""Attempt nswap double-edge swaps in the graph G.
A double-edge swap removes two randomly chosen edges u-v and x-y
and creates the new edges u-x and v-y::
u--v u v
becomes | |
x--y x y
If either the... | 5,291,745 |
def _verify_hash(filename: Path, access_calculated_hash: str) -> None:
"""
Verifies the hash of the file matches the calculated hash from the access log
:param filename: file to verify the hash of
:param access_calculated_hash: hash read from the access log for this filename
"""
calculated... | 5,291,746 |
def up(user_version: int) -> str:
"""Return minimal up script SQL for testing."""
return f"""
BEGIN TRANSACTION;
PRAGMA user_version = {user_version};
CREATE TABLE Test (key PRIMARY KEY);
COMMIT;
""" | 5,291,747 |
def _generateVariants(seq, possibleAA = None):
"""Given peptide seq, return all POSSIBLE single AA mutants OR
2 random single AA mutants per position in seq
Return a list of variants and a dictionary of variants:(posi,newAA)"""
variantsInfo = {seq:(np.nan,'ORIGINAL')}
"""If we know possibleAA then r... | 5,291,748 |
def indexRepo(repo=None, redisGraphConn=None, rediSearchConn=None):
"""
do indexing on repository object with redisConn connection
"""
if(repo != None):
client = None
_repo = repo
if(redisGraphConn != None and rediSearchConn!=None):
graphName = _repo.RepositoryID + "-... | 5,291,749 |
def load_tasks():
"""
Load timer tasks form settings.py , return command str .
"""
cmd_path = getcwd()
path.insert(0, cmd_path)
# load user config
user_settings_obj = load_module_from_path('settings.py', join(cmd_path, 'settings.py'))
# override default config
settings =... | 5,291,750 |
def mask_to_seeds(mask: np.ndarray,
method: str = 'sitk',
output: str = 'mask',
binary: bool = True
) -> Union[np.ndarray, list]:
"""Find centroid of all objects and return, either as list of points or labeled mask
If binary, all seeds are ... | 5,291,751 |
def assign_weights(pt_state_dict, pretrained_prefix=None):
"""Load pytorch state_dict and assign to tensorflow model."""
import tensorflow as tf
vars = tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES)
vars.pop(0)
pt_state_dict = {k: v for k, v in pt_state_dict.items() if 'num_batches_tracked' not in... | 5,291,752 |
def create(*, db_session, **kwargs) -> Storage:
"""Create a new storage."""
storage = Storage(**kwargs)
db_session.add(storage)
db_session.commit()
return storage | 5,291,753 |
def magic_foo5(self, args):
""" A docstring.
"""
return parse_argstring(magic_foo5, args) | 5,291,754 |
def test_nfc_wps_er_config_token(dev, apdev):
"""WPS NFC configuration token from ER to Enrollee"""
ssid = "wps-nfc-er-config-token"
start_ap_er(dev[0], apdev[0], ssid)
logger.info("WPS provisioning step using configuration token from ER")
conf = dev[0].request("WPS_ER_NFC_CONFIG_TOKEN NDEF " + apde... | 5,291,755 |
def make_coef_surface(p1: Point, p2: Point, p3: Point) -> (float, float, float, float, Tuple[float, float, float]):
"""
Вычисление коэффициентов плоскости A, B, C, проходящую через три точки p1, p2 и p3, и вектора нормали N к этой
плоскости.
:param p1: Первая точка
:param p2: Вторая точка
:param... | 5,291,756 |
def populate_array(array, data, shape, strides, itemsize, meminfo,
parent=None):
"""
Helper function for populating array structures.
This avoids forgetting to set fields.
"""
context = array._context
builder = array._builder
datamodel = array._datamodel
required_field... | 5,291,757 |
def bubbles_from_kmeans(data, upper_lim=True, n_jobs=1, n_clusters=3):
"""
@ Giri at al. (2018a)
It is a method to identify regions of interest in noisy images.
The method finds the optimal threshold using the 1D PDF of the image. It gives similar results compared
to the Otsu's method.
Parameters
----------
d... | 5,291,758 |
def run_main(_):
"""Main in convert_file_to_c_source.py."""
parser = argparse.ArgumentParser(
description=("Command line tool to run TensorFlow Lite Converter."))
parser.add_argument(
"--input_tflite_file",
type=str,
help="Full filepath of the input TensorFlow Lite file.",
required... | 5,291,759 |
def clean_and_reformat_mapping(in_fp, out_fp, body_site_column_name,
exp_acronym):
"""Simplify the mapping file for use in figures
in_fp : input file-like object
out_fp : output file-like object
body_site_column_name : specify the column name for body
exp_acronym : sh... | 5,291,760 |
def one_model(input_val, y_val, fn, fn_kwargs={}, k_folds=1, random_state=15, verbose=False):
"""
1-fold task, mean and std of results are calculated over 1 folds
Params:
input_val: (np.array) 2-D array holding instances (features) of validation set.
y_val: (np.array) 1-D array hold... | 5,291,761 |
def hash256_result(func):
"""Secure the return string of the annotated function with SHA256 algorithm. If the annotated
function doesn't return string or return None, raise ValueError."""
@wraps(func)
def _wrapped_func(*args, **kwargs):
val = func(*args, **kwargs)
if not val:
... | 5,291,762 |
def test_timeout_explicit_status(run_line, load_api_fixtures, patch_sleep, go_ep1_id):
"""
As above, submit a task which sits queued and times out.
Confirms rm exits STATUS after given timeout, where
STATUS is set via the --timeout-exit-code opt
"""
load_api_fixtures("transfer_activate_success.y... | 5,291,763 |
def resize_walls(walls: np.array, factor: int):
"""
Increase the environment size by rescaling.
Parameters
----------
walls : np.array
0/1 array indicating obstacle locations.
factor : int
Factor by which to rescale the environment
Returns
-------
walls : np.array
... | 5,291,764 |
def _dp_graph31_ ( dp , npoints = 250 , masses = False ) :
"""Make a graph of Dalitz plot: s3 vs s1
>>> d = Dalitz (5 , 0.1 , 0.2 , 0.3 )
>>> graph = d.graph31 ()
>>> graph.draw ('al')
"""
points = _dp_points_ ( dp , npoints )
pnts = [ ( p[0], dp.s3( p[0] , p[1] ) ) for p in po... | 5,291,765 |
def meters_to_pixels(meters_x, meters_y, level_of_detail):
"""converts XY point from Spherical Mercator EPSG:900913 to ZXY pixel coordinates
"""
res = ground_resolution(0, level_of_detail) # ground resolution at equator
x = int((meters_x + origin_shift) / res)
y = int((meters_y + origin_shift) / re... | 5,291,766 |
def get_matches(lf, candidate_set, match_values=[1,-1]):
"""
A simple helper function to see how many matches (non-zero by default) an LF gets.
Returns the matched set, which can then be directly put into the Viewer.
"""
matches = []
for c in candidate_set:
label = lf(c)
if label... | 5,291,767 |
def get_credential_options(user, *, challenge, rp_name, rp_id, icon_url):
"""
Returns a dictionary of options for credential creation
on the client side.
"""
options = pywebauthn.WebAuthnMakeCredentialOptions(
challenge, rp_name, rp_id, str(user.id), user.username, user.name, icon_url
)
... | 5,291,768 |
def get_store_inventory(username):
"""
Fetches the inventory of the Bricklink store with the given username.
"""
# 1: fetch the whole store front (because BL sucks)
front_url = 'https://store.bricklink.com/{username}#/shop?o={opts}'.format(username=username,
... | 5,291,769 |
def audioSample(fileOne, fileTwo, name_prefix, time_manager, controller=None, arguments={}, analysis={}):
"""
Confirm fileTwo is sampled from fileOne
:param fileOne:
:param fileTwo:
:param name_prefix:
:param time_manager:
:param arguments:
:return:
@type time_manager: VidTimeManager... | 5,291,770 |
def get_meraki_switchports_status(org_name, device_name):
"""Query Meraki for Port Status for a Switch."""
dashboard = meraki.DashboardAPI(suppress_logging=True)
return dashboard.switch.getDeviceSwitchPortsStatuses(_name_to_serial(org_name, device_name)) | 5,291,771 |
def metaclass(inherit=object):
"""Create a custom metaclass to make the attribute use the `__set__` method.
Normally `class.variable = value` would simply change the class value. By using a metaclass you can force
`class.variable = value` to call the variable's `__set__` method.
Args:
inherit ... | 5,291,772 |
def get_noun_term_freq(df, option='N'):
"""
Returns noun morphemes and freqeuncy
- input : dataframe, {option : compound noun decomposition flag, default : N}
- output : list of tuples(morpheme, frequency)
"""
_noun_type = ['NNG', 'NNP']
_terms = []
for index, row in df.iterrows():
... | 5,291,773 |
def swish(x):
"""Swish activation function.
Arguments:
x: Input tensor.
Returns:
The swish activation applied to `x`.
"""
return nn.swish(x) | 5,291,774 |
def get_connection_string():
""" Reads from the local FS to get the RabbitMQ location to
connect to.
Returns:
A string representing the location of RabbitMQ.
"""
rabbitmq_ip = file_io.read(RABBITMQ_LOCATION_FILE)
return 'amqp://guest:guest@' + rabbitmq_ip + ':' + \
str(RABBITMQ_PORT) + '/... | 5,291,775 |
def run_it(conf):
"""
This function is entry point of this Program.
The Program read information on source cloud:
- about flavors and instances and store it into 'configs/nova.json'
- about compute nodes and store it into 'configs/nodes_info.json'
"""
flavors, vms, nodes = get_flavors_vms_... | 5,291,776 |
def getRecipients(test_data):
"""
Returns, as a string, the email addresses of the student's parents for
the given test
"""
recipients = []
if test_data["MotherEmail"] != "":
recipients.append(test_data["MotherEmail"])
if test_data["FatherEmail"] != "":
recipie... | 5,291,777 |
def get_kitti_frame(sample):
"""
Get KITTI depth image and point cloud
Args:
sample: KITTI sample object
Returns: scene depth and point cloud
"""
H, W, _ = sample['image'].shape
# Filter out lidar points outside field of view
scene_lidar = sample['lidar']
frustum = build_v... | 5,291,778 |
def initialise_indiv_spectra_s6(scouseobject, SAA, njobs):
"""
Initialise the spectra for fitting
"""
indiv_spectra = {}
# Parallel
if njobs > 1:
args = [scouseobject, SAA]
inputs = [[k] + args for k in range(len(SAA.indices_flat))]
# Send to parallel_map
indiv_sp... | 5,291,779 |
def haddock_ref(haddock_host, haddock_root, pkg, module, func_name):
"""
Return a reference link to Haddocks for pkg/module#func_name.
"""
if module == None and func_name == None:
return pkg_root_ref(haddock_host, haddock_root, pkg)
else:
func_name = convert_special_chars_to_ascii(f... | 5,291,780 |
def create_outdir(filename):
"""Create the output directory for a given filename
"""
out_dir = os.path.dirname(filename)
if not os.path.exists(out_dir):
os.makedirs(out_dir) | 5,291,781 |
def format_print_text(text: str, *, color_fg: str = None, color_bg: str = None) -> str:
"""Format given text using ANSI formatting escape sequences.
Could be useful for print command.
:param text:
:param color_fg: text (foreground) color
:param color_bg: text (background) color
"""
from .... | 5,291,782 |
def get_emb_sz_list(dims: list):
"""
For all elements in the given list, find a size for the respective embedding through trial and error
Each element denotes the amount of unique values for one categorical feature
Parameters
----------
dims : list
a list containing a number of integers.... | 5,291,783 |
def pkg_to_sqlite_db(pudl_settings,
pkg_bundle_name,
pkg_name=None):
"""
Turn a data package into a sqlite database.
Args:
pudl_settings (dict) : a dictionary filled with settings that mostly
describe paths to various resources and outputs.
... | 5,291,784 |
def evaluate_topic_models(data, varying_parameters, constant_parameters=None, n_max_processes=None, return_models=False,
metric=None, **metric_kwargs):
"""
Compute several Topic Models in parallel using the "gensim" package. Calculate the models using a list of varying
parameters `... | 5,291,785 |
def convert_weblogo_color(color: Color, color_format: str) -> Union[tuple, str]:
"""Convert weblogo Color to Bokeh color object
Note: Weblogo colors are RGB but fractional [0, 1],
whereas Bokeh and draw_alignment are [0, 255]
:sa: https://github.com/WebLogo/weblogo/blob/master/weblogo/color.py
:p... | 5,291,786 |
def list_signing_certificates(UserName=None, Marker=None, MaxItems=None):
"""
Returns information about the signing certificates associated with the specified IAM user. If none exists, the operation returns an empty list.
Although each user is limited to a small number of signing certificates, you can still... | 5,291,787 |
def BenfordDQ(impath):
"""
Main driver for ADQ3 algorithm.
Args:
impath: Input image path, required to be JPEG with extension .jpg
Returns:
OutputMap: Output of ADQ3 algorithm (2D array).
"""
if impath[-4:] == '.jpg':
try:
im = jio.read(impath)
excep... | 5,291,788 |
def yuanshan_weir_ecological_base_stream_flow():
"""
Real Name: YuanShan Weir Ecological Base Stream Flow
Original Eqn: 198720
Units: m3
Limits: (None, None)
Type: constant
2.3cms, equals 198720 m^3 per day
"""
return 198720 | 5,291,789 |
def generate_repr_factor_batch(dataset: BaseDataset,
repr_fn: Callable[[Tensor], Tensor],
batch_size: int,
num_points: int
) -> Tuple[np.ndarray, np.ndarray]:
"""Generates batch samples of rep... | 5,291,790 |
def get_config(path_to_config: Union[PosixPath, WindowsPath]) -> tuple:
"""Function to get config file and retrive data that is needed
for the script to run
Args:
path_to_config (Union[PosixPath, WindowsPath]): relative path to the
config file
Raises... | 5,291,791 |
def parse_sdl_attrs(prefix: str, all_names: List[str]) -> Tuple[str, str]:
"""Return the name/value pairs, and the final dictionary string for the
library attributes with `prefix`.
Append matching names to the `all_names` list.
"""
names = []
lookup = []
for name, value in sorted(find_sdl_a... | 5,291,792 |
def get_doc_id_filter(doc_id_set):
"""
This function returns a filter which removes any documents not in
doc_id_set.
This filter does not alter record_dict, but instead returns either true or
false indicating whether to document should be kept or not.
Parameters
----------
doc_id_set :... | 5,291,793 |
def get_config_connection(inifile: str, section: str='PostgreSQL') -> connection:
"""ini設定ファイルを読み込みそのパラメーターを元にDBに接続し、コネクションオブジェクトを返す。
iniファイルの形式
[postgres] #セクション名は引数で指定可能
host=ホスト名
port=ポート番号
user=ユーザー名
password=パスワード
dbname=DB名
ユーザー名パスワードは必ず設定する必要がある。
DBはPo... | 5,291,794 |
def ldrpc_source_address(line):
"""Calculate the absolute source address of a PC-relative load.
'line' is a line returned by disassembly_lines().
If it doesn't look like the right kind of instruction, returns None.
"""
# Example: ldr r2, [pc, #900] ; (0x000034b4)
if line.op == 'ldr' and l... | 5,291,795 |
def load_cifar10_class_subsets(classes, train=True, device="cpu", dtype=torch.float, minmax=(0, 1.0)):
"""
Load and return a subset of the CIFAR10 dataset, including only the
specified classes.
- classes: a list of class indices (as returned by label_class_list()
- minmax: transform the range of pi... | 5,291,796 |
def ROCData_from_results(results, clf_index, target):
"""
Compute ROC Curve(s) from evaluation results.
:param Orange.evaluation.Results results:
Evaluation results.
:param int clf_index:
Learner index in the `results`.
:param int target:
Target class index (i.e. positive cl... | 5,291,797 |
def readFileOrGz(file, defStr = None):
""" read a file and return its contents. If the file ends in .gz, use gunzip on it """
if file.endswith(".gz"):
return readPipe("gunzip < '" + file + "'", defStr)
else:
return readFile(file, defStr) | 5,291,798 |
def check_input(linkerpad, rechterpad, seltype):
"""parse input
"""
if linkerpad == "":
return 'Geen linkerbestand opgegeven'
else:
if not pathlib.Path(linkerpad).exists():
return 'Bestand {} kon niet gevonden/geopend worden'.format(
linkerpad)
if rechterp... | 5,291,799 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.