content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def enforce_types(target):
"""Class decorator adding type checks to all member functions
"""
def check_types(spec, *args, **kwargs):
parameters = dict(zip(spec.args, args))
parameters.update(kwargs)
for name, value in parameters.items():
with suppress(KeyError): # Assume... | 27,100 |
def get_article(URL):
"""
Get an article from one our trusted sources.
Args:
URL: URL string to parse, e.g., http://www.hello.com/world
Returns
Article object if URL was success requested and parsed.
None if it fails to parse or the URL is from a source not
in the trust... | 27,101 |
def main():
"""
Create a segmented array.
Compute basic stats for each segment:
(min, max, mean, standard deviation, total, area)
Write the segmented image and the raster attribute table.
"""
# data dimensions
dims = (1000, 1000)
# create some random data and segment via value ... | 27,102 |
def crop_central_whiten_images(images=None, height=24, width=24):
"""Crop the central of image, and normailize it for test data.
They are cropped to central of height * width pixels.
Whiten (Normalize) the images.
Parameters
----------
images : 4D Tensor
The tensor or placeholder of i... | 27,103 |
def get_post(_activePost):
"""
functions to get the input scrapping post url
:return: a list
"""
_link = []
if _activePost == "postLink1":
_scrapping_link = request.form.get("singlePost")
_processed_link = _scrapping_link.replace("www", "m")
_link.append(_processed_link)
... | 27,104 |
def init_app():
"""init sdk app
The appID & app Secret use the Android's application ID and Secret under the same project, next version you can use
the web application's own appId & secret!
"""
# TODO
app_id_at = "Your android application's app id"
app_secret_at = "Your android application's... | 27,105 |
def start(event):
"""
Whether or not return was pressed
"""
return event.type == KEYDOWN and event.key == system["ENTER"] | 27,106 |
def cost(theta, X, y):
"""cost fn is -1(theta) for you to minimize"""
return np.mean(-y * np.log(sigmoid(X @ theta)) - (1 - y) * np.log(1 - sigmoid(X @ theta))) | 27,107 |
def enrich_nodes(nodes, vindplaatsen, articles):
"""
Add some attributes to the nodes.
:param nodes:
:param vindplaatsen:
:return:
"""
nodes = add_year(nodes)
nodes = add_articles(nodes, articles)
nodes = add_versions(nodes, vindplaatsen)
return nodes | 27,108 |
def assert_warns(warning_class: Type[RuntimeWarning], *args: Literal["v", "t"]):
"""
usage.scipy: 6
"""
... | 27,109 |
def has_string(match):
"""Matches if ``str(item)`` satisfies a given matcher.
:param match: The matcher to satisfy, or an expected value for
:py:func:`~hamcrest.core.core.isequal.equal_to` matching.
This matcher invokes the :py:func:`str` function on the evaluated object to
get its length, pas... | 27,110 |
def get_land_sea_mask(gridded_geo_box, \
ancillary_path='/g/data/v10/eoancillarydata/Land_Sea_Rasters'):
"""
Return a land/sea 2D numpy boolean array in which Land = True, Sea = False
for the supplied GriddedGeoBox and using the UTM projected data in the
supplied ancillary_path.
If the spec... | 27,111 |
def qEI_brute(gp_, true_function, X_=np.linspace(0, 1, 200), q=3,
niterations=10, nsim=1000):
"""
q steps EI performed with brute force: Brute search on vector X_
"""
gp = copy.copy(gp_)
i = 0
nn = X_.shape[0]
rshape = q * [nn]
qEI_to_evaluate = np.asarray([np.vstack(np.arr... | 27,112 |
def potential_energy_diff(e_in, e_out):
"""Returns difference in potential energy.
arguments:
e_in - dictionary of energy groups from input file
e_out - dictionary of energy groups from output file
returns:
potential energy difference in units of the input
"""
energy_type ... | 27,113 |
def test_source(source, sourcer_params):
"""
Paths Source - Test various source paths/urls supported by Sourcer.
"""
try:
sourcer = Sourcer(
source, custom_ffmpeg=return_static_ffmpeg(), verbose=True, **sourcer_params
).probe_stream()
logger.debug("Found Metadata: `{}... | 27,114 |
def CA_potential_profile(pot_init: float, pot_step: float, pot_rest: float,
pot_init_time: float, pot_step_time: float, pot_rest_time: float,
buffer_size: int = 1200, samp_rate: int = 3600) -> tuple:
"""
:param pot_init: Initial potential in V
:param pot_ste... | 27,115 |
def generate_model_class(grid_dir, data_dir, Nlon=936, Nlat=1062, Nz=90):
"""
Wrapper function for generating the LLCRegion object describing the
model region. The wrapper automatically reads the grid information.
Default values for grid size are for the Samoan Passage box (Box 12
in Dimitris' notat... | 27,116 |
def discretize_integrate_2D(model, x_range, y_range):
"""
Discretize model by integrating the model over the pixel.
"""
from scipy.integrate import dblquad
# Set up grid
x = np.arange(x_range[0] - 0.5, x_range[1] + 0.5)
y = np.arange(y_range[0] - 0.5, y_range[1] + 0.5)
values = np.empty(... | 27,117 |
def get_saved_model_list(ckpt_dir):
"""Return a list of HDF5 models found in ckpt_dir
"""
filenames_list = []
for (root, directories, filenames) in os.walk(ckpt_dir):
filenames_list += filenames
# Break to only keep the top directory
break
ckpt_list = []
for filename in f... | 27,118 |
def detail(request, question_id):
"""
HelloWorld 내용 출력
"""
question = get_object_or_404(Question, pk=question_id)
context = {'question': question}
return render(request, 'HelloWorld/question_detail.html', context) | 27,119 |
def get_dataset_metadata(data_directory_path: str, output_directory_path: str = None) -> None:
""" Get the metadata of all available datasets from the Open Reaction Database. """
try:
ids, names, descriptions, row_counts = [], [], [], []
for directory_name in tqdm(
iterable=os.... | 27,120 |
def plot_peridogramm_from_timeseries(data: np.ndarray, kwargs: dict, add_smoothing: bool = False,
f_list: List[Tuple[float, str]] = None,
bg_model: List[np.ndarray] = None, plot_name: str = None):
"""
Directly converts a timeseries and pl... | 27,121 |
def TDataStd_BooleanArray_GetID(*args):
"""
* Static methods ============== Returns an ID for array.
:rtype: Standard_GUID
"""
return _TDataStd.TDataStd_BooleanArray_GetID(*args) | 27,122 |
def dt_fits_table():
"""
----------------------------------------------------------------------------------
Demo and test the basic API for FITS tables:
>>> old_state = test_config.setup(url="https://jwst-serverless-mode.stsci.edu")
>>> FITS_FILE = "data/v8q14451j_idc.fits"
>>> tables.ntables(F... | 27,123 |
def get_axis_order():
"""Get the axis_order set by any containing axis_order_scope.
Returns:
List of strings giving an order to use for axis names, or None, if no axis
order is set.
"""
# By storing axis_order in the graph, we can ensure that axis_order_scope is
# thread-safe.
axis_order_list = ops... | 27,124 |
def check_jax_usage(enabled: bool = True) -> bool:
"""Ensures JAX APIs (e.g. :func:`jax.vmap`) are used correctly with Haiku.
JAX transforms (like :func:`jax.vmap`) and control flow (e.g.
:func:`jax.lax.cond`) expect pure functions to be passed in. Some functions
in Haiku (for example :func:`~haiku.get_paramet... | 27,125 |
def features_change(attrname, old, new):
"""Callback for features checkbox group."""
if new == []:
train_button.disabled = True
else:
train_button.disabled = False | 27,126 |
def checkout(
id: str,
workspace: str = get_workspace(),
slug: str = get_slug(),
):
"""Checkout PR by ID"""
url = pr_url.format(workspace=workspace, slug=slug, id=id)
console = Console()
with console.status("[bold green]Loading..."):
resp = get(url)
branch_name = resp["source"]["... | 27,127 |
def test_build_sql_with_map():
"""
Test ``build_sql`` with a column map.
"""
columns = {f"col{i}_": Integer() for i in range(4)}
bounds = {
"col0_": Equal(1),
"col1_": Range(start=0, end=1, include_start=True, include_end=False),
"col2_": Range(start=None, end=1, include_star... | 27,128 |
def score_numeric_deg_ssetype(omega_a, omega_b):
"""
Return the tableau matching score between two Omega matrix entries
omega_a and omega_b, as per Kamat et al (2008),
with effiectvely negative infinty score for SSE type mismatch
Parameters:
omega_a - angle in (-pi, pi]
omega_b - an... | 27,129 |
def top_menu(context, calling_page=None):
"""
Checks to see if we're in the Play section in order to return pages with
show_in_play_menu set to True, otherwise retrieves the top menu
items - the immediate children of the site root. Also detects 404s in the
Play section.
"""
if (calling_page ... | 27,130 |
def DefineJacobian(J, DN, x):
""" This method defines a Jacobian
Keyword arguments:
J -- The Jacobian matrix
DN -- The shape function derivatives
x -- The variable to compute the gradient
"""
[nnodes, dim] = x.shape
localdim = dim - 1
if (dim == 2):
if (nnodes == 2):
... | 27,131 |
def wav_vs_gmm(filebasename, gmm_file, gender, custom_db_dir=None):
"""Match a wav file and a given gmm model file and produce a segmentation
file containing the score obtained.
:type filebasename: string
:param filebasename: the basename of the wav file to process
:type gmm_file: string
:para... | 27,132 |
def run_remove_background(args):
"""The full script for the command line tool to remove background RNA.
Args:
args: Inputs from the command line, already parsed using argparse.
Note: Returns nothing, but writes output to a file(s) specified from
command line.
"""
# Load dataset, ... | 27,133 |
def build_reg_text_tree(text, part):
"""Build up the whole tree from the plain text of a single regulation. This
only builds the regulation text part, and does not include appendices or
the supplement. """
title, body = utils.title_body(text)
label = [str(part)]
subparts_list = []
subpart_... | 27,134 |
def check_url_alive(url, accept_codes=[401]):
"""Validate github repo exist or not."""
try:
logger.info("checking url is alive", extra={"url": url})
response = request.urlopen(url)
status_code = response.getcode()
if status_code in accept_codes or status_code // 100 in (2, 3):
... | 27,135 |
def solve(banks):
"""Calculate number of steps needed to exit the maze
:banks: list of blocks in each bank
:return: number of redistribtion cycles to loop
>>> solve([0, 2, 7, 0])
4
"""
seen = set()
loops = 0
mark = 0
for cycle in count(1):
# find value and the index o... | 27,136 |
def evaluate_python_expression(body):
"""Evaluate the given python expression, returning its result. This is useful if the
front end application needs to do real-time processing on task data. If for instance
there is a hide expression that is based on a previous value in the same form.
The response inc... | 27,137 |
def DictFilter(alist, bits):
"""Translate bits from EDID into a list of strings.
Args:
alist: A list of tuples, with the first being a number and second a string.
bits: The bits from EDID that indicate whether each string is supported by
this EDID or not.
Returns:
A dict of strings and bools... | 27,138 |
def test_extract_from_logfile(runpath):
"""Test extracting values from a logfile via regex matching."""
logname = "file.log"
a = "1"
b = "23a"
message = "Value a={a} b={b}".format(a=a, b=b)
log_regexps = [
re.compile(r".*a=(?P<a>[a-zA-Z0-9]*) .*"),
re.compile(r".*b=(?P<b>[a-zA-Z0... | 27,139 |
def mentions(request):
"""Mentions view."""
return render(request, "mentions.html", {"site_title": "Mentions legales"}) | 27,140 |
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry):
"""activity assistant form a config entry
is only called once the whole magic has to happen here
"""
#_LOGGER.warning(str(entry.version))
#_LOGGER.warning(str(entry.entry_id))
#_LOGGER.warning(str(entry.title))
#_LOGGER.... | 27,141 |
def delete(id):
""" Used by the product page to delete a product. Doesn't actually delete it, just sets the quantity to 0. """
db = get_db()
b_id = session.get("user_id")
query = "UPDATE product SET quantity = 0 WHERE product_id = ? AND for_business = ?"
db.execute(query, (id, b_id,))
db... | 27,142 |
def test_hasname(name, exists):
"""Check if a name exist in registry"""
registry = RstConfigSite()
registry.update({
'foo': 42,
'bar': True,
})
assert registry.has_name(name) == exists | 27,143 |
def resume_training(model_to_resume: str,
dataset_oversampling: Dict[str, int],
checkpoint: Optional[str] = None,
epochs: Optional[int] = None
):
"""Resume training on a partially trained model (or finetune an existing model)
:par... | 27,144 |
def from_meshmaker(filename_or_dict, material="dfalt"):
"""
Generate a mesh from a block MESHM.
Parameters
----------
filename_or_dict: str or dict
Input file name or parameters dict with key "meshmaker".
material : str, optional, default 'dfalt'
Default material name.
"""
... | 27,145 |
def compute_qtys_new_halos_pk(mvir, rvir, redshift, age_yr):
"""
Creates a new galaxy along with the new halo.
Integrates since the start of the Universe.
Updates the initiated quantities with the values of interest.
:param mvir: list of mvir [Msun], length = n.
:param rvir: list of rvir [kpc] , length = n.
... | 27,146 |
def rank():
"""A function which returns the Horovod rank of the calling process.
Returns:
An integer scalar with the Horovod rank of the calling process.
"""
rank = MPI_LIB_CTYPES.horovod_tensorflow_rank()
if rank == -1:
raise ValueError(
'Horovod has not been initialized;... | 27,147 |
def main():
"""
Purpose:
Test the function
Args:
N/A
Returns:
N/A
"""
# Use the test data we have
# df = pd.read_csv("../../data/analysis_data_roadway_blocks.csv")
# 1400 - 1413 BLOCK OF SPRING ROAD NW
# sample address
address = "600 Farragut St. NW"
... | 27,148 |
def getRAMSizeOSX() -> CmdOutput:
"""Returns the RAM size in bytes.
Returns:
CmdOutput: The output of the command, as a `CmdOutput` instance containing
`stdout` and `stderr` as attributes.
"""
return runCommand(exe_args=ExeArgs("sysctl", ["-n", "hw.memsize"])) | 27,149 |
def apply_edge_filters(graph: networkx.MultiDiGraph, edge_filters: Dict[str, Union[str, Set]]) -> None:
"""
Apply filters to graph and remove edges that do not pass given filters.
Parameters
----------
graph: networkx.MultiDiGraph
The graph
edge_filters: Dict[str, Union[str, Set]]
... | 27,150 |
def load_data(filepath, columns=['title','abstract']):
"""Loads specified columns of csv/excel data.
Arguments
---------
filepath: str
Path to file (e.g. 'data.csv')
columns: list
List of strings specifying the column names in the data to load.
Returns
-------
pandas.Da... | 27,151 |
def pre_process(image):
"""
Invert pixel intensity of 'images' (to compensate the conversion into image with imwrite).
"""
return 1 - image * 255 | 27,152 |
def is_source_path(path):
"""Check if path is source code path.
Parameters
----------
path : str
A possible path
Returns
-------
valid : bool
Whether path is a possible source path
"""
if os.path.exists(path):
return True
if path.find("\n") != -1:
... | 27,153 |
def get_examples_to_execute(
predictions: Sequence[inference.Prediction], inference_config: inference.Config
) -> List[official_evaluation.ExecutionInstructions]:
"""
Converts predictions from a model into sqlite execution instructions. If abstract SQL was used, converts back to fully-specfied SQL.
"""
... | 27,154 |
def verify_query(ctx):
"""
Verify a LQL query.
"""
label_widget = ctx.get_state(state="query_builder", key="query_label")
lql_query = ctx.get("lql_query")
evaluator_id = ctx.get("lql_evaluator")
try:
_ = ctx.client.queries.validate(
lql_query, evaluator_id=evaluator_id)
... | 27,155 |
def data_feature_engineering(data):
"""
Add features to the data for later use
state_code, weekday, month, year
"""
data['state_code'] = data['state'].map(us_state_abbrev)
data['weekday'] = pd.to_datetime(data['date']).dt.weekday
data['weekday'] = data['weekday'].map(weekday_map)
mont... | 27,156 |
def gauss_to_post(config, num_jobs):
"""
Multiprocessing function that does Gaussian selection and posterior extraction
See:
- http://kaldi-asr.org/doc/gmm-global-get-post_8cc.html
- http://kaldi-asr.org/doc/scale-post_8cc.html
for more details
on the Kaldi binary this runs.
Also see... | 27,157 |
def test_bracketing():
"""The method getRegularlySampledBracketingPrfs() has some fairly complicated
bookkeeping to find the locations of the 4 prfs that brack the input col,row
in 2d space. It internally checks this bookkeeping is correct and raises
an assert on failure. This test exercises all 4 paths... | 27,158 |
def rename_folder(name, path):
""" Adapt the building block folder name.
Args:
name (str): Name to personalize the folder name.
path (str): Path to find the files.
"""
source = os.path.join(path, "src", "bb")
destination = os.path.join(path, "src", name)
os.rename(source, destin... | 27,159 |
def train_ei_oc(emotion, model, algorithm, evaluation, finetune, baseline, preprocessor=None):
"""
2. Task EI-oc: Detecting Emotion Intensity (ordinal classification)
Given:
a tweet
an emotion E (anger, fear, joy, or sadness)
Task: classify the tweet into one of four ordinal classes of intens... | 27,160 |
def new_person():
"""Fuction adds a new person into its database."""
name = 'interviewer'
filename = 'interviewer.jpeg'
image = cv.imread(filename)
encodings =[]
conv_image = cv.cvtColor(image,cv.COLOR_BGR2RGB)
encodings.append(fc.face_encodings(conv_image , fc.face_locations(image))[0])
with open('know... | 27,161 |
def cross(genom1, genom2, mutation_rate, widths, bounds):
"""
Generates a child_genom by breeding 2 parent_genoms with
a mutation chance = mutation rate = [0, 1].
"""
child_genom = []
for i in range(len(genom1)):
if widths[i] == 0:
child_genom.append(genom1[i])
... | 27,162 |
def version_0_2(path_in, path_out_base, skip_if_exists = True):
"""
* name is based on start time (not launch time)
:param path_in:
:param path_out_base:
:param skip_if_exists:
:return:
"""
version = 'v0.2'
content = raw.read_file(path_in)
name_new = generate_name(content)
p... | 27,163 |
def value_or_dash(value):
"""Converts the given value to a unicode dash if the value does
not exist and does not equal 0."""
if not value and value != 0:
return u'\u2013'.encode('utf-8')
return value | 27,164 |
def distroy_db(app):
"""
wipe the database
"""
pass | 27,165 |
def jaccard_index(box_a, box_b, indices=[]):
"""
Compute the Jaccard Index (Intersection over Union) of 2 boxes. Each box is (x1, y1, x2, y2).
:param box_a:
:param box_b:
:param indices: The indices of box_a and box_b as [box_a_idx, box_b_idx].
Helps in debugging DivideByZero err... | 27,166 |
def ComputePerSliceMetrics( # pylint: disable=invalid-name
slice_result: beam.pvalue.PCollection,
eval_shared_model: types.EvalSharedModel,
desired_batch_size: Optional[int] = None,
compute_with_sampling: Optional[bool] = False,
random_seed_for_testing: Optional[int] = None) -> beam.pvalue.PCollect... | 27,167 |
def null() -> ColumnExpr:
"""Equivalent to ``lit(None)``, the ``NULL`` value
:return: ``lit(None)``
.. admonition:: New Since
:class: hint
**0.6.0**
"""
return lit(None) | 27,168 |
def uCSIsThaana(code):
"""Check whether the character is part of Thaana UCS Block """
ret = libxml2mod.xmlUCSIsThaana(code)
return ret | 27,169 |
def geomprojlib_Curve2d(*args):
"""
* gives the 2d-curve of a 3d-curve lying on a surface ( uses GeomProjLib_ProjectedCurve ) The 3dCurve is taken between the parametrization range [First, Last] <Tolerance> is used as input if the projection needs an approximation. In this case, the reached tolerance is set in <T... | 27,170 |
def histogram(ds, x, z=None, **plot_opts):
"""Dataset histogram.
Parameters
----------
ds : xarray.Dataset
The dataset to plot.
x : str, sequence of str
The variable(s) to plot the probability density of. If sequence, plot a
histogram of each instead of using a ``z`` coordin... | 27,171 |
def get_full_file_path(filepath_parts, path, merge_point=None):
""""Typical path formats in json files are like:
"parent": "block/cube",
"textures": {
"top": "block/top"
}
This checks in filepath_parts of the blender file,
matches the base path, then merge... | 27,172 |
def test_fst_send_oom(dev, apdev, test_params):
"""FST send action OOM"""
ap1, ap2, sta1, sta2 = fst_module_aux.start_two_ap_sta_pairs(apdev)
try:
fst_module_aux.connect_two_ap_sta_pairs(ap1, ap2, sta1, sta2)
hapd = ap1.get_instance()
sta = sta1.get_instance()
dst = sta.own_a... | 27,173 |
def set_seed(seed: int) -> None:
"""
Set seed for reproducibility.
:param int seed: seed.
"""
random.seed(seed)
np.random.seed(seed) | 27,174 |
def get_resource(name):
"""Convenience method for retrieving a package resource."""
return pkg_resources.resource_stream(__name__, name) | 27,175 |
def get_team(args):
"""Return authenticated team token data."""
return Team.query.get(args['team_id']) | 27,176 |
def test_et_stack_run_proba():
"""[EnsembleTransformer | Stack | Prep] retrieves fit predictions."""
run(EnsembleTransformer, 'stack', True, True, folds=3) | 27,177 |
def make_unweight_time_optimal_supervisor(comp_names, req_names, evt_pairs,
sup_name):
"""
Compute a non weighted time optimal supervisor.
@param comp_names: Available components (weighted automata).
@type comp_names: C{list} of L{str}
@param req_names: Ava... | 27,178 |
def config_sanity_check(config: dict) -> dict:
"""
Check if the given config satisfies the requirements.
:param config: entire config.
"""
# back compatibility support
config = parse_v011(config)
# check model
if config["train"]["method"] == "conditional":
if config["dataset"]... | 27,179 |
def parse_yaml() -> Dataset:
"""Test that 'after' parameters are properly read"""
d = yaml.safe_load(f)
dataset = d.get("dataset")[0]
d: FidesopsDataset = FidesopsDataset.parse_obj(dataset)
return convert_dataset_to_graph(d, "ignore") | 27,180 |
def run(
desc_file, results_dir, start_date, walltime, n_days=1, no_submit=False, quiet=False
):
"""Create and populate a temporary run directory, and a run script,
and submit the run to the queue manager.
The run script is stored in :file:`SoGWW3.sh` in the temporary run directory.
That script is ... | 27,181 |
def race_data_cleaning(race_ethnicity_path):
"""Clean and relabel birth data based on race/ ethnicity."""
# Read in CSV.
race_df = pd.read_csv(race_ethnicity_path, na_values='*', engine='python')
# Fill na values with 0.
race_df.fillna(value=0, inplace=True)
# Drop default sort column.
rac... | 27,182 |
def validate_resource_policy(policy_document):
"""validate policy_document. Between 1 to 5120"""
if not isinstance(policy_document, policytypes):
raise ValueError("PolicyDocument must be a valid policy document")
if isinstance(policy_document, str) and not json_checker(policy_document):
ra... | 27,183 |
def ResolveOrganizationSecurityPolicyId(org_security_policy, display_name,
organization_id):
"""Returns the security policy id that matches the display_name in the org.
Args:
org_security_policy: the organization security policy.
display_name: the display name of the... | 27,184 |
def dump_annotations_workflow(
gc, slide_id, local, monitorPrefix='',
save_json=True, save_sqlite=False, dbcon=None,
callback=None, callback_kwargs=None):
"""Dump annotations for single slide into the local folder.
Parameters
-----------
gc : girder_client.GirderClient
a... | 27,185 |
def load_dataset(filenames, batch_size, corruption_func, crop_size):
"""
The following function generates a
random data out of filenames,
it keeps a cache dictionary of images,
once it is called, it generates
2 patches, out of the random image,
one is sampled from image-0.5, the other
is... | 27,186 |
def upsample_filt(size):
"""
Make a 2D bilinear kernel suitable for upsampling of the given (h, w) size.
"""
factor = (size + 1) // 2
if size % 2 == 1:
center = factor - 1
else:
center = factor - 0.5
og = np.ogrid[:size, :size]
return (1 - abs(og[0] - center) / factor) * \
(1 - abs(og[1] - center) / fact... | 27,187 |
def test_bossac_create_with_adafruit(cc, req, bcfg_ini, bcfg_check,
bcfg_val, get_cod_par, sup,
runner_config):
"""
Test SAM-BA extended protocol with Adafruit UF2 variation
Requirements:
SDK >= 0.12.0
Configuration:
Extended bootloader
CONFIG_USE_DT_CODE_PARTITION=y
CONFIG_BOOTL... | 27,188 |
def _MAC_hash(mac_str):
"""
Returns MAC hash value in uppercase hexadecimal form and truncated to
32 characters.
"""
return MD5.new(mac_str).hexdigest().upper()[:32] | 27,189 |
def divide_rows(matrix, column, in_place=False):
"""Divide each row of `matrix` by the corresponding element in `column`.
The result is as follows: out[i, j] = matrix[i, j] / column[i]
Parameters
----------
matrix : np.ndarray, scipy.sparse.csc_matrix or csr_matrix, shape (M, N)
The input ... | 27,190 |
def multiSMC(nruns=10, nprocs=0, out_func=None, collect=None, **args):
"""Run SMC algorithms in parallel, for different combinations of parameters.
`multiSMC` relies on the `multiplexer` utility, and obeys the same logic.
A basic usage is::
results = multiSMC(fk=my_fk_model, N=100, nruns=20, nproc... | 27,191 |
def test_X_setter():
"""Assert that the X setter changes the feature set."""
atom = ATOMClassifier(X_bin, y_bin, random_state=1)
atom.X = atom.X.iloc[:, :10]
assert atom.X.shape == (len(X_bin), 10) | 27,192 |
def colon_event_second(colon_word, words, start):
"""The second <something>
<something> can be:
* <day-name> -- the second day of that name in a month
"""
if len(words) != 1:
raise GiveUp('Expected a day name, in {}'.format(
colon_what(colon_word, words)))
elif words[0]... | 27,193 |
def outfalls_to_dfs(model, model_id):
""" Read a .CSV into a Pandas DataFrame until a blank line is found, then stop.
"""
global RELEVANT_NODES
RELEVANT_NODES = get_nodes_from_links(model, model_id)
start = build_groups_dicts(model)['nodes_outfalls']['start']
skip_rows = build_groups_dicts(mode... | 27,194 |
def get_count(path, **kwargs):
"""
Return the number of items in an dictionary or array
:param path: Path to the dictionary or array to count
This operation is only valid in :cb_bmeth:`lookup_in`
.. versionadded:: 2.2.5
"""
return _gen_3spec(_P.SDCMD_GET_COUNT, path, **kwargs) | 27,195 |
def test_basic_circle_net():
"""Test basic circle net forward
"""
circle_net = BasicCircleNet(
spatial_dims=2,
in_channels=5,
out_channels_heatmap=1,
out_channels_radius=3,
)
tensor = torch.from_numpy(
np.arange(3 * 5 * 32 * 32).reshape(
3, 5, ... | 27,196 |
def error_message() -> str:
"""Error message for invalid input"""
return 'Invalid input. Use !help for a list of commands.' | 27,197 |
def has_substring(string):
"""
Validate that the given substring is part of the given string.
>>> f = has_substring('foobarhamjam')
>>> f('arham')
True
>>> f('barham')
True
>>> f('FOO')
False
>>> f('JAMHAM')
False
:param str string: Main string to compare against.
:... | 27,198 |
def ReplyGump(gumpid: int, buttonid: int, switches: int, textentries: int, str6: str):
"""
Sends a button reply to server gump, parameters are gumpID and buttonID.
:param gumpid: ItemID / Graphic such as 0x3db.
:param buttonid: Gump button ID.
:param switches: Integer value - See description for ... | 27,199 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.