content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def extract_metrics(postprocessors):
"""
Extract performance metrics from multiple runs.
:param postprocessors:
:param data_projection:
:return:
"""
n_runs = len(postprocessors[0])
n_estimators = len(postprocessors)
n_clusters = postprocessors[0][0].nclusters
x_vals = np.arange(... | 70,600 |
def load_notebook(filename):
"""load a notebook object from a filename"""
if not os.path.exists(filename) and not filename.endswith(".ipynb"):
filename = filename + ".ipynb"
with io.open(filename) as f:
return nbf.read(f, as_version=4) | 70,601 |
def concat_gdf(*args):
"""
Concatenates an arbitrary number of GeoDataFrames
"""
return geopandas.GeoDataFrame(pandas.concat([*args], ignore_index=True)) | 70,602 |
def UnregisterNamedPath(name):
"""Unregister a named path - ie, a named PythonPath entry.
"""
keyStr = BuildDefaultPythonKey() + "\\PythonPath\\" + name
try:
win32api.RegDeleteKey(GetRootKey(), keyStr)
except win32api.error, (code, fn, details):
import winerror
if code!=winerror.ERROR_FILE_NOT_FOUND:
rais... | 70,603 |
def save_images(src, name):
"""
保存图片到本地
:param src: 图片 src
:param name: 保存图片名
"""
try:
img = requests.get(src, headers=HEADERS)
with open(name + ".jpg", "ab") as f:
f.write(img.content)
print("{}.jpg save Successfully".format(name))
except:
pa... | 70,604 |
def match_stops_in_model(stops):
"""
Matches a list of bus stops with stops present in the model.
The bus_station_ids provides a handling method for bus stations.
Input all the ATCO codes associated with bus station stops into the array
and ensure the Bus Terminal in Aimsun has the EID 'Bus Station'.
Parameters
... | 70,605 |
def sigma_at_error_rate_with_good_examples(
model, sess, x, y, desired_error_rate,
gaussian_samples_at_sigma_1, num_examples_wanted, distance_scale,
initial_guess=0.1, tol=0.001, sample_batch_size=10):
"""The scale at which Gaussian noise produces the provided error rate.
Args:
model: A `Model`; th... | 70,606 |
def get_all_matching_models(cars=cars, grep='trail'):
"""return a list of all models containing the case insensitive
'grep' string which defaults to 'trail' for this exercise,
sort the resulting sequence alphabetically"""
matches = []
for mfg, modellist in cars.items():
for model in mo... | 70,607 |
def psresp(t, y, dy, slopes, dt, df, percentile, oversampling=10, number_simulations=100):
"""
Compute power spectral density of a light curve assuming an unbroken power law with the PSRESP method.
The artificial light curves are generated using the algorithm by Timmer and Koenig (1995).
For an introdu... | 70,608 |
def _set_reuse_port(socket):
"""
Tells to the kernel to allow this endpoint to be bound to the same port as an other existing endpoint already
might be bound to.
Parameters
----------
socket : `socket.socket`.
The socket to set reuse to.
Raises
------
ValueError
... | 70,609 |
def gaussian_mixture(x: np.ndarray, params: np.ndarray
) -> np.ndarray: # pragma: no cover
"""
Mixture of gaussian curves.
Parameters
----------
x : np.array
params: np.ndarray
parameter for each curve the shape of the array is n_curves by
3. Eac... | 70,610 |
def get_parser() -> argparse.ArgumentParser:
"""Create and return the argparser for undiscord flask/cheroot server"""
parser = argparse.ArgumentParser(
description="Start the UnDiscord flask/cheroot server",
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
)
group = parser.add_ar... | 70,611 |
def text(body: t.Any, status: int = 200, content_type: str = 'text/plain', headers: Headers = None) -> Response:
"""
Response object that contains prepared plain text
:param body: dict object
:param status: http status
:param content_type: response content type (default text/plain)
:param header... | 70,612 |
def derive_cfda(obj, cfda_dict, job_id, detached_award_financial_assistance_id):
""" Deriving cfda title from cfda number using cfda program table.
Args:
obj: a dictionary containing the details we need to derive from and to
cfda_dict: a dictionary containing data for all CFDA objec... | 70,613 |
def test_import_multiple_raw_media_data_raises_media_import_error(mocker, lo):
"""Test that a meta data import does not raise errors if exceptions are raised
in MetaDataHandler, but the errors are returned as strings."""
mocker.patch(
"univention.bildungslogin.handlers.MetaDataHandler.create",
... | 70,614 |
def test_unicode_basics(webapp):
"""Test that Unicode domains work on all endpoints."""
unicode_domain = 'xn--sterreich-z7a.icom.museum'.decode('idna')
endpoints = ('fuzz', 'ip', 'parked', 'safebrowsing', 'whois')
for endpoint in endpoints:
webapp.get('/api/{}/{}'.format(
endpoint,
... | 70,615 |
def risk_estimate(est, gt, loss_func='zero-one-loss'):
""" est: cause x effect (indirect) boolean matrix"""
if loss_func == 'zero-one-loss':
return np.logical_xor(est.astype('bool'), gt.astype('bool')).sum()
else:
raise Exception('Specify correct loss function') | 70,616 |
def mf_session(mf_engine):
"""Define a default fixture in for the session, in case the user defines only `mf_engine`.
"""
Session = sessionmaker(mf_engine)
return Session() | 70,617 |
def mafiaAlgorithm(transactions, min_support_count):
""" Extract the MFIs (Maximal Frequent Itemsets) from transactions with min support count using MAFIA Algorithm
Parameters
----------
transactions : list of sets
The list of transactions
min_support_count : int
The minimum support count threshold
Returns... | 70,618 |
def train_test_apart_stratify(df, group, test_size=0.25, train_size=None,
stratify=None, force=False, random_state=None,
fLOG=None):
"""
This split is for a specific case where data is linked
in one way. Let's assume we have two ids as we have
... | 70,619 |
def get_ipsec_udp_key_status(
self,
) -> dict:
"""Get IPSEC UDP key status for all appliances
.. list-table::
:header-rows: 1
* - Swagger Section
- Method
- Endpoint
* - ikeless
- GET
- /ikeless/seedStatus
:return: Returns dictionary ike... | 70,620 |
def compute_loss_sparse(logits, indices, weights=None):
"""Cross-entropy loss when only 1 label per example."""
losses = tf.nn.sparse_softmax_cross_entropy_with_logits(
labels=indices, logits=logits)
if weights is not None:
row_sums = tf.squeeze(batch_gather(weights, tf.expand_dims(indices, 1)), 1)
... | 70,621 |
def test_atomic_unsigned_short_max_exclusive_2_nistxml_sv_iv_atomic_unsigned_short_max_exclusive_3_1(mode, save_output, output_format):
"""
Type atomic/unsignedShort is restricted by facet maxExclusive with
value 64347.
"""
assert_bindings(
schema="nistData/atomic/unsignedShort/Schema+Instan... | 70,622 |
def convert_poly(p, zoom, im_height):
"""Move a polygon to the correct zoom level and referential"""
polygon = affine_transform(p, [powdiv(1, zoom), 0, 0, powdiv(1, zoom), 0, 0])
return affine_transform(polygon, [1, 0, 0, -1, 0, im_height]) | 70,623 |
def sample_images(data_loader, generator, epoch, path):
"""Save Sample Images for Every Epoch"""
input, target = next(iter(data_loader))
input = input.to(device)
target = target.to(device)
generated = generator(input)
result = torch.cat((target, input, generated), dim=0)
save_im... | 70,624 |
def get_volume_from_pod(volume_name, namespace, experiment_id):
"""
Get volume content zipped on base64.
Parameters
----------
volume_name: str
namespace: str
experiment_id: str
Returns
-------
str
Volume content in base64.
"""
load_kube_config()
... | 70,625 |
def PyOS_double_to_string(space, val, format_code, precision, flags, ptype):
"""Convert a double val to a string using supplied
format_code, precision, and flags.
format_code must be one of 'e', 'E', 'f', 'F',
'g', 'G' or 'r'. For 'r', the supplied precision
must be 0 and is ignored. The 'r' form... | 70,626 |
def describe_services(
ecs, cluster: str, services: typing.Set[str]
) -> typing.List[typing.Dict[str, typing.Any]]:
"""Wrap `ECS.Client.describe_services` to allow more then 10 services in
one call.
"""
result: typing.List[typing.Dict[str, typing.Any]] = []
services_list = list(services)
fo... | 70,627 |
async def Custom(title:str, text:str) -> nextcord.Embed:
"""
Success Embed
-------------
Input: `Text`
Output: `nextcord.Embed` object
"""
# Start constructing the embed
embed = nextcord.Embed(
title = f"[ ■ ] {title}",
description = text,
color = nextco... | 70,628 |
def _get_article_nb_links_and_scores(url, links_dict=None, score_counter=None, base_score=1, current_deep=1, max_deep=1, top_n=10):
"""Function to accumulate article neighborhood scores recursively."""
article, _ = get_or_create_article_by_url(url)
# if article == None:
# return None, None
... | 70,629 |
def handle_deprecated_data_source(data_collection, data_source, default=None):
""" Joins parameters used to specify a data collection. In case data_source is given it raises a warning. In case
both are given it raises an error. In case neither are given but there is a default collection it raises another
wa... | 70,630 |
def extract_page_nr(some_string):
""" extracts the page number from a string like `Seite 21`
:param some_string: e.g. `Seite 21`
:type some_string: str
:return: The page number e.g. `21`
:rtype: str
"""
page_nr = re.findall(r'\d+', some_string)
if len(page_nr) > 0:
return "-".... | 70,631 |
def trec_8(data_dir="data/", keep_download=False,
overwrite_download=False, verbose=False, info_only=False):
""" Download the trec_8 dataset
more info: https://trec.nist.gov/data/topics_eng/"""
if info_only:
print(""" Download the trec_8 dataset
more info: https://trec.ni... | 70,632 |
def is_notification_center_valid(notification_center):
""" Given notification_center determine if it is valid or not.
Args:
notification_center: Instance of notification_center.NotificationCenter
Returns:
Boolean denoting instance is valid or not.
"""
return isinstance(notification_center, Notifica... | 70,633 |
def get_codec(module):
"""Creates and returns the codec defined in the given module path
(ex: ``"myapp.mypackage.mymodule"``). The argument can also be an alias to
a built-in codec, such as ``"json"``, ``"json_zlib"`` or ``"pickle"``.
"""
if module in CODECS:
# The "_codec" suffix is to avoi... | 70,634 |
def zeros(shape, dtype=hl.tfloat64):
"""Creates a hail :class:`.NDArrayNumericExpression` full of zeros.
Examples
--------
Create a 5 by 7 NDArray of type `tfloat64` zeros.
>>> hl._nd.zeros((5, 7))
It is possible to specify a type other than `tfloat64` with the `dtype` argumen... | 70,635 |
def get_expenses_by_year(session, user_id, year):
"""
Function to get expenses by year
:param session: current db session
:param user_id: user id
:param year: year
:return: returns list of expenses
"""
date_begin = datetime(year=year, month=1, day=1)
date_end = datetime(year=year + 1... | 70,636 |
def get_graph_tool_from_adjacency(adjacency, directed=None):
"""Get graph-tool graph from adjacency matrix."""
idx = np.nonzero(np.triu(adjacency.todense(),1))
weights = adjacency[idx]
if isinstance(weights, np.matrix):
weights = weights.A1
g = gt.Graph(directed=directed)
g.add_edge_list... | 70,637 |
def embed_batch(X, Y, mask):
"""Embed a square matrix x with y where mask is true.
Args:
x <list<np.array>>: set of to be embedded matrices
y <list<np.array>>: set of elements that are embedded into elements of X.
Same size as X.
mask <np.array<bool>>: marks where to embed.... | 70,638 |
def linux(request):
"""Start a linux session"""
yield from session_for(request) | 70,639 |
def test_workspace_creation():
"""
Test CLI init() is working properly.
"""
runner = CliRunner()
with runner.isolated_filesystem():
result = runner.invoke(init, [])
assert result.exit_code == 0
assert os.path.isdir("./feathr_user_workspace")
total_yaml_files = glob... | 70,640 |
def copy_sequencer_files():
"""
Run ccs_get_sequencer_paths.py script to get sequencer files. Copy
these files via scp to the current working directory.
"""
json_file = 'sequencer_paths.json'
my_ccs_script = os.path.join(os.environ['IANDTJOBSDIR'], 'harnessed_jobs',
... | 70,641 |
def ttgrange(*args, **kwargs):
"""
A shortcut for `tqdm.contrib.telegram.tqdm(xrange(*args), **kwargs)`.
On Python3+, `range` is used instead of `xrange`.
"""
return tqdm_telegram(_range(*args), **kwargs) | 70,642 |
def decode_lookup(key, dataset, description):
"""Convert a reference to a description to be used in data files"""
if key in dataset:
return dataset[key]
else:
decoded = input("Please enter {desc} for {key}: ".format(desc=description, key=key))
dataset[key] = decoded
return de... | 70,643 |
def comp_conv2d(conv2d, X):
"""
# 定义一个函数来计算卷积层,它初始化卷积层权重,并对输入和输出做相应的升维和降维
(主要是增删批量大小和通道数两个维度的信息)
"""
conv2d.initialize()
X = X.reshape((1, 1) + X.shape) # (1, 1)代表批量大小和通道数(“多输入通道和多输出通道”一节将介绍)均为1
Y = conv2d(X)
return Y.reshape(Y.shape[2:]) | 70,644 |
def get_axes():
"""It returns the value set for the option 'axes' of the plot."""
return h.axes | 70,645 |
def create_explicit_child_condition(parentage_tuple_list):
"""
This states for a parent node, what its explicit children are.
"""
def explicit_child_condition(G):
return all(
[sorted(G.out_edges(y[0])) == sorted([(y[0],x) for x in y[1]])
for y in parentage_tuple_list])... | 70,646 |
def similar_in_backness(backness_1: UnmarkableBackness) -> List[Backness]:
"""
If the value is a wildcard value, return
all possible backness values, otherwise
return the single corresponding backness value.
"""
if isinstance(backness_1, MarkedBackness):
return backness_1.backness
return backness_states | 70,647 |
def test_final_event(event_log, sample_log_lines):
"""Test getting the final event."""
insert_log_line = sample_log_lines.make_insert_log_line()
update_log_line = sample_log_lines.make_update_log_line()
event_log.add_event_log_line(insert_log_line)
event_log.add_event_log_line(update_log_line)
a... | 70,648 |
def ajax_delete_comment():
""" Deletes a comment from the recipe document """
response = {
"success" : False,
"flash" : {"message" : "Deletion Failed!", "category" : "error"},
"response" : None
}
if "comment" in request.json and "recipe" in request.json:
index = int(requ... | 70,649 |
def line_job():
"""
每条线路的计划分配情况
:return: "data": [
{
"choice_plan": "5e71dd0d3ae156497e114364",
"device_id": "7WIZya2wsIKGuitNpHyIWjCq",
"id": "5e6ee2ddc1094a4d94ed0264",
"limit": 100.0,
"line": 1,
"line_name": "线路一",
... | 70,650 |
def generate_random_GenericWindRoseVT():
"""
Generate a random GenericWindRoseVT object
Parameters
----------
N/A
Returns
-------
wind_rose GenericWindRoseVT
A wind rose variable tree
"""
weibull_array = np.array([[ 0.00000000e+00, 3.59673400e-02, 9.2242... | 70,651 |
def CMYK_to_CMY(CMYK):
"""
Converts from *CMYK* colourspace to *CMY* colourspace.
Parameters
----------
CMYK : array_like, (4,)
*CMYK* colourspace matrix.
Returns
-------
ndarray, (3,)
*CMY* matrix.
Notes
-----
- Input *CMYK* colourspace matrix is in doma... | 70,652 |
def hash_contents(self, instance: models.AnalysisFileset):
"""Store a unique hash of the file contents"""
# instance = models.AnalysisFileset.objects.get(pk=fileset_id)
sha256 = processors.get_file_sha256(os.path.join(settings.MEDIA_ROOT, instance.raw_gwas_file.name))
instance.file_sha256 = sha256
... | 70,653 |
def intDictToStringDict(dictionary):
"""
Converts dictionary keys into strings.
:param dictionary:
:return:
"""
result = {}
for k in dictionary:
result[str(k)] = dictionary[k]
return result | 70,654 |
def tree_insert(tree, z):
"""Inserts node 'z' into binary tree 'tree'."""
y = NIL
x = tree.root
while x != NIL:
y = x
if z.key < x.key:
x = x.left
else:
x = x.right
z.p = y
if y == NIL:
tree.root = z
elif z.key < y.key:
y.left =... | 70,655 |
def calculate_displacement(src_grammar, tgt_grammar):
"""Calculate displacement between 2 grammar. E.g: S -> A B C to S -> B C A has displacement of [1 2 0]"""
src_grammar_lst = src_grammar.split()
tgt_grammar_lst = tgt_grammar.split()
src_grammar_lst = src_grammar_lst[src_grammar_lst.index("->")+1... | 70,656 |
def create_confusion_matrix(actual, predicted, category):
"""
Calculates the confusion matrix for a give category.
:param actual: The actual labels of the data
:param predicted: The predicted labels of the data
:param category: The category we of the confusion matrix
:return: dictionary, with th... | 70,657 |
def moving_wall_bc(state,dim,t,qbc,auxbc,num_ghost):
"""Initial pulse generated at left boundary by prescribed motion"""
if dim.on_lower_boundary:
qbc[0,:num_ghost]=qbc[0,num_ghost]
t=state.t; t1=state.problem_data['t1']; tw1=state.problem_data['tw1']
amp_wall=state.problem_data['amp_wa... | 70,658 |
def GetUnionSelectorTypes(union_type):
"""Returns a list of all acceptable selector types for a given union."""
return _SELECTORS[union_type]['type'] | 70,659 |
def efficientnet_b6(
num_classes: int = 1000,
class_type: str = "single",
dropout: float = 0.5,
se_mod: bool = False,
) -> EfficientNet:
"""
EfficientNet B6 implementation; expected input shape is (B, 3, 528, 528)
:param num_classes: the number of classes to classify
:param class_type: ... | 70,660 |
def _save_lidar(file_list, output_file, location, keep_uuid):
"""Saves the Raman Lidar netcdf-file."""
anker = 0
file_data = {key: var for key, var in file_list[anker].data.items()}
file_data['time'].data = np.ma.concatenate([file_list[i].data['time'].data for i in range(len(file_list))])
# becaus... | 70,661 |
def load_test_config_file(test_config_path, tb_filters=None):
"""Processes the test configuration file provied by user.
Loads the configuration file into a json object, unpacks each testbed
config into its own json object, and validate the configuration in the
process.
Args:
test_config_pa... | 70,662 |
def colorWipeLumen(strip,wait_ms=60):
"""Wipe color across display a pixel at a time."""
start = 0
for y in range(0, 100, 1):
for i in range(strip.numPixels()):
if(i == strip.numPixels()):
color = Color(int(round(y)), int(round(y*0.564)), int(round(y*0.1896)))
... | 70,663 |
def spectrogram(signal, sampling_rate, window, step, plot=False,
show_progress=False):
"""
Short-term FFT mag for spectogram estimation:
Returns:
a np array (numOfShortTermWindows x num_fft)
ARGUMENTS:
signal: the input signal samples
sampling_rate: the s... | 70,664 |
def remove_spikes(data,threshold=None,window=12):
"""remove everything that deviates more than 500kPa from the median of a detrended 1-hour (12 points) window"""
# note that trends of 100kPa/hour are absolutely realistic
# so anything that departs by more than 500kPa from the trend should
# be pre... | 70,665 |
def SelectMultiple(
description: str = "",
description_tooltip: str = None,
disabled: bool = False,
index: Sequence[int] = (),
label: Sequence[str] = (),
layout: Union[Dict[str, Any], Element[ipywidgets.widgets.widget_layout.Layout]] = {},
options: Any = (),
rows: int = 5,
style: Uni... | 70,666 |
def expand_cigar(seq, cigar_ops):
"""Yield (ref_offset, seq_base) pairs."""
ref_offset = 0
seq_offset = 0
for count, op in cigar_ops:
if op in "MX=":
for (i, base) in enumerate(seq[seq_offset : seq_offset + count]):
yield ref_offset + i, base
ref_offset +=... | 70,667 |
def register_component(var, config):
"""Register the given obj as a component.
This is a coroutine, you must await it with a 'yield' expression!
:param var: The variable representing the component.
:param config: The configuration for the component.
"""
id_ = str(var.base)
if id_ not in CO... | 70,668 |
def test_predict_build(name):
"""Check that basic predict image builds successfully"""
code = baklava.predict(example(name), [])
assert code == 0 | 70,669 |
def test_subset_or_none_with_not_subset():
"""
Test resources.subset_or_none when the second directory is a
subset
"""
dict1 = { 1: 10, 2: 20, 3: 30 }
dict2 = { 1: 11, 4: 31 }
result = resources.subset_or_none(dict1, dict2)
assert isinstance(result, dict)
assert not result | 70,670 |
def clock(func):
"""
定义装饰器decorator,除了实现原函数功能外,额外提供计时功能
装饰器就是一个函数,它接收函数(原函数),返回函数(新函数)
:param func: 被装饰的函数
:return: 装饰后的函数
"""
def decorator():
t0 = time.perf_counter()
result = func()
elapsed = time.perf_counter() - t0
print("elapsed: {:.8f}s".forma... | 70,671 |
def print_avg_sentiment(df):
""" Prints the average sentiment per user
Parameters:
-----------
df : pandas dataframe
Dataframe with raw messages including a column called
'Sentiment' that has a value between -1 and 1
"""
# Prints the average sentiment per user
print_title... | 70,672 |
def all_acc(y_true, y_pred):
"""
All Accuracy
https://github.com/rasmusbergpalm/normalization/blob/master/train.py#L10
"""
return K.mean(
K.all(
K.equal(
K.max(y_true, axis=-1),
K.cast(K.argmax(y_pred, axis=-1), K.floatx())
),
... | 70,673 |
def main(**kwargs):
"""
Draw a couple of simple graphs and optionally generate an HTML file to upload them
"""
draw_lines()
draw_histogram()
draw_bar_chart()
destination = "-r /report"
if use_html:
generate_html()
command = "dx-build-report-html {h} {d}".format(h=html_fil... | 70,674 |
def walk(
top: str, topdown: bool = True, onerror: Optional[Callable[[OSError], None]] = None
) -> Iterator[Tuple[str, Sequence[str], Sequence[str]]]:
"""
Walk a directory tree in a similar manner to os.walk
"""
if not isdir(top):
return
if _is_local_path(top):
top = o... | 70,675 |
def main():
""" Scans for MAC addresses and/or keys. """
if len(sys.argv) == 1:
macs = scan(SCAN_SECONDS)
else:
macs = sys.argv[1:]
for mac in macs:
data = keyscan(mac)
if data is not None:
sys.stdout.write("%s = %02x\n" % (mac, data)) | 70,676 |
def _submit_cli(
input_file_path: Optional[str],
molecule_smiles: Optional[str],
force_field_path: Optional[str],
spec_name: Optional[str],
spec_file_name: Optional[str],
):
"""Submit a new bespoke optimization to a running executor."""
pretty.install()
console = rich.get_console()
... | 70,677 |
def generate_identifier(signingkey):
"""Generates encoded version of the public key associated with
signingkey.
Args:
signingkey (str): A private key.
Returns:
str: An encoded 'address' associated with the public key.
"""
return pybitcointools.pubtoaddr(pybitcointools.privtopub... | 70,678 |
def test_remove_edge():
"""
Test removing an edge from an NxGraph.
"""
g = get_graphs()[1]
g.remove_edge("B", "A")
assert not g.has_edge("B", "A") | 70,679 |
def get_args():
"""Get command-line arguments"""
parser = argparse.ArgumentParser(
description='Mad libs',
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('positional',
help='Input file',
metavar='FILE',
... | 70,680 |
def set_gid(gid: int) -> None:
"""Set the global group id. This is only used to set st_gid for new files,
no permision checks are performed.
Args:
gid: (int) the group ID of the user calling the file system functions.
"""
global GROUP_ID
GROUP_ID = gid | 70,681 |
def no_undos():
"""Inform the user that there are no moves to undo by printing
a message in the bottom left corner.
"""
no_undo_text = tk.Text(
root, bg="forest green", font=("Courier", 20), highlightthickness=0)
no_undo_text.place(x=50, y=700)
no_undo_text.insert("1.0", "There are no m... | 70,682 |
def get_page(paginated_list):
"""
Take a github.PaginatedList.PaginatedList and then iterate through the
pages to get all of its entries
Args:
paginated_list (github.PaginatedList.PaginatedList): PyGithub paginated
list object
Returns:
`list`: All entries in the paginated ... | 70,683 |
def acnt2(chain: pv.Chain, wallet: pv.Wallet) -> pv.Account:
"""
acnt2 is the fixture that returns the account of nonce 2.
Args:
chain (pv.Chain): The Chain object.
wallet (pv.Wallet): The wallet object.
Returns:
pv.Account: The account.
"""
return wallet.get_account(ch... | 70,684 |
def _get_acc_data():
""" Датасет для графика акселерометра """
time = now()
datax, datay, dataz = [_get_data_abstract("IMU", x, time) for x in ("xacc", "yacc", "zacc")]
for x, y, z in zip(datax, datay, dataz):
x["y"] /= 1000.0
y["y"] /= 1000.0
z["y"] /= 1000.0
lat... | 70,685 |
def run(plotIt=True):
"""
EM: TDEM: 1D: Inversion
=======================
Here we will create and run a TDEM 1D inversion.
"""
cs, ncx, ncz, npad = 5., 25, 15, 15
hx = [(cs,ncx), (cs,npad,1.3)]
hz = [(cs,npad,-1.3), (cs,ncz), (cs,npad,1.3)]
mesh = Mesh.CylMesh([hx,1,hz... | 70,686 |
def zip_encrypt_file(file_to_encrypt, password):
""" Zip compress file with password """
dst_file = file_to_encrypt + ".zip"
print("[+] Zip-Encrypting file: ", file_to_encrypt)
# Ignore deprecation warnings so we don't flood the console with garbage
# This is a known issue in pyminizip; see: https:... | 70,687 |
def git_ref(check=True):
"""
return name for current branch / tag
If `check` is True, the execution end if git root not found.
Otherwise `None` is returned.
"""
branch = _exec("git rev-parse --abbrev-ref HEAD".split(), check)
if branch != "HEAD":
return branch
tag_ref = _exec("g... | 70,688 |
def get_metadata_from_asset_name(asset_name: str) -> dict:
"""Get metadata for given asset"""
url = f"{POOL_PM_URL}/asset/{POLICY_ID}.{asset_name}"
response = get_request(url, headers=None)
return response.get("metadata") | 70,689 |
def save(upload_file, filename, email):
"""
Upload input file (photo) to specific path for individual user.
Save original file and thumbnail file.
:param upload_file: file object
:param filename: secure filename for upload
:param email: user email address
:param app: Flask.application
:r... | 70,690 |
def test_feature_fr_from_string():
"""
Language: FR -> Feature.from_string
"""
feature = Feature.from_string(OUTLINED_FEATURE, language="fr")
assert feature.name == "Faire plusieur choses en même temps"
assert feature.description == (
"De façon à automatiser les tests\n"
"En t... | 70,691 |
def run_gen_srcs(files):
"""
Runs test tools only for interesting files that were changed in this commit.
"""
if len(files) == 0:
return
success = 0 # exit code 0 = success, >0 error.
had_diffs = False
for tool_dict in TOOLS_GEN_SRCS:
tool_ran_at_least_once = False
for f in files:
if ... | 70,692 |
def prime(n):
"""Primality test by trial division."""
if n == 2:
return True
elif n < 2 or n % 2 == 0:
return False
else:
return not any(n % x == 0
for x in range(3, math.ceil(math.sqrt(n)) + 1, 2)) | 70,693 |
def rate_monadic_arg(max_rate_hz=30, monad_init="", monad_op=operator.concat):
"""TODO : description + doctest"""
def decorator(coro):
last_call = time.time()
last_arg = monad_init
last_handle = None
@functools.wraps(coro)
async def maxrate_monad_coro(arg):
n... | 70,694 |
def is_sukun(archar):
"""Checks for Arabic Sukun Mark.
@param archar: arabic unicode char
@type archar: unicode
@return:
@rtype:Boolean
"""
return archar == SUKUN | 70,695 |
def get_handler(update, context):
"""Get command handler
Commands:
/get - Get all subscriptions data
/get <subreddit> - Get selected subreddit data
Args:
update (telegram.Update): Object represents an incoming update.
context (telegram.ext.CallbackContext): Telegram bot con... | 70,696 |
def get_rev_ids_for_filters(filters):
"""
1. If filter_hash in rev_cache, then retrieve those revisions
2. If filter_hash not in rev_cache, retrieve 10K revs for filter and add them to the cache. Then, GOTO step 1.
3. Get user_data on revs, 100 at a time: have these revisions already been annotated?
... | 70,697 |
async def run(event, gh, config, **kwargs):
"""Run task."""
disabled = 'triage' in config.get('disabled_actions', [])
print(f'TRIAGE: {event.full_name} ({"disabled" if disabled else "enabled"})')
if disabled:
return
try:
if config.get('error', ''):
raise Exception(confi... | 70,698 |
def radio_util(
data # type: "XDR Data"
):
"""Radio Utilization Counter - Type: Counter, Enterprise: 0, Format: 1002"""
sample_data = {} # Cache
sample_data["Elapsed Time Milliseconds"] = int(data.unpack_uint())
sample_data["On Channel Time Milliseconds"] = int(data.unpack_uint())
sample_data["On Channel Busy Ti... | 70,699 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.