content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def countingOp(i, m, Npair):
"""
Calculates the application of the counting operator to a basis state m. Returns 0 or 1, according to the occupation of the energy level.
"""
m1 = flipBit(m, Npair-i-1)
if m1 < m:
return 1
else:
return 0 | 68,200 |
async def cmd_showme_module(message : discord.Message, args : str, isDM : bool):
"""Return the URL of the image bountybot uses to represent the specified inbuilt module
:param discord.Message message: the discord message calling the command
:param str args: string containing a module name
:para... | 68,201 |
def safestring_to_string(s):
"""Return the original string encoded by string_to_safestring"""
return _base64.b64decode(s.encode("utf-8")).decode("utf-8") | 68,202 |
def test_extrapolators(extrapolator_name: str, ic_method_name: str):
"""This tests runs the example experiment configuration once."""
# Set some important environment variables
os.environ["CHIA_CPU_ONLY"] = "1" # We need this for cloud testing
helpers.setup_environment()
# Read example configurat... | 68,203 |
def check_setup(mod_name):
"""Parses the required modules from a setup.py file and check they are
available in the PYTHONPATH"""
pass | 68,204 |
def apparent_spectrum_fit_function(wn, Z_ref, p, b, c, g):
"""
Function used to fit the apparent spectrum
:param wn: wavenumbers
:param Z_ref: reference spectrum
:param p: principal components of the extinction matrix
:param b: Reference's linear factor
:param c: Offset
:param g: Extinct... | 68,205 |
def write_to_file(data):
"""
Check for the output test.yaml file if it exists, else create one and write
to it.
"""
test_yaml_path = os.path.join(test_dir, "test.yaml")
try:
os.remove(test_yaml_path)
except FileNotFoundError:
logger.info("{} not found. Creating...".format(tes... | 68,206 |
def tempdir():
"""Creates a temporary directory"""
directory_path = tempfile.mkdtemp()
def clean_up(): # pylint: disable=missing-docstring
shutil.rmtree(directory_path, onerror=on_error)
with cd(directory_path, clean_up):
yield directory_path | 68,207 |
def normalization(vector):
"""
Normalize scores in this vector
"""
x = vector[vector>0]
print(x)
exit() | 68,208 |
def start_client(ip, port):
"""
:param ip:
:param port:
:return:
"""
with xmlrpc.client.ServerProxy("http://{}:{}".format(ip, port)) as proxy:
while True:
command = input("Function\n\tdel_contact(name)\n\tget_directory()\n\t"
"nb_telephone_number(... | 68,209 |
def active_matrix_from_intrinsic_euler_xyz(e):
"""Compute active rotation matrix from intrinsic xyz Cardan angles.
Parameters
----------
e : array-like, shape (3,)
Angles for rotation around x-, y'-, and z''-axes (intrinsic rotations)
Returns
-------
R : array-like, shape (3, 3)
... | 68,210 |
def test_post_handlers():
# language=rst
"""
Post handlers
-------------
In the simplest cases, like in a create form, you only have one post handler.
You can do this yourself in the classic Django way:
"""
# @test
request = req('post', foo='foo', **{'-submit': True})
form = F... | 68,211 |
def parse(raw):
"""
Parses the given dict into a Entry object. This assumes the data is
formatted according to version 1.0 (or equivalent) of the RNAcentral JSON
schema.
"""
def key(raw):
return gene(raw) or ""
context = Context(
database=raw["metaData"]["dataProvider"],
... | 68,212 |
def wrapper(f):
"""Internal wrapper, takes a function f, adds type checking and return handling.
"""
signature = inspect.signature(f)
@wraps(f)
def new_func(*args, **kwargs):
payload = request.json
new_args = []
new_kwargs = {}
try:
for name in signatu... | 68,213 |
def callbacks() -> dict:
"""
Return a dictionary of callbacks with asynchrony support.
:return: a collections.defaultdict that returns callbacks by name.
"""
return collections.defaultdict(MockCallable) | 68,214 |
def run_kmeans(x, args):
"""
Args:
x: data to be clustered
"""
results = {'im2cluster':[],'centroids':[],'density':[]}
for seed, num_cluster in enumerate(args.num_cluster):
print('performing kmeans clustering on ...',num_cluster)
# intialize faiss clustering pa... | 68,215 |
def test_search_multiple(run_in_tmpdir, dials_regression):
"""Perform a beam-centre search and check that the output is sane.
Do the following:
1. Run dials.search_beam_centre on two datablocks and two pickled
reflection tables, as output by dials.find_spots;
a) Check that the program exits corre... | 68,216 |
def gensym(name: str) -> str:
"""Generates a globally unique name, using the given one as a base"""
global GENSYM_COUNTER
uniq = f"{name}__{GENSYM_COUNTER}"
GENSYM_COUNTER += 1
return uniq | 68,217 |
def setup(bot: commands.Bot) -> None:
"""Starts admin cog."""
bot.add_cog(admin(bot)) | 68,218 |
def write_schedule(schedule):
"""Gets given schedule completed if not complete and calls SAVE_SCHEDULE API to write it.
1. Fill in given schedule to complete it - fill_incomplete_schedule(schedule)
2. Create target URL using environment variable SAVE_SCHEDULE_URL and authUid
3. Call sav... | 68,219 |
def do_host_cpu_list(cc, args):
"""List cpu cores."""
host = host_utils._find_host(cc, args.hostnameorid)
cpus = cc.cpu.list(host.uuid)
field_labels = ['uuid', 'log_core', 'processor', 'phy_core', 'thread',
'processor_model']
fields = ['uuid', 'cpu', 'numa_node', 'core', 'thre... | 68,220 |
def bfs_algorithm():
"""
How to design a BFS algorithm.
"""
ans = """
How does the breadth-first search work?
It essentially is as follows:
1. Begin with a queue that has only one element in it: the starting node.
2. Add the neighbors of that node to the queue.
1. If destination node is present in ... | 68,221 |
def save_images(images, meta_data, path, base_filename, raw_skip=0):
"""
:param raw_skip: Skips x writes for every one taken. np.isinf(raw_skip) will skip all and save nothing.
:param path: Path of the directory to save fits file to.
:param base_filename: Name for file.
:return: None
"""
if... | 68,222 |
def parse_args():
"""Set up and parse arguments"""
p = ArgumentParser()
p.add_argument('-t', '--train-file', default=stdin)
p.add_argument('-c', '--config', type=str,
help="Location of YAML config")
p.add_argument('-p', '--parameters', type=str,
help="Manually sp... | 68,223 |
def test_other_metric_observe_value(OtherMetric, other_metric_arg): # noqa: F811
"""Observe a histogram or summary value and make sure it is stored properly"""
_m = OtherMetric(other_metric_arg)
test_metric_string = f"test_{other_metric_arg}_observe_value"
m = _m(test_metric_string, test_metric_string)... | 68,224 |
def normal_empirical_cdf(
target_cdf: float = 0.5,
mean: float = 0.0,
sigma: float = 1.0,
samples: int = 1000000,
bins: int = 1000):
"""
computes the value x for target_cdf
"""
# --- argument checking
if target_cdf <= 0.0001 or target_cdf >= 0.9999:
ra... | 68,225 |
def get_openweather_data():
"""Gathers weather data and returns the required list."""
response = requests.get(API_URL).json()
weather_data = response['list']
# Add date info
for entry in weather_data:
entry['date'] = datetime.fromtimestamp(entry['dt']).date()
entry['datetime'] = dat... | 68,226 |
def find_break_edges(ptree):
""" Find edges which to remove from the graph for the original tree behind this ptree.
==> edges between adjac
"""
ret = set()
if len(ptree.insert_descendants) > 0:
lca = ptree.insert_descendants[0]
for lca_child in lca:
ret.add((lca.nodei... | 68,227 |
def _getMASTidentifier(ID, lkwargs):
""" return KIC/TIC/EPIC for given ID.
If input ID is not a KIC/TIC/EPIC identifier then the target is looked up
on MAST and the identifier is retried. If a mission is not specified the
set of observations with the most quarters/sectors etc. will be used.
... | 68,228 |
def test_catalog_by_id(http_service: Any) -> None:
"""Should return status code 200 and single catalog in a turtle body."""
url = f"{http_service}/catalogs/1"
resp = requests.get(url)
assert 200 == resp.status_code
assert 0 < len(resp.content)
assert "text/turtle; charset=utf-8" == resp.headers[... | 68,229 |
def generate_ui_list_data(item_type="parts", pack=None):
"""Generate a list of Blender UI friendly data of categories and parts.
When we retrieve presets we just want an item name.
For parts I am doing a trick where I am grouping sets of 3 parts in order
to make a grid in each UIList entry.
A... | 68,230 |
async def test_cli_request_internal_error(capsys: CaptureFixture) -> None:
"""
Test the CLI output when an internal error has occurred.
:param capsys: System-level capture fixture
"""
with aioresponses() as mocked:
prefix = '<h3 class="{}">'.format(CountdoomClient.SELECTOR[1:])
suff... | 68,231 |
def pad_image(image):
"""
Parameters
----------
image : ndarray
DESCRIPTION.
Returns
-------
TYPE
padded image and its information
"""
padded_image = image
pad_x1, pad_x2, pad_y1, pad_y2, pad_z1, pad_z2 = 0, 0, 0, 0, 0, 0
# Padding on X axes
if image.sh... | 68,232 |
def parse_calibration(filename):
""" read calibration file with given filename
Returns
-------
dict
Calibration matrices as 4x4 numpy arrays.
"""
calib = {}
calib_file = open(filename)
for line in calib_file:
key, content = line.strip().split(":")
values = [float(v) for v... | 68,233 |
def create_network_graph_and_refresh():
"""Makes a network graph and refreshes open_file_tab"""
network_graph_file.set(filedialog.asksaveasfilename(initialdir="/",
title="Select or Create file:"))
graph_network.make_utilization_graph_neat(model, netwo... | 68,234 |
def get_celsius(temperature_in_fahrenheit):
"""
Returns the temperature in Celsius of the given Fahrenheit temperature.
For example, this function returns XXX when given YYY.
Type hints:
:type temperature_in_fahrenheit: float
"""
return (temperature_in_fahrenheit - 32) * (5 / 9) | 68,235 |
def solve_f35d900a(x):
"""
Difficulty: High
The Problem: The input grid is a rectangular (list of lists) matrix with variable shape, with numbers ranging
from 0 to 9. (inclusive). Different colors of the color spectrum are represented by the integers.
The task is to ... | 68,236 |
def config_fixture(hass):
"""Define a config entry data fixture."""
return {
CONF_USERNAME: "user@email.com",
CONF_PASSWORD: "password",
} | 68,237 |
def erfc(x):
"""
Complimentary error function, with handling of Quantity objects
Only Dimensionless quantities can be handled
erfc(x) = 1 - erf(x)
"""
if isinstance(x, Quantity):
return scipy.special.erfc(x.to("").magnitude)
else:
return scipy.special.erfc(x) | 68,238 |
def call_responder(server, endpoint, payload=''):
"""
Call a responder
Keyword arguments:
server: server
endpoint: REST endpoint
psyload: POST payload
"""
url = CONFIG[server]['url'] + endpoint
try:
if payload:
headers = {"Content-type": "application/j... | 68,239 |
def save_settings(settings, stream=None):
"""
Сохраняет настройки в файл в ямл
Сохраняются только те настройки, которые отличаются от дефолтных.
:param settings:
:param file_path:
:return:
"""
# Образец с дефолтными значениями для сравнения
templ = Settings()
# Вырезаем только... | 68,240 |
def json_exporter(data, filepath, compress=True):
"""Export a file to JSON. Compressed with ``bz2`` is ``compress``.
Returns the filepath of the JSON file. Returned filepath is not necessarily ``filepath``, if ``compress`` is ``True``."""
if compress:
filepath += ".bz2"
with bz2.BZ2File(fil... | 68,241 |
def is_linear(x, y):
"""
Returns True if molecule is linear
(largest eigenvalue almost equivalent to second largest)
"""
x = x - np.mean(x, axis=0)
y = y - np.mean(y, axis=0)
L, Q = sorted_eigh(build_F(x, y))
if L[0]/L[1] < 1.01 and L[0]/L[1] > 0.0:
return True
else:
... | 68,242 |
def _realroots_quadratic(a1, a0):
"""gives the real roots of x**2 + a1 * x + a0 = 0"""
D = a1*a1 - 4*a0
if D < 0:
return []
SD = math.sqrt(D)
return [0.5 * (-a1 + SD), 0.5 * (-a1 - SD)] | 68,243 |
def add_users():
"""add users from csv file"""
df = pd.read_csv(r'D:\PythonProjects\Kwiatki.csv',sep=';')
#print(df.head())
#print(User.query.delete())
for i, row in df.iterrows():
user = User.query.filter_by(username=row.username).first()
if user is None:
print(f'User {r... | 68,244 |
def add_column(recarray, name, val, index=None):
#Stolen from Ska.Numpy
"""
Add a column ``name`` with value ``val`` to ``recarray`` and return a new
record array.
:param recarray: Input record array
:param name: Name of the new column
:param val: Value of the new column (np.array or list)
... | 68,245 |
def gunning_fog_index(n_words, n_polysyllable_words, n_sents):
"""https://en.wikipedia.org/wiki/Gunning_fog_index"""
return 0.4 * ((n_words / n_sents) + 100 * (n_polysyllable_words / n_words)) | 68,246 |
def makeGIF(FF_input, start_frame=0, end_frame =255, ff_dir = '.', deinterlace = True, print_name = True, optimize = True, Flat_frame = None, Flat_frame_scalar = None, dark_frame = None, gif_name_parse = None, repeat = True, fps = 25, minv = None, gamma = None, maxv = None, perfield = False, data_type=1):
""" Makes... | 68,247 |
def russell_rao(
x: BinaryFeatureVector, y: BinaryFeatureVector, mask: BinaryFeatureVector = None
) -> float:
"""Russel-Rao similarity
Russell, P. F., & Rao, T. R. (1940).
On habitat and association of species of anopheline larvae in south-eastern Madras.
Journal of the Malaria Institute of India, ... | 68,248 |
def test_sed_dep_new():
"""
This tests only the power_law version of the SDE.
It uses a landscape run to 5000 100y iterations, then having experienced
a 20-fold uplift acceleration for a further 30000 y. It tests the outcome
of the next 1000 y of erosion.
"""
mg = RasterModelGrid((25, 50), 2... | 68,249 |
def _generate_windows_body(hooks):
"""Generate Windows specific functions.
At the moment it implements load_impls_from_library, class destructor, and an utility function
to convert from utf8 to wide-strings so we can use the wide family of windows
functions that accept unicode.
"""
# generate d... | 68,250 |
def ereference2link(self: ecore.EReference):
"""${self.eContainer().name} -> ${self.eType.name}""" | 68,251 |
def delete_by_id(_id):
"""
Delete user by their id
"""
User.query.filter_by(id=_id).delete()
db.session.commit() | 68,252 |
def get_binary(img_gray):
"""
Get binary threshold filter of image.
"""
thresh = cv2.threshold(img_gray, 128, 255, cv2.THRESH_BINARY)[1]
thresh = thresh[:, :, np.newaxis]
return thresh | 68,253 |
def bt_rr(weights, bounds):
"""
LP-based OBBT using ReLU relaxation. The procedure is named RR in the paper.
Assuming that NN model has K-1 hidden layers with ReLU activation and 1 linear output layer
Variables are named as x_i_j, where i is the layer number, and j is the unit number (of layer i)
... | 68,254 |
def WhaorNet(name: str = "whaornet", driver: str = "bridge") -> ContextManager[Network]:
"""Context manager which yields a network to connect containers to.
Args:
name (str): Name of network.
driver (str): Type of network drivier.
Yields:
Network: A Docker network.
"""
whao... | 68,255 |
def energy(sig: _Array) -> _Array:
"""Total energy of time domain signal.
Args:
sig: Time domain signal.
Returns:
Energy along fist axis.
"""
if not _np.isfinite(sig).all():
raise ValueError('Input ``sig`` contains NaNs or infinite values.')
return _np.sum(_np.square(_... | 68,256 |
def _compute_expected_shocks(dense_key_to_choice_set_in_period, optim_paras):
"""Compute an array with the expected value of the shocks."""
n_wages = len(optim_paras["choices_w_wage"])
exp_shocks = np.zeros(len(optim_paras["choices"]))
var = np.diag(optim_paras["shocks_cholesky"].dot(optim_paras["shock... | 68,257 |
def a_star(graph, start, goal):
""" this thing does not work :( """
# pdb.set_trace()
logger.setLevel(logging.INFO)
queue = [ [start] ]
step = 0
logging.info("START: %s" % start)
logging.info("GOAL: %s" % goal)
def a_star_sort(path1, path2):
l1 = path_length(graph, path1)
... | 68,258 |
def _preprocessor_public(X_raw):
"""Data preprocessing function.
This function prepares the features of the data for training,
evaluation, and prediction.
Parameters
----------
X_raw : ndarray
An array, this is the raw data as downloaded
Returns
... | 68,259 |
def p_acls(p):
"""acls : aclable ACL"""
p[0] = p[1].acls() | 68,260 |
def alreadyHasEntry(oldClassString, og):
""" Return true if there is already an owl:Class with the old id"""
namespace = oldClassString.split(':')[0]
if namespace == 'http':
target = rdflib.URIRef(oldClassString)
print('OLD CLASS ID IS A URL', oldClassString)
else:
try:
... | 68,261 |
def loadTLE(tle_file, satlst=None):
""" load TLE from file """
with open(tle_file, 'r') as f:
satlist = []
for l1 in f:
l2 = f.readline()
l3 = f.readline()
norad_id = l2[2:8]
if satlst is not None:
if norad_id in satlst:
... | 68,262 |
def bake(schema_name: str, config: Optional[Dict[str, Any]] = None) -> str:
"""
Links the directive to the appropriate schema and returns the SDL related
to the directive.
:param schema_name: schema name to link with
:param config: configuration of the directive
:type schema_name: str
:type ... | 68,263 |
def main():
"""Main function"""
couch = couchdb.Server()
topics_db = couch['meneame_topic_db']
news_db = couch['meneame']
logging.info('Loading topic distribution...')
logging.info('Retrieving news from DB...')
news = {}
for post in news_db:
new = dict(news_db.get(post))
... | 68,264 |
def cents_to_ratio(c):
"""Cents to pitch ratio."""
return np.power(2, c/1200.0) | 68,265 |
def move_file(source, dest, overwrite=True, cmp_on_overwrite=True, preserve_if_not_move=False):
"""
Move file, creating a containing folder if necessary. Returns ``True`` if the operation was performed.
Args:
overwrite (bool): If ``True``, overwrite existing file (if the existing file isn't ove... | 68,266 |
def get_prev_frames(ind, path):
"""
for this index return the closest previous frame which is non none
:param ind: input index
:param path:
:return: frame and the count
"""
cur_ind = ind - 1
count = 1
while (path[cur_ind] is None and cur_ind >0):
count = count + 1
cur... | 68,267 |
def test_metric_get(test_flask_client):
"""Tests the GET method"""
with mock.patch("bluebird.api.resources.metrics.utils", wraps=utils) as utils_patch:
sim_proxy_mock = mock.Mock()
utils_patch.sim_proxy.return_value = sim_proxy_mock
# Test no providers available
sim_proxy_moc... | 68,268 |
async def create_remove_vote(res: Response, vote: VoteBaseModel) -> Dict[str, Any]:
"""create or remove a Vote from Vote table
Args:
vote (VoteBaseModel): vote to create or remove
Returns:
Dict[str, Any]: vote created
"""
response = {
"success": True,
"vote": {},
... | 68,269 |
def delete_file(app_id, file_name, mode):
# type: (int, str, bool) -> bool
""" Call to delete_file.
:param app_id: Application identifier.
:param file_name: File name reference.
:param mode: Delete mode.
:return: The deletion result.
"""
return _COMPSs.delete_file(app_id, file_name, mod... | 68,270 |
def update_consumer_view(request):
"""
Updates a consuemr on ``POST`` request and returns the consumer update form for ``GET`` request.
.. http:get:: /consumer/update
Gets the consumer update form whose primary key matches the query parameter ``pk``.
**Example request**:... | 68,271 |
def LastValueMinMaxQuantize(inputs,
min_var,
max_var,
bit_width,
is_training,
mode,
name_scope="LastValueMinMaxQuantize"):
"""Last value float scale q... | 68,272 |
def write_out(df, meta, filename="tbl_{dims}--{name}", out_dir=None, filetype="csv"):
""" Write a dataframe to disk
"""
meta = meta.copy()
meta["dims"] = ".".join(df.index.names)
complete_file = filename.format(**meta)
if out_dir:
complete_file = os.path.join(out_dir, complete_file)
... | 68,273 |
def wikitext103_local_cluster4k():
"""Routing attention on sequence length 4k."""
hparams = wikitext103_local4k()
hparams.local_num_heads = 8
hparams.sparsity_cluster_num_heads = 8
hparams.sparsity_cluster_attention_window = 512
hparams.sparsity_cluster_size = 8
hparams.share_qk = True
return hparams | 68,274 |
def log10(pred, depth):
""" Mean log10 Error (LOG10) """
return np.absolute(np.log10(pred) - np.log10(depth)).mean() | 68,275 |
def test_plan_built_on_method(hook):
"""
Test @sy.meth2plan and plan send / get / send
"""
hook.local_worker.is_client_worker = False
x11 = th.tensor([-1, 2.0]).tag("input_data")
x21 = th.tensor([-1, 2.0]).tag("input_data")
device_1 = sy.VirtualWorker(hook, id="device_1", data=(x11,))
... | 68,276 |
def get_proto_deserializer(proto_class):
"""
Return a proto deserializer that takes in a proto type to deserialize
the serialized msg stored in the RedisState proto
"""
def _deserialize_proto(serialized_rule):
proto_wrapper = RedisState()
proto_wrapper.ParseFromString(serialized_rule... | 68,277 |
def last_failed(url, job_type):
"""Return last failed job for a specified job type."""
# query
query = {
"query": {
"bool": {
"must": [
{
"terms": {
"status": [ "job-failed" ]
... | 68,278 |
def p2pkh_address_to_pubkey_hash(address):
"""
Takes a P2PKH address (starting with a 1, m or n symbol) and extracts its
HASH160 hash (used as a public key hash).
:see: https://en.bitcoin.it/wiki/List_of_address_prefixes
:param address: P2PKH public address
:returns: HASH160 hash of the ... | 68,279 |
def get_dashboard(dashboard_id: Optional[str] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetDashboardResult:
"""
Resource schema for AWS::IoTSiteWise::Dashboard
:param str dashboard_id: The ID of the dashboard.
"""
__args__ = dict()
__args__['dashboardId... | 68,280 |
def resize_intrinsics(intrinsics, target_size):
"""Transforms camera intrinsics when image is resized.
Args:
intrinsics: 1-d array containing w, h, fx, fy, x0, y0.
target_size: target size, a tuple of (height, width).
Returns:
A 1-d tensor containing the adjusted camera intrinsics.
"""
with tf.n... | 68,281 |
def insert_artifact_v2(request_body: RequestBody, settings: config.APISettings = Depends(get_settings)):
"""Insert a JSON file of dbt artifacts v1.
NOTE:
The base configuration is implemented in `config.py`.
We can pass concrete values to it with an `.env.xxx` file.
The fixed `.env.xxx`... | 68,282 |
def test_post_promo_coupon(admin_drf_client, promo_coupon_json):
""" Test that the correct model objects are created for a promo coupon """
data = promo_coupon_json
resp = admin_drf_client.post(reverse("coupon_api"), type="json", data=data)
assert resp.status_code == status.HTTP_200_OK
model_version... | 68,283 |
def fix_spaces_inside_quotes(text, quote='``'):
"""
>>> test = '''\
:meth:`update` accepte soit un autre objet dictionnaire ou un iterable de\
paires clé / valeur (comme tuples ou d'autres iterables de longueur deux).\
Si les arguments de mots clés sont spécifiés, le dictionnaire est alors mis\
... | 68,284 |
def toGoatLatin(S):
"""
:type S: str
:rtype: str
"""
count=1
sentences=S.split()
for i in range(len(sentences)):
if sentences[i][0].lower() in "aeiou":
sentences[i]+="ma"+count*"a"
else:
sentences[i]=sentences[i][1:]+sentences[i][0]+'ma'+count*"a"
count+=1
return " ".join(sentences) | 68,285 |
def __prepare_line(string, dir_source, replace_string):
"""
Prepare the line before it is being written into the content file
"""
if not replace_string == None:
string = string.replace(dir_source, replace_string)
return string | 68,286 |
def create_adjacency_matrix(graph):
"""
Creating a sparse adjacency matrix.
:param graph: NetworkX object.
:return A: Adjacency matrix.
"""
index_1 = [edge[0] for edge in graph.edges()] + [edge[1] for edge in graph.edges()]
index_2 = [edge[1] for edge in graph.edges()] + [edge[0] for edge in... | 68,287 |
def count_trainable_parameters():
"""Counts the number of trainable parameters in the current default graph."""
tot_count = 0
for v in tf.trainable_variables():
v_count = 1
for d in v.get_shape():
v_count *= d.value
tot_count += v_count
return tot_count | 68,288 |
def create_diagram(start_from=None, kind="default", in_notebook=True):
"""Visually create a diagram.
Parameters
----------
start_from : list, optional
Starting coordinates (list of (x, y) tuples). By default uses a triangle.
kind : str
Can be one of "default", "x-marked".
in_not... | 68,289 |
def create_synchronous_model(file, population_size):
""" Creates synchronous model of *population_size* agents to a *file* with probabilities p and q in [0,1].
For more information see the HSB19 paper.
Args:
file (string): filename with extension
population_size (int): agent quantity
M... | 68,290 |
def _unfreeze(*args):
""" unfreeze the network for parameter update"""
for module in args:
if module:
for p in module.parameters():
p.requires_grad = True | 68,291 |
def run_module():
"""Create the Safegraph indicator."""
params = read_params()
# Place to write output files.
export_dir = params["export_dir"]
# Location of input files.
raw_data_dir = params["raw_data_dir"]
# Number of cores to use in multiprocessing.
n_core = int(params["n_core"])
... | 68,292 |
def extractsignalpdata(signalp_file_name,main_dic,translator_dic,n_termin_dict):
"""
This function reads an abridged signalp file, parses the signalp data and
adds the information in the (?) column to the main class.
"""
for line in open(signalp_file_name,'r'):
#Filter out title and s... | 68,293 |
def mosaic_template(
endpoint: str, mapbox_access_token: str = "", mapbox_style="satellite"
) -> str:
"""Rio-viz viewer."""
return f"""<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8' />
<title>Cogeo-Mosaic Viewer</title>
<meta name='viewport' content='initial-scale=1,maxi... | 68,294 |
def add(click_context: click.Context, local: bool, remote: bool) -> None:
"""Add a package to the agent."""
ctx = cast(Context, click_context.obj)
enforce(
not (local and remote), "'local' and 'remote' options are mutually exclusive."
)
if not local and not remote:
try:
c... | 68,295 |
def check_versions_in_tox_correct(file: str = "tox.ini") -> None:
"""
Check the versions in tox are matching the ones in Pipfile.
:param file: the file to check.
:param dependencies: the deps in pipfile
:return: True if match
"""
dependencies = get_deps_in_pipfile()
with open(file, "r"... | 68,296 |
def remove_ttfa_table(tt) -> None:
"""Removes TTFA table from a fontTools.ttLib.TTFont object"""
try:
del tt["TTFA"]
except KeyError:
# do nothing if table is not present in the font
pass | 68,297 |
def write_smiles(molecule, default_element='*', start=None):
"""
Creates a SMILES string describing `molecule` according to the OpenSMILES
standard.
Parameters
----------
molecule : nx.Graph
The molecule for which a SMILES string should be generated.
default_element : str
Th... | 68,298 |
def lint_code(session):
"""
Run PyLint against the code. Set PYLINT_REPORT to a path to capture output.
"""
flags = ["--disable=I"]
if session.posargs:
paths = session.posargs
else:
paths = ["setup.py", "noxfile.py", "coveragectx/"]
_lint(session, ".pylintrc", flags, paths) | 68,299 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.