content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def process_datasets(db_conn, box_dir):
"""Process datasets separately, since they contain one-to-many relationships (1 dataset -> N runs and/or M analyses)."""
folder = box_dir / 'datasets'
raw_files = folder.glob('EGAD*')
parsed_files = ( extract_dataset_info(f) for f in raw_files )
for (result, run_links... | 38,500 |
def steps_d_m(
n,
d=11,
m=5,
stopping=None):
"""
Generate steps for `step_sort()` (Shell sort).
These are of the form: x(k) = m * x(k - 1) // d
with initial value equal `n`.
Must be that `d > m`.
If `d=11, m=4`, this is yielding near-optimal empirical performan... | 38,501 |
def run_dataset(data):
""" Match features between image pairs. """
images = data.images()
start = timer()
pairs_matches, preport = matching.match_images(data, images, images)
matching.save_matches(data, images, pairs_matches)
end = timer()
write_report(data, preport, list(pairs_matches.ke... | 38,502 |
def nearest(x, xp, fp=None):
"""
Return the *fp* value corresponding to the *xp* that is nearest to *x*.
If *fp* is missing, return the index of the nearest value.
"""
if len(xp) == 1:
if np.isscalar(x):
return fp[0] if fp is not None else 0
else:
return np.a... | 38,503 |
def generate_warning_message(content: str):
"""
Receives the WARNING message content and colorizes it
"""
return (
colorama.Style.RESET_ALL
+ colorama.Fore.YELLOW
+ f"WARNING: {content}"
+ colorama.Style.RESET_ALL
) | 38,504 |
def extract_Heff_params(params, delta):
"""
Processes the VUMPS params into those specific to the
effective Hamiltonian eigensolver.
"""
keys = ["Heff_tol", "Heff_ncv", "Heff_neigs"]
Heff_params = {k: params[k] for k in keys}
if params["adaptive_Heff_tol"]:
Heff_params["Heff_tol"] ... | 38,505 |
def illumination_correction(beam_size: sc.Variable, sample_size: sc.Variable,
theta: sc.Variable) -> sc.Variable:
"""
Compute the factor by which the intensity should be multiplied to account for the
scattering geometry, where the beam is Gaussian in shape.
:param beam_size:... | 38,506 |
def get_subscription_query_list_xml(xml_file_path):
"""
Extract the embedded windows event XML QueryList elements out of a an XML subscription setting file
"""
with open(xml_file_path, 'rb') as f_xml:
x_subscription = lxml.etree.parse(f_xml)
# XPath selection requires namespace to used!
x_subscript... | 38,507 |
async def create_state_store() -> StateStore:
"""Create a ready-to-use StateStore instance."""
deck_data = DeckDataProvider()
# TODO(mc, 2020-11-18): check short trash FF
deck_definition = await deck_data.get_deck_definition()
deck_fixed_labware = await deck_data.get_deck_fixed_labware(deck_definit... | 38,508 |
def get_stream(name: Optional[str] = None,
tags: Optional[Mapping[str, str]] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetStreamResult:
"""
Use this data source to get information about a Kinesis Stream for use in other
resources.
For more details, s... | 38,509 |
def get_vlan_config_commands(vlan, vid):
"""Build command list required for VLAN configuration
"""
reverse_value_map = {
"admin_state": {
"down": "shutdown",
"up": "no shutdown"
}
}
if vlan.get('admin_state'):
# do we need to apply the value map?
... | 38,510 |
def kdf():
"""
Returns a dataframe with a few values for generic testing
"""
return ks.DataFrame(
{
"x": [36.12, 47.32, 56.78, None],
"y": [28.21, 87.12, 90.01, None],
"names": ["geography", "place", "location", "geospatial"],
}
) | 38,511 |
def _process_endnotes_in_file(filename: str, root: Path, note_range: range, step: int) -> None:
"""
Helper function for reordering endnotes.
This has to be outside of the class to be able to be called by `executor`.
"""
with open(root / filename, "r+", encoding="utf-8") as file:
xhtml = file.read()
processed... | 38,512 |
def build_name(prefix: str, source_ind: int, name: Path) -> str:
"""Build a package name from the index and path."""
if name.name.casefold() == '__init__.py':
name = name.parent
name = name.with_suffix('')
dotted = str(name).replace('\\', '.').replace('/', '.')
return f'{prefix}_{source_ind:... | 38,513 |
def step(x, mu, sigma, bkg, a):
"""
A step function template
Can be used as a component of other fit functions
"""
step_f = bkg + a * erfc((x-mu)/(np.sqrt(2)*sigma))
return step_f | 38,514 |
def parse_args():
"""Command line argument parsing."""
global flag_serial
try:
optlist, args = getopt.getopt(sys.argv[1:], "d")
except getopt.GetoptError as err:
# unrecognized option
usage(str(err))
if not args or len(args) != 1:
usage("supply a single device serial number as argument")
fl... | 38,515 |
def run():
"""Entrypoint for 'neurotin.preprocessing.pipeline'."""
parser = argparse.ArgumentParser(
prog="NeuroTin", description="NeuroTin auto-preprocessing pipeline."
)
parser.add_argument(
"dir_in",
type=str,
help="folder where FIF files to process are stored.",
)... | 38,516 |
def json_line_to_track(line):
"""Converts a json line to an appropriate Track object
"""
track_dct = json.loads(line)
# Clean up word count dictionary
wc_dct = {}
for word_id, word_count in track_dct['wordcount'].iteritems():
wc_dct[int(word_id)] = int(word_count)
track = Track(track... | 38,517 |
def update_planting(
key, secret, planting_info,
):
"""Updates a specified planting.
API reference: https://docs.awhere.com/knowledge-base-docs/field-plantings/
Parameters
----------
key : str
API key for a valid aWhere API application.
secret : str
API secret for a valid ... | 38,518 |
def check_for_multiple(files):
""" Return list of files that looks like a multi-part post """
for regex in _RE_MULTIPLE:
matched_files = check_for_sequence(regex, files)
if matched_files:
return matched_files
return "" | 38,519 |
def get_density2D(f,data,steps=100):
""" Calcule la densité en chaque case d'une grille steps x steps dont les bornes sont calculées à partir du min/max de data. Renvoie la grille estimée et la discrétisation sur chaque axe.
"""
xmin, xmax = data[:,0].min(), data[:,0].max()
ymin, ymax = data[:,1].min(), data[:,1].m... | 38,520 |
def draw_cards_command(instance, player, arguments):
""" Draw cards from the deck and put them into the calling player's hand.
Args:
instance: The GameInstance database model for this operation.
player: The email address of the player requesting the action.
arguments: A list of arguments to this comman... | 38,521 |
def recipe_content(*,
projects_base,
project,
recipe):
"""
Returns the content of a recipe in a project, based on the
projects base path, and the project and recipe name.
Kwargs:
projects_base (str): base path for all projects, e.g.
... | 38,522 |
def mock_is_dir_true(monkeypatch):
"""Fake directory exists."""
mock_is_dir = mock.Mock()
mock_is_dir.return_value = True
monkeypatch.setattr("version_hunter.versioner.os.path.isdir", mock_is_dir) | 38,523 |
def precision_score(
y_true: str,
y_score: str,
input_relation: Union[str, vDataFrame],
cursor=None,
pos_label: (int, float, str) = 1,
):
"""
---------------------------------------------------------------------------
Computes the Precision Score.
Parameters
----------
y_true: str
Response col... | 38,524 |
def new_deployment(name):
"""
Creates a new deployment in the /deployments directory.
Usage:
`drone-deploy new NAME`
Where NAME == a friendly name for your deployment.
Example:
`drone-deploy new drone.yourdomain.com`
"""
# create the deployment/$name directory
deployme... | 38,525 |
def GenerateConfig(context):
"""Returns a list of configs and waiters for this deployment.
The configs and waiters define a series of phases that the deployment will
go through. This is a way to "pause" the deployment while some process on
the VMs happens, checks for success, then goes to the next phase.
Th... | 38,526 |
def test_get_row_ngrams(mention_setup):
"""Test the get_row_ngrams function."""
mentions = mention_setup
assert mentions[52].get_span() == "saag"
assert list(get_row_ngrams(mentions[52])) == ["paneer"] + ["joan"] + ["medium"] + [
"$",
"11",
]
# when a mention is not tabular
... | 38,527 |
def test_config_restore_from_model_state():
""" Test restoring object from full model state
"""
state = {'__model__': 'cryptater.app.config.ConfigOptions', '__ref__': 'f6422d2cb1681771eed6d4ada89f28', '_id': '',
'loglevel': 'DEBUG'}
cfg = asyncio.run(ConfigOptions.restore(state))
asser... | 38,528 |
def _format_param_value(value_repr):
"""
Format a parameter value for displaying it as test output. The
values are string obtained via Python repr.
"""
regexs = ["^'(.+)'$",
"^u'(.+)'$",
"^<class '(.+)'>$"]
for regex in regexs:
m = re.match(regex, value_repr... | 38,529 |
def HackMaxTime(maxTime=8*60*60):
"""Set maxTime default value to 8 hours. This function must be called before
adding steps."""
from buildbot.process.buildstep import RemoteShellCommand
assert RemoteShellCommand.__init__.func_defaults == (None, 1, 1, 1200, None,
{}, 'slave-config', True)
RemoteShellComm... | 38,530 |
def redis_get_keys(duthost, db_id, pattern):
"""
Get all keys for a given pattern in given redis database
:param duthost: DUT host object
:param db_id: ID of redis database
:param pattern: Redis key pattern
:return: A list of key name in string
"""
cmd = 'sonic-db-cli {} KEYS \"{}\"'.for... | 38,531 |
def data_process(X, labels, window_size, missing):
"""
Takes in 2 numpy arrays:
- X is of shape (N, chm_len)
- labels is of shape (N, chm_len)
And returns 2 processed numpy arrays:
- X is of shape (N, chm_len)
- labels is of shape (N, chm_len//window_size)
"""
# Re... | 38,532 |
def check_response_status(curr_response, full_time):
"""Check response status and return code of it.
This function also handles printing console log info
Args:
curr_response (str): Response from VK API URL
full_time (str): Full format fime for console log
Returns:
int: Sta... | 38,533 |
def height_to_amplitude(height, sigma):
"""
Convert height of a 1D Gaussian to the amplitude
"""
return height * sigma * np.sqrt(2 * np.pi) | 38,534 |
def get_param_value(val, unit, file, line, units=True):
"""
Grab the parameter value from a line in the log file.
Returns an int, float (with units), bool, None (if no value
was provided) or a string (if processing failed).
"""
# Remove spaces
val = val.lstrip().rstrip()
# Is there a v... | 38,535 |
def assert_array_equal(x: numpy.ndarray, y: List[Union[float, int]]):
"""
usage.scipy: 7
usage.seaborn: 2
usage.sklearn: 2
"""
... | 38,536 |
def exact_auc(errors, thresholds):
"""
Calculate the exact area under curve, borrow from https://github.com/magicleap/SuperGluePretrainedNetwork
"""
sort_idx = np.argsort(errors)
errors = np.array(errors.copy())[sort_idx]
recall = (np.arange(len(errors)) + 1) / len(errors)
errors = np.r_[0.,... | 38,537 |
def avalanche_basic_stats(spike_matrix):
"""
Example
-------
total_avalanches, avalanche_sizes, avalanche_durations = avalanche_stats(spike_matrix)
"""
total_spikes = spike_matrix.sum(axis=0)
total_spikes = np.hstack(([0], total_spikes)) # Assure it starts with no spike
avalanche = pd.S... | 38,538 |
def parse_jax_dot_general(parameters, innodes):
"""
Parse the JAX dot_general function.
Parameters
----------
parameters: A dict containing the parameters of the dot_general function.
parameters['dimension_numbers'] is a tuple of tuples of the form
((lhs_contracting_dims, rhs_contra... | 38,539 |
def get_stratum_alert_data(threshold: float, notification_channel: int) -> Dict[str, Any]:
""" Gets alert config for when stratum goes below given threshold
:param threshold: Below this value, grafana should send an alert
:type description: float
:param notification_channel: Id of the noti... | 38,540 |
def opponent1(im, display=False):
""" Generate Opponent color space. O3 is just the intensity """
im = img.norm(im)
B, G, R = np.dsplit(im, 3)
O1 = (R - G) / np.sqrt(2)
O2 = (R + G - 2 * B) / np.sqrt(6)
O3 = (R + G + B) / np.sqrt(3)
out = cv2.merge((np.uint8(img.normUnity(O1) * 255),
... | 38,541 |
def shuffle_multiset_data(rv, rv_err):
"""
"""
#shuffle RV's and their errors
comb_rv_err = zip(rv, rv_err)
random.shuffle(comb_rv_err)
comb_rv_err_ = [random.choice(comb_rv_err) for _ in range(len(comb_rv_err))]
rv_sh, rv_err_sh = zip(*comb_rv_err_)
return np.array(rv_sh), np.array... | 38,542 |
def parse_pubdate(text):
"""Parse a date string into a Unix timestamp
>>> parse_pubdate('Fri, 21 Nov 1997 09:55:06 -0600')
880127706
>>> parse_pubdate('2003-12-13T00:00:00+02:00')
1071266400
>>> parse_pubdate('2003-12-13T18:30:02Z')
1071340202
>>> parse_pubdate('Mon, 02 May 1960 09:0... | 38,543 |
def test_draw_group(client):
"""attempt to draw a lottery as a group
1. make some applications to one lottery as a group
2. draws the lottery
3. test: status code
4. test: DB is changed
5. test: result of each member (win)
target_url: /lotteries/<id>/draw [POST]
"... | 38,544 |
def find_ngram(x: np.ndarray, occurence: int= 2) -> List[int]: # add token
"""
Build pairwise of size occurence of conssecutive value.
:param x:
:type x: ndarray
:param occurence: number of succesive occurence
:type occurence: int
:return:
:rtype:
Example:
--------
>>> a = n... | 38,545 |
def list2ids(listf, verbose=False):
""" Read a list of ids, one per line
:param listf: file of ids
:param verbose: more output
:return: a set of IDS
"""
if verbose:
sys.stderr.write(f"{bcolors.GREEN} Reading IDs from text file: {listf}{bcolors.ENDC}")
i=set()
with open(listf, '... | 38,546 |
def ewma(current, previous, weight):
"""Exponentially weighted moving average: z = w*z + (1-w)*z_1"""
return weight * current + ((1.0 - weight) * previous) | 38,547 |
def test_values_int():
"""
Ensures that parsing an int produces the expected tree
"""
result = parse('3\n')
expression = result.block.rules.absolute_expression.expression
entity = get_entity(expression)
assert entity.values.number.child(0) == Token('INT', 3) | 38,548 |
def create(
filename,
config_file,
cancel_on_blocking_job_failure,
minutes_per_job,
shuffle,
strip_whitespace,
verbose,
):
"""Create a config file from a filename with a list of executable commands."""
level = logging.DEBUG if verbose else logging.WARNING
setup_logging("auto_conf... | 38,549 |
def srs_double(f):
"""
Creates a function prototype for the OSR routines that take
the OSRSpatialReference object and
"""
return double_output(f, [c_void_p, POINTER(c_int)], errcheck=True) | 38,550 |
def atmost_one(*args):
"""Asserts one of the arguments is not None
Returns:
result(bool): True if exactly one of the arguments is not None
"""
return sum([1 for a in args if a is not None]) <= 1 | 38,551 |
def _get_default_group():
"""
Getting the default process group created by :func:`init_process_group`.
"""
if not is_initialized():
raise RuntimeError(
"Default process group has not been initialized, "
"please make sure to call init_process_group."
)
return ... | 38,552 |
def switchon(dev, i):
"""
Switches outlet i of the device on.
@param dev: device
@param i: outlet
"""
assert i >= getminport(dev) and i <= getmaxport(dev)
enable(dev)
buf = bytes([0x00]);
# Read status
buf = dev.ctrl_transfer(0xC0, 0x0c, 0x0000, 0x01, buf, 500)
if len(buf) == 0:
raise RuntimeError("re... | 38,553 |
def test_inquire_telkom_response(setup_http_response, generate_sepulsa_response,
assert_inquire_telkom_bill):
""" simulate success inquire telkom response from sepulsa """
sepulsa_response = generate_sepulsa_response("INQUIRE_TELKOM")
mock_http_response = setup_http_respons... | 38,554 |
def string_parameter(name, in_, description=None):
"""
Define a string parameter.
Location must still be specified.
"""
return parameter(name, in_, str, description=description) | 38,555 |
def change_time(plan: Plan, items: dict):
"""Change arrival and departure time for each place in the plan.
Args:
plan: plan object selected to modify the place times.
items: modify information received from POST method.
"""
for place in items:
if place['arrival'] != "":
... | 38,556 |
def _transform_request(request):
"""
Convert from bytes/json/etc to dict of tf.tensor/np.array/etc
:param request:
:return:
"""
# TODO: Uncomment out one of the examples below - or provide your own implementation
#
# Note: The dict keys used below (ie. 'image') depend on the TF Signatur... | 38,557 |
def greater_version(versionA, versionB):
"""
Summary:
Compares to version strings with multiple digits and returns greater
Returns:
greater, TYPE: str
"""
try:
list_a = versionA.split('.')
list_b = versionB.split('.')
except AttributeError:
return versio... | 38,558 |
def test_a_command(vim_bot):
"""Append text after the cursor."""
main, editor_stack, editor, vim, qtbot = vim_bot
editor.stdkey_backspace()
editor.go_to_line(2)
# editor.stdkey_up(True)
editor.moveCursor(QTextCursor.StartOfLine, QTextCursor.KeepAnchor)
cmd_line = vim.get_focus_widget()
l... | 38,559 |
def copy_env_files(src_prefix, dest_prefix):
"""Export a copy of conda env var files to local dir.
Args:
src_prefix (pathlib.Path):
- Path prefix for env files
dest_prefix (pathlib.Path):
- Destination path prefix
"""
src_paths = load_env_paths(src_prefix)
... | 38,560 |
def create_starting_samples(run_dict, space_obj, start_from_last_gen):
"""
Load the starting samples for the optimization run.
Parameters
----------
run_dict : dict
The dictionary with user-defined values for
the characterization of the optimization.
space_obj : object
... | 38,561 |
def py_repl_close():
"""Function to close the REPL"""
pass | 38,562 |
def get_post_mapping(content):
"""This function extracts blog post title and url from response object
Args:
content (request.content): String content returned from requests.get
Returns:
list: a list of dictionaries with keys title and url
"""
post_detail_list = []
post_soup = ... | 38,563 |
def transform(original_documentation_dir, generated_docs_dir, version, options=None):
"""
Given a raw repo directory contents, perform the following steps (conditional to the repo):
- Generate the output HTML contents from its source content generator engine.
- Strip their contents from the static files... | 38,564 |
def get_output_foldername(start_year: int, end_year: int) -> str:
""" Create an output folder and return its name """
folder_name = "app/data/{}-{}".format(start_year, end_year)
if not os.path.exists(folder_name):
os.mkdir(folder_name)
return folder_name | 38,565 |
def test_raises_exception_when_temp_too_low():
"""Checks if exception is raised if Fridge class is instantiated with temp
below 1."""
with pytest.raises(ValueError, message="Ice cream or beer Sir?"):
wrong_temp_fridge = Fridge("INV2401PH", temp=0) | 38,566 |
def test__get_max_wt():
"""Testing the sampling function"""
lows = np.array(
[
[0.0, 0.0, 0.0, 0.0],
[-1.0, -1.0, -1.0, -1.0],
[-2.0, -2.0, -2.0, -2.0],
[2.0, 2.0, 2.0, 2.0],
]
)
highs = np.array(
[
[1.0, 1.0, 1.0, 1.0],... | 38,567 |
def _dict_attribute_help(object_name, path, parent_object_names, attribute):
"""
Get general help information or information on a specific attribute.
See get_help().
:param (str|unicode) attribute: The attribute we'll get info for.
"""
help_dict = {
'object_name': object_name,
... | 38,568 |
def len_iter(iterator):
"""Count items in an iterator"""
return sum(1 for i in iterator) | 38,569 |
def clones(module, N):
"""Produce N identical layers."""
return nn.ModuleList([copy.deepcopy(module) for _ in range(N)]) | 38,570 |
def form_transfer(form):
"""
:param form: formula in string type. e.g. 'y~x1+x2|id+firm|id',dependent_variable~continuous_variable|fixed_effect|clusters
:return: Lists of out_col, consist_col, category_col, cluster_col, fake_x, iv_col respectively.
"""
form = form.replace(' ', '')
out_col, con... | 38,571 |
def test_dfs_radar_chanlist(dev, apdev):
"""DFS chanlist when radar is detected"""
try:
hapd = None
hapd = start_dfs_ap(apdev[0], chanlist="40 44", allow_failure=True)
time.sleep(1)
dfs_simulate_radar(hapd)
ev = wait_dfs_event(hapd, "DFS-CAC-COMPLETED", 5)
if ev... | 38,572 |
def merge_metadata(preprocess_output_dir, transforms_file):
"""Merge schema, analysis, and transforms files into one python object.
Args:
preprocess_output_dir: the output folder of preprocessing. Should contain
the schema, and the numerical and categorical
analysis files.
transforms_file: ... | 38,573 |
def get_user(request):
"""
Returns the user model instance associated with the given request session.
If no user is retrieved an instance of `MojAnonymousUser` is returned.
"""
user = None
try:
user_id = request.session[SESSION_KEY]
token = request.session[AUTH_TOKEN_SESSION_KEY]... | 38,574 |
def main(database):
"""
:type database: db.BlogDB
"""
sqls = []
sql_create_articles = 'CREATE TABLE {} '.format(database.table_name['articles']) + \
'(id INTEGER PRIMARY KEY AUTOINCREMENT, slug CHAR(100) NOT NULL UNIQUE, cat_id INT,' + \
'ti... | 38,575 |
def fav_rate(y_pred_group):
"""
Gets rate of favorable outcome.
:param y_pred_group: Model-predicted labels of test set for privileged/unprivileged group
:type y_pred_group: `np.array`
:return: rate of favorable outcome
:rtype: `float`
"""
if y_pred_group == []:
return 0
els... | 38,576 |
def parse_date(datestring):
"""
Parse a date/time string into a tuple of integers.
:param datestring: The date/time string to parse.
:returns: A tuple with the numbers ``(year, month, day, hour, minute,
second)`` (all numbers are integers).
:raises: :exc:`InvalidDate` when the date ca... | 38,577 |
def read_datafiles(filepath):
"""
Example function for reading in data form a file.
This needs to be adjusted for the specific format that
will work for the project.
Parameters
----------
filepath : [type]
[description]
Returns
-------
[type]
[descriptio... | 38,578 |
def test_cte_patch(transacted_postgresql_db, query, alias):
"""Tests patching a CTE"""
patch = pgmock.patch(pgmock.cte(alias),
[('val1.1', 'val2.1'), ('val1.2', 'val2.2')],
['c1', 'c2'])
sql = pgmock.sql(query, patch)
res = transacted_postgresql_db.conn... | 38,579 |
def get_outputs(var_target_total, var_target_primary, reg, layer):
"""Construct standard `vlne` output layers."""
outputs = []
if var_target_total is not None:
target_total = Dense(
1, name = 'target_total', kernel_regularizer = reg
)(layer)
outputs.append(target_total... | 38,580 |
def getJsonPath(name, moduleFile):
"""
获取JSON配置文件的路径:
1. 优先从当前工作目录查找JSON文件
2. 若无法找到则前往模块所在目录查找
"""
currentFolder = os.getcwd()
currentJsonPath = os.path.join(currentFolder, name)
if os.path.isfile(currentJsonPath):
jsonPathDict[name] = currentJsonPath
return currentJsonPa... | 38,581 |
def flatten_list(l):
"""
Function which flattens a list of lists to a list.
"""
return functools.reduce(operator.iconcat, l, []) | 38,582 |
def js_to_python(in_file, out_file=None, use_qgis=True, github_repo=None):
"""Converts an Earth Engine JavaScript to Python script.
Args:
in_file (str): File path of the input JavaScript.
out_file (str, optional): File path of the output Python script. Defaults to None.
use_qgis (bool, ... | 38,583 |
def getPutDeltas(delta, optType):
"""
delta: array or list of deltas
optType: array or list of optType "C", "P"
:return:
"""
# otm_x = put deltas
otm_x = []
for i in range(len(delta)):
if optType[i] == "C":
otm_x.append(1-delta[i])
else:
otm_x.appe... | 38,584 |
def test_folders_has_path_long(list_folder_path, max_path=260):
"""tests a serie of folders if any of them has files whose pathfile
has a larger length than stipulated in max_path
Args:
list_folder_path (list): list of folder_path to be tested
max_path (int, optional): max file_path len per... | 38,585 |
def get_positive_empirical_prob(labels: tf.Tensor) -> float:
"""Given a set of binary labels, determine the empirical probability of a positive label (i.e., the proportion of ones).
Args:
labels: tf.Tensor, batch of labels
Returns:
empirical probability of a positive label
"""
n_pos_labels = tf.math... | 38,586 |
def xonsh_builtins(xonsh_events):
"""Mock out most of the builtins xonsh attributes."""
builtins.__xonsh_env__ = DummyEnv()
if ON_WINDOWS:
builtins.__xonsh_env__['PATHEXT'] = ['.EXE', '.BAT', '.CMD']
builtins.__xonsh_ctx__ = {}
builtins.__xonsh_shell__ = DummyShell()
builtins.__xonsh_hel... | 38,587 |
def RELOAD():
"""
RELOAD - reload the environment variable handler, envvar_handler
"""
global envvar_handler
envvar_handler = ColabEnvHandler() | 38,588 |
def episode_reset(): #Hàm thiết lập lại episode cho quá trình warmup và training
"""
Resets the episode/conversation in the warmup and training loops.
Called in warmup and train to reset the state tracker, user and agent. Also get's the initial user action.
"""
# First reset the state tra... | 38,589 |
def networks_get_by_id(context, network_id):
"""Get a given network by its id."""
return IMPL.networks_get_by_id(context, network_id) | 38,590 |
def get_particles(range_diff, image, clustering_settings):
"""Get the detections using Gary's original method
Returns a list of particles and their properties
Parameters
----------
range_diff:
output from background subtraction
image:
original image frame for intensity calculat... | 38,591 |
def validate_file(file):
"""Validate that the file exists and is a proper puzzle file.
Preemptively perform all the checks that are done in the input loop of sudoku_solver.py.
:param file: name of file to validate
:return True if the file passes all checks, False if it fails
"""
try:
o... | 38,592 |
def poly(coeffs, n):
"""Compute value of polynomial given coefficients"""
total = 0
for i, c in enumerate(coeffs):
total += c * n ** i
return total | 38,593 |
def group_by_vals(
features: Iterable[feature]
) -> Dict[Hashable, Tuple[feature, ...]]:
"""
Construct a dict grouping features by their values.
Returns a dict where each value is mapped to a tuple of features that have
that value. Does not check for duplicate features.
:param features: A... | 38,594 |
def show_error(msg):
"""
Show an error message and exit
"""
log.critical("Error: %s" % msg)
sys.exit(1) | 38,595 |
def sync_users(api_token, input_filepath):
"""
Load local User data, get system User data, compare and add users to system
"""
sc_client = sp.SafetyCulture(api_token)
logger = import_grs.configure_logger()
# Validating the CSV input first
dataValidator = open(input_filepath,'r')
reader=... | 38,596 |
def observe_queue(env, cafe, obs_time, queue_length):
""" Process to observe the queue length during a simulation.
Args:
env (simpy.Environment): the simulation environment
cafe (CafeJava): the cafe to observe
obs_time (list): the observation times
queue_length (list): the obser... | 38,597 |
async def pingme(pong):
""" .ping komutu userbotun ping değerini herhangi bir sohbette gösterebilir. """
start = datetime.now()
await pong.edit("`Pong!`")
end = datetime.now()
duration = (end - start).microseconds / 1000
await pong.edit("`Pong!\n%sms`" % (duration)) | 38,598 |
def coords2cells(coords, meds, threshold=15):
"""
Single plane method with KDTree. Avoid optotune <-> holography mismatch weirdness.
Threshold is in pixels.
"""
holo_zs = np.unique(coords[:,2])
opto_zs = np.unique(meds[:,2])
matches = []
distances = []
ismatched = []
for hz, oz... | 38,599 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.