content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def do_split(txt_file):
"""save cv fold json"""
files = get_files_from_txt(txt_file)
kf = KFold(n_splits=4, random_state=123, shuffle=True)
train, val = {}, {}
for i, (train_index, val_index) in enumerate(kf.split(files)):
tmp_tr = [files[idx] for idx in train_index]
tmp_val... | 66,500 |
def visualize_dataset(images, labels, task):
"""
Helper function to visualize the dataset samples
"""
image_num = len(images)
subplot_rows = 1 if task == "Segmentation" else 4
for i in range(image_num):
plt.imshow(images[i])
plt.title('Original')
plt.savefig('./sbd_origin... | 66,501 |
def restart_system(fw):
"""
Restart the firewall
Parameters
----------
fw : Firewall
A PanDevice for firewall
"""
print('Restarting system...\n')
try:
command = '<request><restart><system></system></restart></request>'
fw.op(cmd=command, cmd_xml=False)
excep... | 66,502 |
def convertMDSToCreateObjectExpression(mds, path, allowPrivate, name, pathToCodeDefinitionStrings):
"""given an MDS and a path, return an expression
that creates a module member and the type of module member."""
tree = convertMDSToSourceCodeTree(mds, name)
parser = ForaNative.ModuleParser()
resul... | 66,503 |
def load_pickle(file, decompress=True):
"""
Load a .pickle file.
:param file: file .pickle to load.
:param decompress: the compress or not the file
:return: loaded data.
"""
with open(file, "rb") as f:
if decompress:
data = pickle.load(f)
else:
data = ... | 66,504 |
def delete_test_session(dirname=None):
"""Removes all file in directory so we can test writing to it"""
if dirname is None:
dirname = os.path.join(os.path.dirname(__file__),
'files_for_tests/klustakwik/test3')
for fi in glob.glob(os.path.join(dirname, '*')):
os... | 66,505 |
def main():
""" Run script extender if it exists. Use wine_mem_alloc_mod for skyui
"""
util.wine_mem_alloc_mod()
if os.path.isfile(os.path.join(os.getcwd(), 'skse64_loader.exe')):
zenity_bin = splash.sys_zenity_path()
if not zenity_bin:
return
zenity_cmd = ' '.join(... | 66,506 |
def plot_spectrogram(x, Fs=11025, N=4096, H=2048, figsize=(4, 2)):
"""Computation and subsequent plotting of the spectrogram of a signal
Notebook: C1/C1S3_Timbre.ipynb
Args:
x: Signal (waveform) to be analyzed
Fs: Sampling rate (Default value = 11025)
N: FFT length (Default value =... | 66,507 |
def _calc_traceback_limit(tb):
"""Calculates limit-parameter to strip away pytypes' internals when used
with API from traceback module.
"""
limit = 1
tb2 = tb
while not tb2.tb_next is None:
try:
maybe_pytypes = tb2.tb_next.tb_frame.f_code.co_filename.split(os.sep)[-2]
... | 66,508 |
def latex(df):
"""Converte o DF fornecido para tabela LaTeX"""
return print(df.to_latex()) | 66,509 |
def generate_king_attack_bb_from_square(from_square: int) -> np.uint64:
"""
Returns the king attack bitboard on an otherwise empty board from the provided square
:param from_square: starting square from which to generate king attacks
:return: np.uint64 bitboard representation of king attacks on an other... | 66,510 |
def get_review_by_product(request, id):
"""get reviews of certain product and return render"""
prod = get_object_or_404(Product, pk=id) # get product
related = Review_Connector.objects.all().select_related().filter(product_id=id)
context = {'review_connected': related,
"product_id": ... | 66,511 |
def kill_processes(processes, delay=1):
""" Kills processes in list. """
for proc in psutil.process_iter():
if proc.name in processes:
print('killing process: ' + proc.name)
proc.kill()
time.sleep(delay) | 66,512 |
def evaluate_nontrainable_policy_pk(
mlflow_experiment_name,
num_experiments_to_perform,
policy, # random or equal_interval
device,
n_rollout=2048 * 2,
num_inner_samples=int(5e5),
seed=-1,
):
""" T designs at equal intervals """
pyro.clear_param_store()
seed = auto_seed(seed)
... | 66,513 |
def normalise_operator_input(*args):
"""Input to Operator may contain products of epsilons which are sympy TensMul
objects. This causes problems since I don't want to define products of
epsilons or deltas to be operators.
This function normalises the input to the Operator constructor to avoid
probl... | 66,514 |
def make_button(
name: str = '',
parent: QObject|None = None,
slots: Sequence[Callable, ...] = (),
hint: str = ''
):
"""Make a simple, default Qt push button.\n
Slots will be connected to the `clicked` signal.
"""
if parent is not None:
btn = QPushButton(text=... | 66,515 |
def _fontValidator(font):
"""Check if font value is valid, regex is too slow.
Checks everything before ``,`` on basic font value. Everything after should
be a valid font-family value.
"""
if u',' in font:
# split off until 1st family
font1, families2 = font.split(u',', 1)
... | 66,516 |
async def edit_event(ctx, client):
"""
Function:
edit_event
Description:
A existing event is edited from the user's schedule file
Input:
ctx: the current context
client: the instance of the bot
Output:
- A reply saying whether the event was updated or not
... | 66,517 |
def plot_country(country, yvals, y2vals):
"""Makes 3-panel plot from country data"""
# Log values
yvals_log = get_log(yvals)
y2vals_log = get_log(y2vals)
# Per-day change
yvals_perday = get_change_per_day(yvals)
y2vals_perday = get_change_per_day(y2vals)
fig = make_subplots(
r... | 66,518 |
def get_accountinfo(msg: dict) -> str:
"""
Returns a dictionary containing the
account id and an array of prowler group checks.
"""
if msg == "":
raise IndexError
else:
try:
account_id = msg['Id']
return account_id
except KeyError as err:
... | 66,519 |
def export_to_csv(db_engine: sqlalchemy.engine.Engine, table_or_view: str, output_file: t.Union[Path, str], schema: str = 'public') -> None:
"""Export table/view to a csv file"""
output_file = Path(output_file).resolve()
con: pg2ext.connection = db_engine.raw_connection()
cur: pg2ext.cursor = con.cursor... | 66,520 |
def create_observable_df() -> pd.DataFrame:
"""Create empty observable dataframe
Returns:
Created DataFrame
"""
df = pd.DataFrame(data={col: [] for col in OBSERVABLE_DF_COLS})
return df | 66,521 |
def MST(N_mels,sequence_samples,audio_win,audio_hop):
""" Return SMel as a keras model
Parameters
----------
N_mels : int
Number of mel bands
sequence_samples : int
Number of samples in each input
audio_win : int
Number of samples in each frame
audio_hop : int
... | 66,522 |
def maximum_gap_in_days(col: pd.Series) -> int:
"""Compute maximum gap in a series of dates
(2020-01-01 - 2020-01-02 -> gap = 0 days)
:param col: pd.Series of dates
:return: greatest gap
"""
return col.sort_values().diff().max().days - 1 | 66,523 |
def get_resource_endpoint(host, hpc_backend):
"""
Get ssh URI of remote host
:param host: host to make url for it
:param hpc_backend: hpc_backend integer value according to HPCBackend enum
:return:
"""
# Default SAGA adaptor to ssh
adaptor = 'ssh'
if helpers.is_localhost(host):
... | 66,524 |
def wrap_function(lib, funcname, restype, argtypes):
"""Simplify wrapping ctypes functions"""
func = lib.__getattr__(funcname)
func.restype = restype
func.argtypes = argtypes
return func | 66,525 |
def test_lsinitrd_broken():
"""
For this testcase, ls_parser.parse() will throw an IndexError.
Assert with this specific error here.
"""
with pytest.raises(Exception) as err:
lsinitrd.Lsinitrd(context_wrap(LSINITRD_BROKEN))
assert "list index out of range" in str(err) | 66,526 |
def get(
policy_class=None,
return_full_policy_names=True,
hierarchical_return=False,
adml_language="en-US",
return_not_configured=False,
):
"""
Get a policy value
Args:
policy_class (str):
Some policies are both user and computer, by default all policies
... | 66,527 |
def add_graph_nodes(data_graph, root_city, wikicities, root_city_attributes):
"""
add_graph_nodes adds nodes to a graph and returns the new graph
@param data_graph: the current graph
@param root_city: the root city
@param wikicities: all catched cities
@param root_city_attributes: attributes of ... | 66,528 |
def create_index(genome_fasta, nameOUT):
"""
creates HISAT index for target genome
aligns synthetic rRNA reads
"""
SYN_rRNA_FASTA = '../../../data/18SrRNA/pipeline_mapping/fastq_files/reads_total.fastq'
# extract species prefix
prefix = genome_fasta.split("/")[-1].split(".")[0]
#... | 66,529 |
def dump_cter_v1_0(file_name: str, cter_data: pd.DataFrame) -> None:
"""
Create a cter v1.0 partres file based on the cter_data information.
Arguments:
file_name - Path to the output partres file.
cter_data - Pandas data frame containing ctf information.
Returns:
None
"""
cter_head... | 66,530 |
def add_suffix(img_file,suffix):
"""
add suffix for a given file name, and not change the file type
:param img_file: img file, e.g. "xxx.jpg"
:param suffix: "——abcde"
:return: "xxx——abcde.jpg"
"""
name = os.path.splitext(img_file)[0]
type_ = os.path.splitext(img_file)[1]
file_name =... | 66,531 |
def pairwise_distances_euclidean(points):
"""Return the matrix of pairwise euclidean distances between points.
Parameters
----------
points: 2d numpy.array
The coordinates of the point, points[0, :] and points[1, :] corresponding to x's and y's respectively.
Returns
-------
... | 66,532 |
def check_dtype(h5_dset):
"""
Checks the datatype of the input HDF5 dataset and provides the appropriate
function calls to convert it to a float
Parameters
----------
h5_dset : :class:`h5py.Dataset`
Dataset of interest
Returns
-------
func : callable
function that w... | 66,533 |
def stdev_fuel_per_hour(iterable):
"""
>>> round(stdev_fuel_per_hour(clean_data(row_merge(log_rows))), 4)
0.0897
"""
return stdev(row.fuel_per_hour for row in iterable) | 66,534 |
def stratified_mean_squared_error(observed, predicted, idx, verbose=False):
"""
Computes the stratified mean squared error (MSE) values. Stratified MSE is computed separately in each
bin (cluster) of an observed dependent variable, :math:`\\phi_o`.
MSE in the :math:`j^{th}` bin can be computed as:
... | 66,535 |
def write_file_diff(file_obj, qml_version, file_url, outputs, diff_indices):
"""Write the outputs produced by a demonstration from the QML repository to
a file.
Args:
file_obj (object): the file object used to write the diffs found when
checking a specific version of the demonstration
... | 66,536 |
def retrieve(*, sodar_url, sodar_api_token, project_uuid):
"""Retrieve project information."""
while sodar_url.endswith("/"):
sodar_url = sodar_url[:-1]
url_tpl = "%(sodar_url)s/project/api/retrieve/%(project_uuid)s"
url = url_tpl % {"sodar_url": sodar_url, "project_uuid": project_uuid}
log... | 66,537 |
def modify_ldap_config():
"""
修改ldap模块信息
:return:
"""
try:
put_data = request.get_json(force=True)
ldap_host = put_data.get("ldap_host")
bind_dn = put_data.get("ldap_bind_dn")
bind_dn_password = put_data.get("ldap_bind_dn_password")
base_dn = put_data.get("l... | 66,538 |
def gallows(wrong_times):
"""
This function is to make the gallows, which is based on the times of wrong guess.
:param wrong_times: N_TURNS - left_turns
:return: The previous 6 steps is to hang man,
if N_TURNS > 7, the 7th to the (N_TURNS -1)th look of gallows would be the same as 'g6'.
... | 66,539 |
def extract_data_files(path: pathlib.Path, data_dir: pathlib.Path, file_list_file: pathlib.Path) -> None:
"""Choose extractor based on filetype and extract the data files.
:param path: Path to the dataset to extract.
:param data_dir: Path to the data dir to extract the data file to.
:param file_list_fi... | 66,540 |
def create_sorted_poly_list(poly2d_vector:_Poly2DVector):
"""
Create a SortedPolyList from the values provided in metadata classes of base type _Poly2DVector
:param poly2d_vector:
:return sorted_poly_list:
"""
return SortedPolyList(list_generic_poly=[_create_generic_poly(p) for p in poly2d_vect... | 66,541 |
def rgb_to_hls(arr):
""" fast rgb_to_hls using numpy array """
# adapted from Arnar Flatberg
# http://www.mail-archive.com/numpy-discussion@scipy.org/msg06147.html
arr = arr.astype("float32") / 255.0
out = np.empty_like(arr)
arr_max = arr.max(-1)
delta = arr.ptp(-1)
arr_min = arr.min(... | 66,542 |
def shp2geojsonOgr(layer):
"""Shapefile to Geojson conversion using ogr."""
cmd = 'ogr2ogr -f GeoJSON -t_srs'\
+ ' crs:84'\
+ ' {layer}.geojson'\
+ ' {layer}.shp'
cmd = cmd.format(layer=layer)
return cmd | 66,543 |
def gluon_seresnext101_32x4d(pretrained=False, num_classes=1000, in_chans=3, **kwargs):
"""Constructs a SEResNeXt-101-32x4d model.
"""
default_cfg = default_cfgs['gluon_seresnext101_32x4d']
model = ResNet(
Bottleneck, [3, 4, 23, 3], cardinality=32, base_width=4, use_se=True,
num_classes=... | 66,544 |
def lut_canonical_potential_edge(potential_edge):
"""Returns a canonical name of a potential edge, with respect to LUT height.
Parameters
----------
potential_edge : str
Instantiated name of the potential edge to be canonicized.
Returns
-------
str
A canonical potential edg... | 66,545 |
def _delete_dhcp_relays_v1(port_name, vrf_name="default", **kwargs):
"""
Perform a DELETE call to delete all the IPv4 DHCP helper(s) for an L3 interface.
:param port_name: Alphanumeric name of the Port
:param vrf_name: Alphanumeric name of the VRF
:param kwargs:
keyword s: requests.session ... | 66,546 |
def safe_std(data):
"""Remove zero std values for ones."""
std = np.std(data, axis=0)
return np.array([val if val != 0.0 else 1.0 for val in std]) | 66,547 |
def purge_cache(cache_path):
"""
Remove cache is present
"""
if os.path.exists(cache_path):
os.remove(cache_path) | 66,548 |
async def test_white_value_template(hass, expected_white_value, start_ha):
"""Test the template for the white value."""
state = hass.states.get("light.test_template_light")
assert state is not None
assert state.attributes.get("white_value") == expected_white_value | 66,549 |
def country_list_nlp(cts):
"""NLP countries so we can use for vector comparisons"""
ct_nlp = []
for i in cts.keys():
nlped = nlp(i)
ct_nlp.append(nlped)
return ct_nlp | 66,550 |
def is_unique_column(df_column: pd.Series) -> bool:
"""Check if a column has unique non-empty values.
:param df_column: Column of a pandas data frame
:return: Boolean encoding if the column has unique values
"""
return len(df_column.dropna().unique()) == len(df_column) | 66,551 |
def profile_edit(request, username, edit_profile_form=EditProfileForm,
template_name='userena/profile_form.html', success_url=None,
extra_context=None, **kwargs):
"""
Edit profile.
Edits a profile selected by the supplied username. First checks
permissions if the user ... | 66,552 |
def minimal_medium(
models: CommunityModelDirectory, min_growth: float = 0.1, threads: int = 1
) -> pd.DataFrame:
"""Calculate the minimal medium for a set of community models."""
manifest = models.manifest.view(pd.DataFrame)
model_folder = str(models.model_files.path_maker(model_id="blub")).replace(
... | 66,553 |
def task_select_roi_lesion():
"""Select lesion ROIs from the pmap DICOMs."""
for mode, sl in product(MODES, SAMPLELISTS):
for c, s, l in lesions(mode, sl):
yield get_task_select_roi_lesion(mode, c, s, l) | 66,554 |
def ais_singleiter(
y_pred, y_test, prob_pos, sample_budget, g, alpha, known_rows, filter_rows
):
"""Perform a single AIS iteration of calibration + sampling.
Args:
y_pred: model predictions (k,)
y_test: ground-truth labels for sampled rows (samples,)
prob_pos: model scores (k,)
... | 66,555 |
def write_image_binary(fname,image,verbose=0):
"""Write a binary image to disk. This verifies first that the given image
is, in fact, binary. The image may be of any type, but must consist of only
two values."""
if verbose: print("# writing", fname)
assert image.ndim==2
image = array(255*(image... | 66,556 |
def request_user_has_rule_trigger_permission(request, trigger):
"""
Check that the currently logged-in has necessary permissions on the trigger used / referenced
inside the rule.
"""
if not cfg.CONF.rbac.enable:
return True
user_db = get_user_db_from_request(request=request)
rules_r... | 66,557 |
def dict_update(d, u):
"""Update dict d based on u recursively."""
for k, v in u.items():
if isinstance(v, collections.Mapping):
d[k] = dict_update(d.get(k, {}), v)
else:
d[k] = v
return d | 66,558 |
def soft_break(value, length, process=lambda chunk: chunk):
"""
Encourages soft breaking of text values above a maximum length by adding
zero-width spaces after common delimeters, as well as soft-hyphenating long
identifiers.
"""
delimiters = re.compile(r'([{}]+)'.format(''.join(map(re.escape, '... | 66,559 |
def flip(function):
"""
Returns a function which behaves like `function` but gets the given
positional arguments reversed; keyword arguments are passed through.
>>> from brownie.functional import flip
>>> def f(a, b): return a
>>> f(1, 2)
1
>>> flip(f)(1, 2)
2
"""
@wraps(fun... | 66,560 |
def org_has_prescribing(org_type, org_id):
"""
Return whether this org has any prescribing data associated with it
"""
row_grouper = get_row_grouper(org_type)
return org_id in row_grouper.offsets | 66,561 |
def get_or_create_experiment(experiment_name: str) -> mlflow.entities.Experiment:
"""
Returns an existing MLflow experiment if it exists, otherwise it creates a new one.
Args:
experiment_name (str): The name or ID of the experiment.
Returns:
mlflow.experiment: The found or created expe... | 66,562 |
def main():
"""
"""
# arg parsing
desc = ""
parser = argparse.ArgumentParser(description=desc)
parser.add_argument("-l", "--loci", required=True,
nargs=3, metavar=("chr", "begin", "end"),
help="comma-delimited loci [required]")
parser.add_argum... | 66,563 |
def data_generator(metric):
"""
finding gamma for NNC and generating files to train and test data sets
:param metric: string of metric name
:return: X_train: vector with size of n_train of binary vectors with size of example_size
X_test: vector with size of n_test of binary vectors with siz... | 66,564 |
def _main_by_id (cmd) :
"""Print all characters in `id_to_chr_map` sorted by id."""
sk = (lambda x : x [1]) if cmd.sort_by_code else None
for line in UCD.by_id (sk) :
print (line) | 66,565 |
async def name_handler(client: Client, message: Message):
"""
Change my profile name, this command is flexible and has an auto-balancer for long names.
"""
args = message.text.split()[1:]
if not args:
await message.edit_text('Pass your new name.\n`.name I\'m a superman!`')
else:
... | 66,566 |
def cal_total_variation_loss_v1(logits, gts=None, reduction="mean"):
"""
:param preds: (N,C,H,W) logits predicted by the model.
:param gts: useless arg.
:param reduction: specifies how all element-level loss is handled.
:return: total_variation_loss
"""
probs = logits.simgoid()
h, w = pr... | 66,567 |
def encode_boolean(value):
"""
Returns 1 or 0 if the value is True or False.
None gets interpreted as False.
Otherwise, the original value is returned.
"""
if value is True:
return 1
if value is False or value is None:
return 0
return value | 66,568 |
def is_gauss_sum_separable(n,k):
"""
Returns true if gauss sum is separble for dirichlet characters mod k calculated for positive integer n
Parameters
----------
n : int
denotes positive integer for which dirichlet characters are calculated
k : int
denotes positive intger mod
... | 66,569 |
def get_session():
"""
Returns:
the trident _SESSION
"""
return _SESSION | 66,570 |
def clip_by_global_norm(max_norm) -> GradientTransformation:
"""Clip updates using their global norm.
References:
[Pascanu et al, 2012](https://arxiv.org/abs/1211.5063)
Args:
max_norm: the maximum global norm for an update.
Returns:
An (init_fn, update_fn) tuple.
"""
def init_fn(_):
retu... | 66,571 |
def random_file_url(company):
"""
Generate a random image url string.
Parameters:
company: str
The company name for the hostname.
Return:
str
A generated url for an image on the company's host.
"""
url = "-".join(company.split())
return f"https://{ur... | 66,572 |
def validate_sami_id(candidate_sami_id):
"""Dummy validation function for SAMI IDs, always returns true."""
return True | 66,573 |
def get_binary_column_prob(dataset):
"""Returns a probability tuples for binary class = True and binary class = False
for the binary column in the dataset"""
binary_column = dataset.columns_that_are('binary')[0]
a_count = 0
not_a_count = 0
for attr_value, class_value in zip(binary_column, da... | 66,574 |
async def some_iter_func(number):
""" emits 1 number per second """
for i in range(1, number):
yield i
await asyncio.sleep(1) | 66,575 |
def nearing_recursion_limit():
"""Return true if current stack depth is within 100 of maximum limit."""
return sys.getrecursionlimit() - _get_stack_depth() < 100 | 66,576 |
def get_workloads(month):
"""Calls the same method on the Month model."""
return month.get_workloads() | 66,577 |
def GetCrypter(secret):
"""Returns the Keyczar Crypter object returned by the secrets manager
instance GetCrypter method."""
return GetSecretsManagerForSecret(secret).GetCrypter(secret) | 66,578 |
def resample(image, target, mapping, shape, order=3):
"""
Resample an image to a target CoordinateMap with a "world-to-world" mapping
and spline interpolation of a given order.
Here, "world-to-world" refers to the fact that mapping should be
a callable that takes a physical coordinate in "target"
... | 66,579 |
def run_pyflakes(verbose, files=None):
"""
Runs pyflakes on a package or list of files
"""
config = load_configuration()
quality_info = ()
if files == None: # run on entire package
quality_info = pyflakes_file([config.package_name()], verbose=verbose)
else:
quality_info = py... | 66,580 |
def roster_details(member_id):
"""Get the roster details for a particular member
Decorators:
ROSTER
Arguments:
member_id {[number]} -- [Id that uniquely identies this member]
"""
_db = DB()
start_time = request.args.get("start_time")
end_time = request.args.get("end_time")
... | 66,581 |
def interpft(x, N):
"""Interpolates x to n points in Fourier Transform domain
"""
n = len(x)
assert n < N
a = jfft.fft(x)
nyqst = (n + 1) // 2
z = jnp.zeros(N -n)
a1 = a[:nyqst+1]
a2 = a[nyqst+1:]
b = jnp.concatenate((a1, z, a2))
if n % 2 == 0:
b = b.at[nyqst].set(b[n... | 66,582 |
def price_router(token_in, token_out=usdc, router=None):
"""
Calculate a price based on Uniswap Router quote for selling one `token_in`.
Always uses intermediate WETH pair.
"""
tokens = [interface.ERC20(token) for token in [token_in, token_out]]
router = interface.UniswapRouter(router or ROUTERS... | 66,583 |
def main():
"""
This program simulates a bouncing ball at (START_X, START_Y)
that has VX as x velocity and 0 as y velocity. Each bounce reduces
y velocity to REDUCE of itself.
"""
global ball
ball.filled = True
window.add(ball, x=START_X, y=START_Y)
onmouseclicked(start) | 66,584 |
def test_three_ips(one_event_bundle, tmpdir):
"""A single Observation SDO can contain any arbitrary number and type
of SCOs. In the case that one type appears multiple times,
firepit will attempt to mark one as the "primary", or most
significant, instance by setting an "x_root" attribute to 1 (note
... | 66,585 |
def create_esax_time_series(ts_subs, w, per):
"""
This method creates the eSAX representation for each subsequence and puts them row wise into a dataframe.
:param ts_subs: a list of np arrays with the subsequences of the time series
:type ts_subs: list of np arrays
:param w: word size used for the ... | 66,586 |
def regex_for_progress():
""" T0:210 /210 B:0 /0 """
return '([0-9].*)\/([0-9].*?)\\r' | 66,587 |
def update_ld_api(project: str, environment: str, feature: str, state: str):
"""
Execute command against the LaunchDarkly API.
This command is generally not used directly, instead it is called as a
part of running the ``playback()`` function.
:param project: LaunchDarkly project key.
:param en... | 66,588 |
def _scrape_article_list(d, e, sites, api_fields, filename, lang="en"):
"""Scrape pages from list of different pages
Reads a list of pages from text file and scrapes the pages. Works in priciple the same as _scrape_category(..),
only creates a mock category based on the file of the text file and adds all p... | 66,589 |
def check_penn_treebank_dataset(method):
"""A wrapper that wraps a parameter checker around the original Dataset(PennTreebankDataset)."""
@wraps(method)
def new_method(self, *args, **kwargs):
_, param_dict = parse_user_args(method, *args, **kwargs)
nreq_param_int = ['num_samples', 'num_par... | 66,590 |
def _get_all_topic_subscription(topicid):
"""Gets all of the users subscribed to the topic subscription if you are an admin."""
current_user = get_jwt_identity()
if current_user:
user = User.query.filter_by(username=current_user).first()
if user.is_staff:
topic_sub = Topic_Subscr... | 66,591 |
def shuffle_files_in_list_from_categories(paths_list, categories, metadata_path, type='youtube8m', seed=5):
"""
generates a list of randomly shuffled paths of the files contained in the provided directories which match at least one
of the given categories from the 'categories' list. metadata (json file) must be p... | 66,592 |
def lambda_handler(event, context):
"""
Route the incoming request based on intent.
The JSON body of the request is provided in the event slot.
"""
# By default, treat the user request as coming from the America/New_York time zone.
os.environ['TZ'] = 'America/New_York'
time.tzset()
... | 66,593 |
def get_phase(signal,
sample_rate,
frame_length=32,
frame_shift=8,
window_type="hanning",
preemphasis=0.0,
square_root_window=True):
"""Compute phase imformation.
Args:
signal: input speech signal
sample_rate: w... | 66,594 |
def crossGeneRandom(genea, geneb):
"""
A crossover startegy where parts of two genes are randomly swapped.
12347 => 14341
54321 52327
Parameters
----------
genea : 1D numpy array
An 1D numpy array/list of genes.
geneb : 1D numpy array
An 1D nu... | 66,595 |
def predict(summaries, row) -> tuple:
"""
Predict the most likely class from inputs:
summaries: prepared summaries of dataset
row: a row in the dataset for predicting its label (a row of X_test)
This function uses the probabilities calculated from each class via the function 'calculate_class_proba... | 66,596 |
def find_antenna_overlay_for_sector(points_to_cover, center, radius, detection_coverage):
"""
Find the overlay pattern for antennas so they cover a sector.
"""
def find_cover(rotated_antenna_pattern,points_to_cover):
""" Find the subset of points covered by a rotated_antenna_pattern from a set o... | 66,597 |
def disable_tls_for(template, port):
"""
Change a deployment template to disable TLS communications.
@param template: deployment template
@param port: listening port for Cloudera Manager with TLS disabled
@rtype: DeploymentTemplate
@return: updated deployment template
"""
if not templat... | 66,598 |
def get_staffline(y_position, extracted_staff_arr):
"""Gets the staffline of the extracted staff.
Args:
y_position: The staffline position--the relative number of notes from the
3rd line on the staff.
extracted_staff_arr: An extracted staff NumPy array, e.g.
`StafflineExtractor.extract_stav... | 66,599 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.