content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def create_batch(klass, size, **kwargs):
"""Create a factory for the given class, and create a batch of instances."""
return make_factory(klass, **kwargs).create_batch(size) | e87a8659067938e6a48a1d514eef410ede4bc9a7 | 60,000 |
def compute_x(g, h, p, e, n):
"""Compute intermediate x such as h=g^x in the group <g> (cf. Pohlig-Hellman algorithm)."""
mod = pow(p, e)
ghat = pow(g, pow(p, e-1), n)
ginv = gmpy2.invert(g, n)
x = 0
tmp = 1
for i in range(e):
exp_hhat = pow(p, e-1-i)
hhat = pow(h*tmp, exp_hh... | 5b74fd08e44fac1c7647e93763d106bd74f10fcc | 60,001 |
def fib_recursion(n):
"""
Assum n is an integer n > 0
"""
if n == 1:
return 0
if n == 2:
return 1
return fib_recursion(n-1) + fib_recursion(n-2) | 1a59e9df4f8ae0150234ab5401021b298493e1c9 | 60,002 |
def linearize(path, n_points=360):
"""Interpolate between all points on a path."""
points = []
for segment in path._segments:
if type(segment).__name__ == 'Line':
n_points = 0
linearized = linearize_segment(segment, n_points)
points.extend(linearized[:-1])
points.appe... | 0e664ea07bec07b911c3061598869e43b8052084 | 60,003 |
def del_records(bibcode_list):
"""
:param bibcode_list:
:return:
"""
try:
with current_app.session_scope() as session:
count = 0
for bibcode in bibcode_list:
count += session.query(DataLinks).filter(DataLinks.bibcode == bibcode).delete(synchronize_ses... | 54dbed2eeff2215276fb249121cb21b326f38551 | 60,004 |
import logging
def setup_logger(name, use_colors=True, verbose_count=0):
"""
初始化日志~
:param name: 日志名
:type name: str
:param use_colors:
:type use_colors: bool
:param verbose_count:
:type verbose_count: int
:return:
"""
fmt = '[%(levelname).8s %(asctime)s %(name)s:%(lineno)d... | d2a8a294b013ff862487637befc50cc89c87e826 | 60,005 |
import tarfile
def fetch_tgz(dataname, urlname, data_home=None):
"""Fetch zipped dataset.
Fetch a tgz file from a given url, unzips and stores it in a given
directory.
Parameters
----------
dataname: string
Dataset name.
urlname: string
Dataset url.
data_ho... | 9d81d8a246ecc372599cec2a170d1fdadec54913 | 60,006 |
from typing import Callable
def find_best_transform(
sorted_x: np.ndarray,
y: np.ndarray,
w: np.ndarray,
pct_to_clip: float = 0.005,
identity_bias: float = 1e-6) -> Callable[[np.ndarray], np.ndarray]:
"""Finds the best transformation to use for PWLCurve fitting.
Chooses between identity, log,... | 3e5d0af4c096cb92e2db8c8e4b12ae3cad7ebeaa | 60,007 |
import sys
def connect_db(ini: dict, db_name):
"""
Connects to a DB returning its instance or None in error case
"""
# Validate mqtt configuration parameters
if not config.verify_params(ini, 'couchdb',
['server', 'port', 'user', 'password',
'realti... | 358a1596c42e8d27d1340cecf0ced0e1861a6322 | 60,008 |
def convert_url_to_path(url: str) -> str:
"""
>>> convert_url_to_path('file:///var/tmp/libreoffice')
'/var/tmp/libreoffice'
"""
return pyuno.fileUrlToSystemPath(url) | 14235857901fe35e6fba77d6f5466c9fa095188a | 60,009 |
import os
def change_param_val(
filepath,
param_key,
param_val):
"""
Change the parameter value of an image filename in a filepath.
Parameters
==========
filepath : str
The image filepath.
param_key : str
The identifier of the parameter to change.
n... | 4006547da517f28f432eaa6ff4293b0240f01de5 | 60,010 |
def get_query_matching_table(df_base, df_query, class_column='category', n_closest_matches=5, df_true_label="true_class",
df_pred_label="pred_class_", df_query_label="category", df_query_id="id"):
"""
Yields a pandas dataframe in which each row contains the n_closest_matches as a result... | c702deefdb3f7330fb41055b51d3d3157cb236e6 | 60,011 |
def get_x():
"""
Get current X keyboard setting
CLI Example:
.. code-block:: bash
salt '*' keyboard.get_x
"""
cmd = "setxkbmap -query | grep layout"
out = __salt__["cmd.run"](cmd, python_shell=True).split(":")
return out[1].strip() | 6fe8299273de514ef628a823ae70daf832b25667 | 60,012 |
def _called_with_cfg(*args, **kwargs):
"""
Returns:
bool: whether the arguments contain CfgNode and should be considered
forwarded to from_config.
"""
if len(args) and isinstance(args[0], _CfgNode):
return True
if isinstance(kwargs.pop("cfg", None), _CfgNode):
re... | 7626750f99504828330921ecae3613d0d03d0fc9 | 60,013 |
def are_content_experiments_enabled(course):
"""
Returns True if content experiments have been enabled for the course.
"""
return (
'split_test' in ADVANCED_COMPONENT_TYPES and
'split_test' in course.advanced_modules
) | 04c0e13fd4456b3dda3b59c36568403ed448d42e | 60,014 |
def experiment_fn(output_dir):
"""Creates an experiment using cnn for MNIST dataset classification task."""
plx.datasets.mnist.prepare('../data/mnist')
config = './yaml_configs/conv_highway_mnist.yml'
# or
config = './json_configs/conv_highway_mnist.json'
experiment_config = plx.configs.Experim... | 1a4b811f37bc525da063bf96e496fd9117fa81b3 | 60,015 |
import scipy
def normalize_graph(graph,
normalized = True,
add_self_loops = True):
"""Normalized the graph's adjacency matrix in the scipy sparse matrix format.
Args:
graph: A scipy sparse adjacency matrix of the input graph.
normalized: If True, uses the norma... | 82ac6df91e2f2247cdc941e34a84aa5619de0c7c | 60,016 |
import sys
def discriminator_dnn(self, inputs, reuse=False):
"""Build DNN model. On first pass will make vars."""
units = 1024
hidden_layers = 3
activation_fn = tf.nn.relu
relu_stddev = np.sqrt(2 / units)
relu_itializer = tf.truncated_normal_initializer(mean=0.0, stddev=relu_stddev)
# If test of cv , B... | 049ecee99ccd89c5ef3c94c74e8bb431e92d2158 | 60,017 |
def create_block_static(page_type, node):
""" Create a static block
:param page_type: where this block will be rendered
:param node: what this block will contain
:return: the page layout element
"""
block, created = ContentBlock.objects.get_or_create(name='static-%s' % node.title, type='static',... | 40d02eaebf729216fa5d04af559cef5f2669f22b | 60,018 |
def constructObject(data):
"""Constructing an object"""
whitelist = ["message"]
if data[""] not in whitelist:
return None
try:
classBase = getattr(getattr(messagetypes, data[""]), data[""].title())
except (NameError, AttributeError):
logger.error("Don't know how to handle mes... | 9133df35fc700bf052fa05aa108524e24f83499c | 60,019 |
def sample_from_cylinder(xy, height_object=0.25, radius=0.1):
"""
Randomly sample a grasping position from a cylinder
:param xy: x,y coordinates of the base/center of the cylinder
:param height_object: height of the cylinder
:param radius: radius of the cylinder
:return:
"""
approach = 2... | b1c72a62cfba9b6a2ad9791b3efb48fb43e4320f | 60,020 |
def valid_replay(info, ping):
"""Make sure the replay isn't corrupt, and is worth looking at."""
if (info.HasField("error") or
info.base_build != ping.base_build or # different game version
info.game_duration_loops < 1000 or
len(info.player_info) != 2):
# Probably corrupt, or just not interes... | e8fb8834c024f888abea50f8cf0123769a99e706 | 60,021 |
import logging
import sys
def _GetClosureBaseFile(sources):
"""Given a set of sources, returns the one base.js file.
Note that if zero or two or more base.js files are found, an error message
will be written and the program will be exited.
Args:
sources: An iterable of _PathSource objects.
Returns:
... | 970ded0f2c13bab56211db6170918ad817b5eb18 | 60,022 |
def mod(x, y):
"""Compute value of one parameter modulo another, element-wise.
Args:
x (:mod:`~taichi.types.primitive_types`, :class:`~taichi.Matrix`): The first input.
y (:mod:`~taichi.types.primitive_types`, :class:`~taichi.Matrix`): The second input.
Returns:
the value of `x` mo... | 11c97773a5c8be5363f10e3740dee51a5c773d8f | 60,023 |
def view_tutorialvideoslist(request):
"""View function showing all the tutorial videos available available"""
tutorialvideos = TutorialVideo.objects.all()
context = {
"tutorialvideos": tutorialvideos,
}
return render(request=request, context=context, template_name="dashboard/tutorialvideol... | 6bf3cda5e62f2dd08e00515ee7a73aab7352b7b2 | 60,024 |
import scipy.optimize
from padertorch.utils import to_numpy
from pb_bss.permutation_alignment import _mapping_from_score_matrix
def pit_loss_from_loss_matrix(
pair_wise_loss_matrix,
*,
reduction='mean',
algorithm: ['optimal', 'greedy'] = 'optimal',
return_permutation=False,
):
... | f4f2353cfc31941c005ba6b194a97c2e4b88d21f | 60,025 |
def menu_config_network_enable(target):
"""
With the BIOS menu at the top level, enable the configuration option
*EDKII Menu > Platform Configuration > Network Configuration > EFI Network*
:param tcfl.tc.target_c target: target on which to operate (uses
the default console)
:returns: *Tru... | 1257868f2ecebb8b3abeb3bd5a7e7b05e60e8686 | 60,026 |
def series(request: HttpRequest, slug: str) -> JsonResponse:
"""
View that serves a single series as a JSON object.
:param request: The original request.
:param slug: The slug of the series.
:return: A JSON-formatted response with the series.
"""
try:
_series = Series.objects.get(s... | f299065f70d21241e0d56680457d31f201ebc67d | 60,027 |
import os
def version_info():
"""Return bzr version info as a dict."""
out = os.popen('bzr version-info')
pairs = (l.split(':',1) for l in out)
return dict(((k,v.strip()) for (k,v) in pairs)) | a43663ea12d9c3f260ddfcdb03dcb65dd1eec0df | 60,028 |
def create_choropleth(data, column, columns, key_on):
"""
Create Choropleth (see: https://python-visualization.github.io/folium/quickstart.html#Choropleth-maps)
for passed dataset.
Basically an overlay map displaying numerical values over geographic areas
"""
# potential quantiles to include
... | 82326c209d6aad6096ec88a290a870009321e64c | 60,029 |
import requests
def get_receipt_info(receipt_data):
"""
Get information about an Apple receipt by sending its base64 encoded
data.
Args:
receipt_data:
The base64 encoded receipt data that is sent to Apple to
verify.
Returns:
The receipt data returned by Ap... | bca6819bd9b506471792770a220cff672134e956 | 60,030 |
def _align_mem_hla(fastq_file, pair_file, ref_file, out_file, names, rg_info, data):
"""Perform bwa-mem alignment on supported read lengths with HLA alignments
"""
with postalign.tobam_cl(data, out_file, pair_file != "") as (tobam_cl, tx_out_file):
cmd = ("unset JAVA_HOME && "
"%s | %s" ... | 02faa832666c80472644c1315da586d1263df9c8 | 60,031 |
import operator
def process_music(music):
"""Process a music and return the processed music."""
# Raise ValueError if no track is found
if not music.tracks:
raise ValueError("No track is found.")
# Adjust resolution to 24 time steps per quarter note
music.adjust_resolution(24)
# Coll... | ec980dc4a008b904fa954d3e2d1ed3053ed1a741 | 60,032 |
def lpAddRestrictions2(problem: LpProblem, lhs, rhs, name, op='='):
"""
Add vector or matrix of restrictions to the problem
:param problem: instance of LpProblem
:param lhs: 1D array (left hand side)
:param rhs: 1D or 2D array (right hand side)
:param name: name of the restriction
:param... | 3f4a343800b1eb67b9fbd98c1703c46aab2c0a89 | 60,033 |
def get_batch(datasets, phase, reset):
"""Read batches from multiple datasets based on the training phase.
The test dataset is reset at the beginning of every test phase. The training
dataset is repeated infinitely and doesn't need a reset.
Args:
datasets: Dictionary of datasets with training phases as ... | 09715fe850f3bfd5172931c45149649339f72e5c | 60,034 |
def init_api():
"""Initializes the twitter api."""
#REMEMBER TO REMOVE THESE BEFORE PUBLISHING!
consumer_key = '9837qrKedgU22V9Xz9mHgw'
consumer_secret = 'vsGk8T1J9UZwPsBkfgcMRWXSmw44a4mW9MmCPWXVzyc'
access_token_key = '16007524-OyqJQMw2RHi8y1L8URIErrCKHfSYFZGdc5vImrZpf'
access_token_secret = 'Y... | a3d3ca7675e5f5e627d1da48ba5bb93c7a8147f0 | 60,035 |
from typing import List
import urllib
import json
def get_latest_versions(
repo: str, number: int = 5, check_assets: bool = False
) -> List[dict]:
"""Get latest versions from a repository releases"""
# build url
url = f"https://api.github.com/repos/{repo}/releases"
# download data
data = urlli... | 63dff91f06beee168755114961f86e6b735f55b3 | 60,036 |
def get_decoder_self_attention_bias(length):
"""
Calculate bias for decoder that maintains model's autoregressive property.
Creates a tensor that masks out locations that correspond to illegal
connections, so prediction at position i cannot draw information from future
positions.
:param length: length of se... | 9d0288b6682d4774b56e3403ce23d0e64c7dae03 | 60,037 |
def lie_smoother(PopFrenetPath, Model):
"""
LieSmoother
Smoothing by local averaging based on the geodesic distance in SO(p),
i.e. we compute local Karcher mean. It can use the information on the curvature and torsion defined in Model for a better estimation.
...
"""
if isinstance(PopFrenet... | bfc754287b910a4c8abf14c728dd1ebed13ca1ef | 60,038 |
def connect_sequential(graph: Graph):
"""
Connect sequential nodes to sequential graph.
Args:
graph (Graph) :
"""
#
# Get node keys
#
node_keys_input, node_keys_hidden, node_keys_output = split_node_keys(
graph.node_keys,
)
#
# Connect all input nodes to hi... | 293eb23fc2282597301d7e935e6cea3425379643 | 60,039 |
import logging
import re
from pathlib import Path
def _find_downloads(folder, downloads_file):
"""Find artifact links in downloads_file file.
The `downloads_file` should be created during the build procedure (on
Travis). If no `downloads_file` exists, return an empty list.
Each line in the `downloa... | ec2169694e9901e079d82502440d599a47377a31 | 60,040 |
def backward_energy(img):
"""
Simple gradient magnitude energy map.
"""
img = img.astype(np.float64)
kernel_x = np.array([
[1.0, 0.0, -1.0],
[2.0, 0.0, -2.0],
[1.0, 0.0, -1.0],
])
kernel_y = np.array([
[1.0, 2.0, 1.0],
[0.0, 0.0, 0.0],
... | 082d010ad3afd6fc6f27eee523745e071ddda48b | 60,041 |
import logging
import os
def is_obspy(filename, config=None):
"""Check to see if file is a format supported by Obspy (not KNET).
Note: Currently only SAC and Miniseed are supported.
Args:
filename (str):
Path to possible Obspy format.
config (dict):
Dictionary con... | 57b3cf7426055c3da67083d5032f88341ac70a2a | 60,042 |
import signal
import os
def fork_bomb():
"""
Fork bomb
"""
pids = 0
# Reset signal handler for SIGTERM
signal.signal(signal.SIGTERM, signal.SIG_DFL)
# Fork and create as many children as we can
while True:
try:
pid = os.fork()
except OSError:
bre... | 72292a816dc128cb6fad2258631a4118ef60e310 | 60,043 |
import numpy as np
import pandas as pd
from re import T
import typing
def bin_by_blocks(
data: T,
blocks: typing.Sequence[typing.SupportsInt],
block_index_name: typing.Optional[str] = 'block_number',
) -> T:
"""TODO: deprecate
- either:
- refactor using pd.cut() https://stackoverflow.com/a... | a002a2b86f0e248a477d22cc5b0e4dc1ae8dbb36 | 60,044 |
import requests
import logging
def create_or_update(cluster, token_name, token_fields, admin_mode, action, fields_from_args_only, output):
"""Creates (or updates) the given token on the given cluster"""
cluster_name = cluster['name']
cluster_url = cluster['url']
existing_token_data, existing_token_et... | fa3b2e9bd7f58a523475732fc716e1aebc8c5a2f | 60,045 |
def _parse_due_date(part):
"""
Parse a part of text as a date, in either DD/MM/YYYY or YYYY/MM/DD format.
"""
# Strict DMY
m = _DUE_DATE_DMY.match(part)
if m:
return reversed(m.groups())
# Partial (Y)MD
m = _DUE_DATE_YMD.match(part)
if m:
return m.groups() | 0e81a3df1949abaa9b1be100f0596ae2b71e5799 | 60,046 |
from typing import Tuple
from typing import Iterable
import types
from typing import Optional
import six
def _make_dataset_feature_stats_proto(
lifts: Tuple[_SlicedFeatureKey, Iterable[_LiftSeries]],
y_path: types.FeaturePath, y_boundaries: Optional[np.ndarray],
weighted_examples: bool, output_custom_stat... | b365dfafbc5e966fdae61bc15cb5e600852740fd | 60,047 |
def get_from_url(url):
""" Retrieve URL and return content """
try:
return urllib2.urlopen(url).read()
except:
return None | 3f0c883709856b7a292c846c5191f2c8aa2de4ae | 60,048 |
def plot_map_france(ax=None, scale='50m'):
"""
Creates a map for France using :epkg:`cartopy`.
@param ax existing axes or None to create ones
@param scale scale in (`10m`, `50m`, `110m`)
@return ax
.. plot::
from matplotlib import pyplot as plt... | 4716d3eadccf0507fd2ed95412774e6e18cfe7f3 | 60,049 |
def _shortcut(identity, residual, is_nin=False):
"""
合并单位分支和残差分支的shortcut
:param identity: shortcut的单位量分支
:param residual: shortcut的残差量分支
:param is_nin: 是否对单位量实施NIN操作
:return: 合并结果tensor
"""
identity_shape = keras.backend.int_shape(identity)
residual_shape = keras.backend.int_shape(r... | f84d63c1d90d4b048230ba6a5a0342b90c011967 | 60,050 |
import math
import collections
def histogram_dist_column_to_pds(df, column, global_xmin_xmax,
bar_width_fraction,
column_properties=None, plot_individual=False,
bin_width=1,
individual_p... | 6cd7ed3c56c9f6b0e80a06d65f8f938cd448c57f | 60,051 |
def create_stats_filename(subject_line, email_time, ext='.xls'):
"""
Create a .xls filename from iScore email subject line.
Returns None if filename already exists.
:param str subject_line: subject line from iScore email
:param str email_time: time string representing time in inbox
:param str ... | 74158b2f2e954b498330d5b3badbc4fa40722778 | 60,052 |
import os
def metadata_v1(config):
"""
API v1 metadata of the application.
Example::
GET /api/v1/metadata
:return: The application metadata.
"""
if bottle.request.method == 'OPTIONS':
# CORS
return {}
try:
last_update = None
try:
ts_f... | 018ea15feab76e0c9e5f7c8dfa64cb28fec7ffbf | 60,053 |
import typing
def histc(labels: np.ndarray,
bins: np.ndarray = None,
return_bins: bool = False) -> typing.Tuple[np.ndarray, np.ndarray]:
"""MATLAB `histc` equivalent."""
labels = np.array(labels, dtype=int)
if bins is None:
bins = np.unique(labels)
bins = np.array(bins, dty... | 323adfe88b69e875fe4157acc0a353153543a478 | 60,054 |
def repl_escapechar(s):
"""xmlの制御文字をエスケープする。
s: エスケープ処理を行う文字列。
"""
seq = (("&", "&"),
("<", "<"),
(">", ">"),
('"', """),
("'", "'"))
for old, new in seq:
s = s.replace(old, new)
return s | d4c8a13ba295e9f1ebee7627dc810d5626cff957 | 60,055 |
def _sharecard(slug):
"""
Flatfile sharecards, one per liveblog post.
"""
context = get_liveblog_context()
for post in context['posts']:
if slug == post['slug']:
post_context = post
post_context['PARENT_LIVEBLOG_URL'] = context['PARENT_LIVEBLOG_URL']
post_... | 3d5348c7aa53be6fa5339c287d13f17191e098cc | 60,056 |
def pl_detect(state_file):
"""
Assume there is a log.txt recording the audio packets receiving state
at the decoder.
Frame received marked as 1, and frame lost marked as 0.
And the log.txt was named after the audio file name.
"""
with open(state_file, encoding='utf-8') as f:
pl_state... | b87c2dc9d2a792d3b02685c65446ae653d28e2e5 | 60,057 |
def RDP_pureDP(params,alpha):
"""
This function generically converts pure DP to Renyi DP.
It implements Lemma 1.4 of Bun et al.'s CDP paper.
With an additional cap at eps.
:param params: pure DP parameter
:param alpha: The order of the Renyi Divergence
:return:Evaluation of the RDP's epsilo... | d2d6f50f5e213dfafded036b9780d60d33fbb53f | 60,058 |
import logging
def load_reactions(session, model_db_id, model, old_reaction_ids):
"""Load the reactions and stoichiometries into the model.
TODO if the reaction is already loaded, we need to check the stoichometry
has. If that doesn't match, then add a new reaction with an incremented ID
(e.g. ACALD_... | 533c78939663c55881e1ea49403b9eae0c9a704e | 60,059 |
def bins(*args, **kwargs):
"""Create binned data, i.e., a variable with elements that are bins.
The elements of the returned variable are "bins", defined as views into
`data`. The returned variable keeps and manages a copy of `data`
internally.
The variables `begin` and `end` must have the same di... | 0a0661017c617c696f88c9807fd38cac6ca854f8 | 60,060 |
def class_extension(f):
"""
Transform a function into a class extension. This is the same as a type
extension, however, it adds the function as a class method rather than
an instance method.
"""
return extension(f, class_method=True) | 7f0d922c0205c5f95fe6e4c8391b77947489aa45 | 60,061 |
def _from_soap(in_envelope_xml, xmlids=None, **kwargs):
"""Parses the xml string into the header and payload.
"""
ns_soap = kwargs.pop('ns', ns.soap11_env)
if xmlids:
resolve_hrefs(in_envelope_xml, xmlids)
if in_envelope_xml.tag != '{%s}Envelope' % ns_soap:
raise Fault('Client.Soap... | efa5a227cf9cabc6f8041aed610c5df4019bcdb8 | 60,062 |
from .algebra.onnx_operator_mixin import OnnxOperatorMixin
from .algebra.type_helper import guess_initial_types
def to_onnx(model, X=None, name=None, initial_types=None,
target_opset=None, options=None,
white_op=None, black_op=None, final_types=None,
dtype=None, naming=None, verbos... | 293281f10faa47db6cd22e16d933c4a3742bc13f | 60,063 |
from typing import Dict
from typing import Any
def get_aws_account_information(app_id: str, api_key: str) -> Dict[str, Any]:
"""Retrieve aws account information from PythonDeploy."""
typer.echo("Requesting aws account information")
return api_request(app_id, api_key, "aws_account") | ffc9e987d1a6aa8baf4fe24de5bcbdb54d52d12a | 60,064 |
def isUSBLOG(filename):
"""
Checks whether a file is ASCII USB-Logger format.
Supports temperture and humidity logger
Extend that code for CO logger as well
"""
try:
temp = open( filename, "r", newline='', encoding='utf-8', errors='ignore' ).readline()
except:
return False
... | 38023ab4caf7cecd18f0f03ca89399acf64a90d6 | 60,065 |
from typing import Union
def _dec(v: Union[LayerFieldsContainer, LayerField]) -> int:
"""parse the layer field as a decimal"""
assert not isinstance(v, LayerFieldsContainer) or len(v.fields) == 1
return int(v.get_default_value()) | 5cc7a08b3471710bc12c8fc44e5f0663e128f18b | 60,066 |
import os
def get_test_path(relative_path: str) -> str:
"""
Given a path relative to the "tests" directory, return an absolute path to that file.
"""
path_to_this_file = os.path.abspath(__file__)
this_file_dir = os.path.dirname(path_to_this_file)
return os.path.join(this_file_dir, relative_pat... | fcd368da022b32ad801a922210b3b5d957659a9e | 60,067 |
def blockmodel(G, partitions, **attrs):
"""
Analogous to networkx.blockmodel, but can deal with incomplete partitions,
and assigns ``attrs`` to nodes.
Parameters
----------
G: networkx.Graph
The graph to partition
parititions: collections.abc.Iterable[collections.abc.Iterable]
... | a6c102a0fda27cd9905c57d6d6b4ec4c89e6763e | 60,068 |
import os
import io
def load_dot_env_file(dot_env_path):
""" load .env file.
Args:
dot_env_path (str): .env file path
Returns:
dict: environment variables mapping
{
"UserName": "debugtalk",
"Password": "123456",
"PROJECT_KEY": ... | 882d72c73d78e788a2671e4d081bcd8efb45c422 | 60,069 |
def calculate_bitmap_size_parameters(s):
"""
This function will calculate the parameters to be used for bitmap allocation, if we know what is the size we need to allocate, height=1, cBitsPerPel=8
@param s: size of the bitmap we need
@return: (width, height, cBitsPerPel) tuple
"""
p = platform.platform()
if p == ... | 0fba2e7ab59975215274ce5ee7fddb5d43ae0cdf | 60,070 |
from ..simplify import simplify
def simplify_logic(expr, form=None, deep=True):
"""
This function simplifies a boolean function to its simplified version
in SOP or POS form. The return type is an Or or And object in Diofant.
Parameters
==========
expr : string or boolean expression
form ... | c0403bc79e44ba448a4019cec21fc24eef1c1550 | 60,071 |
def w_Create(net):
""" Creates random weight vector of NN and defines sets needed for
derivative calculation
Args:
net: neural network
Returns:
net: neural network
"""
M = net['M'] #number of layers
layers = net['layers'] #NN structure
delay = net['delay'] #time delays in Network Connections
inputs = ... | b03e02bf168348ee1ce2dd613502aae178707600 | 60,072 |
def parse_drawing_level(drawing_level: t.DrawingLevelArg) -> str:
"""Parse drawing level into legal ANSI drawing level Sequence."""
if isinstance(drawing_level, int):
try:
drawing_level = list(ColorDrawingLevel)[drawing_level]
except IndexError:
raise KeyError(
... | 48e9cb292c32e555f8c666be9c117fe73ded920c | 60,073 |
import typing
def require_plan(
valid_plan_ids: typing.Iterable[str],
subscription_retriever: typing.Callable[[Request], Subscription],
):
"""
Decorator to be used on view functions / methods that require a specific plan.
Will result in 403 if resource requested is not part of an organisation tha... | bdbe0c98182ee13d0f00b0d35a95e1214c315560 | 60,074 |
def translate(dna, table=CODON_TABLE):
"""Translates DNA (with gaps) into amino-acids"""
aa = []
assert len(dna) % 3 == 0, "dna sequence length is not a multiple of 3"
for i in xrange(0, len(dna), 3):
codon = dna[i:i+3].upper()
if "N" in codon:
aa.append("X") # unkown ... | f60c4d319714ecaecbae5eed24e27606dfa0d139 | 60,075 |
import pprint
import json
def geolookup(spatial_dataset_id, spatial_id=None): # noqa: E501
"""Translate a spatial identifier into a description of space
# noqa: E501
k
:param spatial_dataset_id: dataset from which to look up spatial identifier
:type spatial_dataset_id: str
:param spatial_id: sp... | 82775287b3de43df1e93c3e2f141cac0539744ac | 60,076 |
def apply_method(state, step):
"""Apply a method to the state. Here data is a dictionary containing
all necessary information.
"""
method = get_method(step['method_name'])
goal_id = ItemID(step['goal_id'])
fact_ids = [ItemID(fact_id) for fact_id in step['fact_ids']] \
if 'fact_ids' in s... | a4770075c9cfca952e58f294ec24f1f2f3bcdfa7 | 60,077 |
def train_deep_sentiment(checkpoints_dir, train_dir, num_steps, model_name=None):
"""Fine tune the inception model, retraining the last layer.
Parameters:
dataset_dir: The directory containing the data.
checkpoints_dir: The directory contained the pre-trained model.
train_dir: The directory to save the trained... | 5fdac7293e14b940a775a3366b5e8727021a31ef | 60,078 |
def schedule_depthwise_conv2d_nhwc(outs):
"""Schedule for depthwise_conv2d_nhwc
Parameters
----------
outs: Array of Tensor
The computation graph description of depthwise_conv2d_nhwc
in the format of an array of tensors.
Returns
-------
sch: Schedule
The computat... | f9cebf7481cd2185875e987e79e5b8737a8eb66d | 60,079 |
def run_from_graph_def(
graph_def,
input_name,
output_name,
input_tensor,
dtype,
batch_size=None,
parallel_iterations=None,
):
"""Runs the GraphDef with `input_tensor` mapped to `input_name` and returns
the tensor matching `output_name`.
Args:
graph_def: A GraphDef proto... | ccd3612a5cd55a4dd3d5c265a37457f5643bf54f | 60,080 |
import sys
import os
def findExecutable(filename):
""" Searches for the named .exe or .dll file along the system PATH
and returns its full path if found, or None if not found. """
if sys.platform == "win32":
for p in os.defpath.split(";") + os.environ["PATH"].split(";"):
if os.path.is... | 0ea4256dd3aa499c9034f72e579c4320d2dafa70 | 60,081 |
def get_text(root_node, tag_name):
"""
get the text from a node's children
"""
values = []
nodes = root_node.getElementsByTagName(tag_name)
while len(nodes):
node = nodes.pop(0)
if node.nodeType == node.TEXT_NODE:
values.append(node.data.strip())
elif node.has... | dc8a3d88d01308ca6df81a493742549c1298bec0 | 60,082 |
import torch
import tqdm
def eval_net(net, loader, device):
"""Evaluation without the densecrf with the dice coefficient"""
net.eval()
mask_type = torch.float32 if net.n_classes == 1 else torch.long
n_val = len(loader) # the number of batch
tot = 0
tot_precision = 0
tot_recall = 0
cou... | 0bc47c6d27a07782730560f081a87ec4156535dd | 60,083 |
def get_model_dirs(data_topdirs):
"""
Args:
datadirs (list): top-level list of directories to search for model
directories
Returns (list): list of directories containing saved_models dir,
file train_history.json, and possibly file test.json
"""
all_subdirs = []
for d... | f7a4bd160de763980c0097052e0c25cc490bb7f0 | 60,084 |
def build_vgg16_unet(input_shape):
""" Input """
inputs = Input(input_shape)
""" Pre-trained VGG16 Model """
vgg16 = VGG16(include_top=False, weights="imagenet", input_tensor=inputs)
""" Encoder """
s1 = vgg16.get_layer("block1_conv2").output ## (512 x 512)
s2 = vgg16.get_layer("bl... | 616772894b9638c94551c9756d9c68aa0643307e | 60,085 |
import os
def _check_file_content(test_object, *file_path):
"""
Check content of the generated files.
Depending on the file extension, this tries to load the content of the file.
It returns the parsed content, depending on the extension.
"""
actual_file_path = _path_prefix_output_result(*file_... | 20cca6b6bce993ecf5ab9a35123b483498ae2fdd | 60,086 |
import os
import csv
def geonames_data():
"""Returns the file contents of the geonames dataset."""
file_contents = []
file_name = os.path.join("resources","geonames_countries.tsv")
with open(file_name, 'r') as fin:
csvreader = csv.reader(fin, delimiter="\t")
for line in csvreader:
... | fd70428f46e44b539c2d08731540cec5877fe6bd | 60,087 |
def check_set_object_type(type_str_list, **kwargs):
"""
Check if each string in type_str_list are corresponding to an actual object's name/alias, create
[objects] ordered lists for:
[[Function],[Data],[State],[Transition],[FunctionalElement],[Attribute],
[FuncitonalInterface],[PhysicalElement],[Phys... | 5c79a96a7fef1c84f6be30ac18518a1abfa10acb | 60,088 |
import time
def slow_down(func):
"""Sleep 1 second before calling the function"""
@wraps(func)
def wrapper_slow_down(*args, **kwargs):
time.sleep(1)
return func(*args, **kwargs)
return wrapper_slow_down | 089e68dd223440f67dd2a09b939759d9f0f10a28 | 60,089 |
import hmac
import hashlib
def calc_sig(payload, key=SECRET_KEY):
"""Calculate the signature of the payload."""
return 'sha1=' + hmac.new(key, payload, hashlib.sha1).hexdigest() | df85f87398597dc9b8141d03cf216ac4f2c5337a | 60,090 |
def load_nearest_neighbour_data(filename):
""" Read a nearest neighbour dataset of the format
ID, Word
:param filename: path to the csv file
:returns: df with the above columns
"""
column_list = ['ID', 'Word']
data = pd.read_csv(filename, header=[0])
cols = sorted(list(... | 3c3f20c9b36b74787bfd0a4a917eb296e2f7df6d | 60,091 |
import os
import gc
def write_par_and_pro(par_template, pro_template, basename,
seed, rpkms, sample):
""" Writes PAR and PRO file for a given sample.
par_template: PAR template file
pro_template: PRO template file
basename: Destination PAR/PRO basename
seed: ... | b4923058f2f1cf35d616033b85b3887ab3f97f1d | 60,092 |
def connect(args):
"""
:param args:
:return:
:rtype pymongo.collection.Collection
"""
conn = MongoClient(host=args.host, port=args.port)
return conn.get_database(args.database).get_collection(args.collection) | 1e01974db7951b2501e15213755a070e737781d8 | 60,093 |
def phased_check(fam, v, gt_bases):
"""
take cases where only 1 parent is HET
"""
gt_type = fam['gt_type']
# need at least 1 het kid
if 0 == ((gt_type[2] == 1) + (gt_type[3] == 1)):
return 0
used = 0
for parent, (p1, p2) in [("dad", (0, 1)), ("mom", (1, 0))]:
if gt_type[... | 256f62b8fa0a648dc6f66a2a652594a4d4d69c3d | 60,094 |
def load_latest_eog_model():
"""
Load latest EOG model from disk.
:return latest EOG model
"""
return _load_latest_model(EOG_MODEL_DIR) | d10545cb96a9c7f9ca90dedfa3b13da0e8ef34e5 | 60,095 |
import ast
import math
def formatHints(s, edit, hintLevel, tree):
"""Format the hints for human consumption"""
hint = Hint(level=hintLevel)
if len(edit) == 0:
hint.message = "No hints could be generated."
hint.save()
return hint
if hintLevel == "next_step" or hintLevel == "half_steps":
hint.message = ""... | 5bbfaf3c922c6e86f237718e455580eb2a89e223 | 60,096 |
import requests
import json
def graphql_multipart_request(body, headers, endpoint=GQL_DEFAULT_ENDPOINT):
"""Execute a multipart graphQL query with `body` provided on the `endpoint`.
Parameters
----------
body : str
payloads of graphQL query.
headers : dict, optional
headers added ... | a4e4311b916c2ca954e144f9a6a39f2af21dcf49 | 60,097 |
import os
import sys
def extract_brain_region(segmentation, levelset_boundary,
maximum_membership, maximum_label,
extracted_region, atlas_file=None,
normalize_probabilities=False,
estimate_tissue_densities=False,
... | 0ca5505d3c843cd1b5e0c7b710aa9608b4bdb3ca | 60,098 |
def _now(request, registry, settings):
"""Get the current time as :term:`UTC`.
:py:func:`websauna.utils.time.now` function.
Example:
.. code-block: html+jinja
<footer class="footer">
<div class="container-fluid">
<p class="copyright pull-right">
© {{ now().ye... | d7dcce1b6eee0c8e8861773a5b3fc3c209a75d00 | 60,099 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.