content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def interpret_go_point(s, size):
"""Convert a raw SGF Go Point, Move, or Stone value to coordinates.
s -- 8-bit string
size -- board size (int)
Returns a pair (row, col), or None for a pass.
Raises ValueError if the string is malformed or the coordinates are out of
range.
Only support... | 6b15b141e9fe5fc4195133f24925672522cdcb35 | 3,638,218 |
def get_domain_name_for(host_string):
"""
Replaces namespace:serviceName syntax with serviceName.namespace one,
appending default as namespace if None exists
"""
return ".".join(
reversed(
("%s%s" % (("" if ":" in host_string else "default:"), host_string)).split(
... | 6084e299f31d9c2eb922783d0488e9672051443f | 3,638,219 |
def bbox_classify(bboxes, possible_k):
"""bbox: x, y, w, h
return: best kmeans score anchor classes [(w1, h1), (w2, h2), ...]
"""
anchors = [bbox[2:4] for bbox in bboxes]
return anchors_classify(anchors, possible_k) | 5387c1441c94f4af0633b9cf73b0e5e53ce1bc9b | 3,638,220 |
def cleanFAAText(origText):
"""Take FAA text message and trim whitespace from end.
FAA text messages have all sorts of trailing whitespace
issues. We split the message into lines and remove all
right trailing whitespace. We then recombine them into
a uniform version with no trailing whitespace.
... | ea9882e24c60acaa35cae97f8e95acb48f5fd2a6 | 3,638,221 |
def LoadModel(gd_file, ckpt_file):
"""Load the model from GraphDef and Checkpoint.
Args: gd_file: GraphDef proto text file. ckpt_file: TensorFlow Checkpoint file.
Returns: TensorFlow session and tensors dict."""
with tf.Graph().as_default():
#class FastGFile: File I/O wrappers without thread loc... | 08089910da145141df8446c1aab9d697b15a3aa6 | 3,638,222 |
from bs4 import BeautifulSoup
import re
def get_additional_rent(offer_markup):
""" Searches for additional rental costs
:param offer_markup:
:type offer_markup: str
:return: Additional rent
:rtype: int
"""
html_parser = BeautifulSoup(offer_markup, "html.parser")
table = html_parser.fi... | 8836beda16e21fe214344d647de9260195afa6a7 | 3,638,223 |
def make_known_disease_variants_filter(sample_ids_list=None):
""" Function for retrieving known disease variants by presence in Clinvar and Cosmic."""
result = {
"$or":
[
{
"$and":
[
... | 288e5a0daa254016f9c1e1ee8e3106ea532008ec | 3,638,224 |
import multiprocessing
def sharedArray(dtype, dims):
"""Create a shared numpy array."""
mpArray = multiprocessing.Array(dtype, int(np.prod(dims)), lock=False)
return np.frombuffer(mpArray, dtype=dtype).reshape(dims) | e01b20f0f21386dd2ec8e1952547fbc9fc15cb65 | 3,638,225 |
def _read_hyperparameters(idx, hist):
"""Read hyperparameters as a dictionary from the specified history dataset."""
return hist.iloc[idx, 2:].to_dict() | b2a036a739ec3e45c61289655714d9b59b2f5490 | 3,638,226 |
def parse_time(date_time, time_zone):
"""Returns the seconds between now and the scheduled time."""
now = pendulum.now(time_zone)
update = pendulum.parse(date_time, tz=time_zone)
# If a time zone is not specified, it will be set to local.
# When passing only time information the date will default t... | 5ca2f5dad85e3492bd9909808990aaef0587343a | 3,638,229 |
def upper_bounds_max_ppr_target(adj, alpha, fragile, local_budget, target):
"""
Computes the upper bound for x_target for any teleport vector.
Parameters
----------
adj : sp.spmatrix, shape [n, n]
Sparse adjacency matrix.
alpha : float
(1-alpha) teleport[v] is the probability to... | 5bab951605ad5181e2fb696836219167dd78a30e | 3,638,231 |
def cramers_corrected_stat(contingency_table):
"""
Computes corrected Cramer's V statistic for categorial-categorial association
"""
try:
chi2 = chi2_contingency(contingency_table)[0]
except ValueError:
return np.NaN
n = contingency_table.sum().sum()
phi2 = chi2... | 89581fbcc306afdf34dac8cb30d3e7b316a47f48 | 3,638,233 |
def frame_comps_from_set(frame_set):
"""
A `set` of all component names every defined within any frame class in
this `TransformGraph`.
Broken out of the class so this can be called on a temporary frame set to
validate new additions to the transform graph before actually adding them.
"""
res... | 525ea19b78cb2a360165085720d42df58aa72500 | 3,638,234 |
def collection_tail(path_string):
"""Walk the path, return the tail collection"""
# pylint: disable=consider-using-enumerate
coll = None
parts = extract_path(path_string)
if parts:
try:
last_i = len(parts) - 1
coll = bpy.data.collections[parts[0]]
f... | 9a9d4e594c654b35f15870d33bc24314f1c48e5c | 3,638,236 |
from pyadlml.dataset.devices import most_prominent_categorical_values
def create_raw(df_dev, most_likely_values=None):
"""
return df:
| time | dev_1 | .... | dev_n |
--------------------------------
| ts1 | 1 | .... | 0 |
"""
df_dev = df_dev.copy()
df = ... | e6659e70bf91876a3cbfcc98aaa71e4e97837a7f | 3,638,237 |
def p1_marker_loc(p1_input, board_list, player1):
"""Take the location of the marker for Player 1."""
# verify if the input is not in range or in range but in a already taken spot
while p1_input not in range(1, 10) or (
p1_input in range(1, 10) and board_list[p1_input] != " "
):
try:
... | ea8cfd35e56d7e34efa7319667f1a655b597cf39 | 3,638,238 |
def chord(tones, dur, phrasing="", articulation="", ornamentation="", dynamics="", markup="", markdown="", prefix="", suffix=""):
""" Returns a list containing a single Point that prints as a chord with the specified tones and duration. """
tones = flatten([tonify(tones)])
return [Point(tones, dur, phrasing... | b6fc7ba5c7e8541eeea540a869b1697c15c5ea47 | 3,638,239 |
def build_gem_graph():
"""Builds a gem graph, F4,1.
Ref: http://mathworld.wolfram.com/GemGraph.html"""
graph = build_5_cycle_graph()
graph.new_edge(1, 3)
graph.new_edge(1, 4)
return graph | 4979ae5643ca44d6fb5eadd4fff18489fd3b5629 | 3,638,240 |
import select
async def get_forecasts_by_user_year_epic(
user_id, epic_id, year, month, session: Session = Depends(get_session)
):
"""Get forecast by user, epic, year, month"""
statement = (
select(Forecast.id, Forecast.month, Forecast.year, Forecast.days)
.where(Forecast.user_id == user_i... | 655863588ece0800d220386282d620d7296fc8a2 | 3,638,241 |
def face_xyz_to_uv(face, p):
"""(face, XYZ) to UV
see :cpp:func:`S2::FaceXYZtoUV`
"""
if face < 3:
if p[face] <= 0:
return False, 0, 0
else:
if p[face - 3] >= 0:
return False, 0, 0
u, v = valid_face_xyz_to_uv(face, p)
return True, u, v | 3483f918ed511c8fdf3c43e147c6cc605633754b | 3,638,242 |
import re
def cleanupString(string, replacewith="_", regex="([^A-Za-z0-9])"):
"""Remove all non-numeric or alphanumeric characters"""
# Please don't use the logging system here. The logging system
# needs this method, using the logging system here would
# introduce a circular dependency. Be careful no... | b327879a345a4236b871f824937997f6bd43d55b | 3,638,243 |
import socket
import json
def send_message(data, header_size=8):
"""Send data over socket."""
@_retry()
def _connect(socket_path):
"""Connect socket."""
sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
sock.connect(socket_path)
sock.settimeout(SOCKET_TIMEOUT)
... | bbe9c11e5b29ac2b0f0d2d9dd357f806a682156b | 3,638,244 |
from typing import Optional
from typing import Set
from typing import Literal
from typing import Any
def _get_mapping_keys_in_condition(
condition: Expression, column_name: str
) -> Optional[Set[str]]:
"""
Finds the top level conditions that include filter based on the arrayJoin.
This is meant to be u... | 7d890e4b68aeba9caca30e5a140214072c781a66 | 3,638,245 |
import requests
from bs4 import BeautifulSoup
def make_request(method, url, **kwargs):
"""Make HTTP request, raising an exception if it fails.
"""
request_func = getattr(requests, method)
response = request_func(url, **kwargs)
# raise an exception if request is not successful
if not response.s... | 1f47b178b66efe31fd78a4affc76a87d5be428bc | 3,638,246 |
def hold(source):
"""Place the active call on the source phone on hold"""
print("Holding call on {0}".format(source.Name))
return operation(source,'Hold') | 297cef77a3630bf3b9cab6256547ec43a5ba797c | 3,638,247 |
import math
def make_grid(batch, grid_height=None, zoom=1, old_buffer=None, border_size=1):
"""Creates a grid out an image batch.
Args:
batch: numpy array of shape [batch_size, height, width, n_channels]. The
data can either be float in [0, 1] or int in [0, 255]. If the data has
only 1 channel it... | 72bbcebd121b13bce31d760b9d8890966155b603 | 3,638,248 |
def _get_patterns_map(resolver, default_args=None):
"""
Cribbed from http://www.djangosnippets.org/snippets/1153/
Recursively generates a map of
(pattern name or path to view function) -> (view function, default args)
"""
patterns_map = {}
if default_args is None:
default_args = {... | 21f149773457b075ba984b028d2c44ac41f09a6a | 3,638,249 |
def encoder_package_to_options(encoder_package, post_url=None,
extra_numerics=None,
extra_categoricals=None,
omitted_fields=None):
"""
:param encoder_package: one hot encoder package
:param post_url: url to send for... | 1286aefef87b547d7a09db8fec3b50f7082e64f8 | 3,638,250 |
def get_subset_values(request, pk):
"""Return the numerical values of a subset as a formatted list."""
values = models.NumericalValue.objects.filter(
datapoint__subset__pk=pk).select_related(
'error').select_related('upperbound').order_by(
'qualifier', 'datapoint__pk')
to... | 1bc34a534a56a7f75742f455aad5575224ce976f | 3,638,251 |
import time
def timestamp(format_key: str) -> str:
"""
格式化时间
:Args:
- format_key: 转化格式方式, STR TYPE.
:Usage:
timestamp('format_day')
"""
format_time = {
'default':
{
'format_day': '%Y-%m-%d',
'format_now': '%Y-%m-%d-%H_%M_%S',
... | dab77afb630193d45fbc5b07c08fd82c3dfa3050 | 3,638,252 |
def _save_conn_form(
request: HttpRequest,
form: SQLConnectionForm,
template_name: str,
) -> JsonResponse:
"""Save the connection provided in the form.
:param request: HTTP request
:param form: form object with the collected information
:param template_name: To render the response
:r... | ee2639e1ab354b6ca722e35167bf6ab7cc57b351 | 3,638,253 |
def client() -> GivEnergyClient:
"""Supply a client with a mocked modbus client."""
# side_effects = [{1: 2, 3: 4}, {5: 6, 7: 8}, {9: 10, 11: 12}, {13: 14, 15: 16}, {17: 18, 19: 20}]
return GivEnergyClient(host='foo') | 9d419927ebcb5a39df27e92e3a378cd5448acf1e | 3,638,254 |
def test_bus(test_system):
"""Create the test system."""
test_system.run_load_flow()
return test_system.buses["bus3"] | fea4880446059171dae5d6fffc24bdc98eede5cd | 3,638,255 |
def mask_target(y_true, bbox_true, mask_true, mask_regress, proposal, assign = cls_assign, sampling_count = 256, positive_ratio = 0.25, mean = [0., 0., 0., 0.], std = [0.1, 0.1, 0.2, 0.2], method = "bilinear"):
"""
y_true = label #(padded_num_true, 1 or num_class)
bbox_true = [[x1, y1, x2, y2], ...] #(padde... | b161178716d890721a7f3cd0bfd61fdcc3efffb4 | 3,638,256 |
from rowgenerators.exceptions import DownloadError
def display_context(doc):
"""Create a Jinja context for display"""
# Make a naive dictionary conversion
context = {s.name.lower(): s.as_dict() for s in doc if s.name.lower() != 'schema'}
mandatory_sections = ['documentation', 'contacts']
# Remo... | 53d455448b37a1236e640a66436525fa9369e575 | 3,638,257 |
import torch
def _get_triplet_mask(labels: torch.Tensor) -> torch.BoolTensor:
"""Return a 3D mask where mask[a, p, n] is True if the triplet (a, p, n) is valid.
A triplet (i, j, k) is valid if:
- i, j, k are distinct
- labels[i] == labels[j] and labels[i] != labels[k]
Args:
l... | 91e4e88507979bacde12c4c2dd9725b4d52e0e90 | 3,638,258 |
import re
def analyse_registration_output(output_string):
"""Parse the registration command output and return appropriate error"""
parse_error="ERROR:Unable to parse error message:" + output_string
success=0
fail=1
status_regex = re.compile("Status\s*:\s*(?P<status>[A-Z]+).*")
try:
s... | e6e90b9a55a8631bcb1c0963c943b08df82f03f4 | 3,638,259 |
import random
def randomrandrange(x, y=None):
"""Method randomRandrange.
return a randomly selected element from
range(start, stop). This is equivalent to
choice(range(start, stop)),
but doesnt actually build a range object.
"""
if isinstance(y, NoneType):
return random.randrange(... | 5c6304f20e6e1ddcfda931278defdc0c8867553f | 3,638,260 |
from typing import Callable
def int_domains(ecoords: np.ndarray, qpos: np.ndarray,
qweight: np.ndarray, dshpfnc: Callable):
"""
Returns the measure (length, area or volume in 1d, 2d and 3d) of
several domains.
"""
nE = ecoords.shape[0]
res = np.zeros(nE, dtype=ecoords.dtype)
... | 64ebe6dea6b86b4d391064b100a159c9641dcdde | 3,638,262 |
def pg_conn(postgresql):
"""Runs the sqitch plan and loads seed data before returning db connection.
"""
with postgresql:
# Loads data from blogdb fixture data
with postgresql.cursor() as cur:
cur.execute(
"""
create table users (
... | df3245eecad1c8f0fd1228ff8f3bf8a57701dfef | 3,638,263 |
def partial_with_hound_context(hound, func, *args, **kwargs):
"""
Retuns a partially bound function
Propagates the currently active hound reason (if any)
Useful for capturing the current contextual hound reason when queueing a background action
"""
if hound is not None:
reason = hound.ge... | e2547f3c59ac4168e0961db7216903c7fdca16af | 3,638,264 |
def rssfeed_edit(request, feed, ret_path):
""" Eigenschaften des RSS-Feeds aendern """
def save_values(feed, old, new):
""" geaenderte Werte des RSS-Feeds speichern """
has_changed = False
key = 'title'
if old[key] != new[key]:
feed.title = encode_html(new[key])
has_changed = True
k... | 0643c6ca976d448bf3faf5539e90e59ea7d06bd7 | 3,638,265 |
def disassemble_pretty(self, addr=None, insns=1,
arch=None, mode=None):
"""
Wrapper around disassemble to return disassembled instructions as string.
"""
ret = ""
disas = self.disassemble(addr, insns, arch, mode)
for i in disas:
ret += "0x%x:\t%s\t%s\n" % (i.addr... | 39bddf246b880decbc84015ef20c5664f88d917e | 3,638,266 |
import torch
def overlay_boxes(image, predictions):
"""
Adds the predicted boxes on top of the image
Arguments:
image (np.ndarray): an image as returned by OpenCV
predictions (BoxList): the result of the computation by the model.
It should contain the field `labels`.
"""
... | 99905ae0206d285fa878b0063f227a9152600fad | 3,638,268 |
def convert_tilt_convention(iconfig, old_convention,
new_convention):
"""
convert the tilt angles from an old convention to a new convention
This should work for both configs with statuses and without
"""
if new_convention == old_convention:
return
def _get_... | a24126a20453cf7a7c42a74e71618643215ad5c9 | 3,638,269 |
def _type_of_plot(orientation, n_var, i, j):
"""internal helper function for determining plot type in a corner plot
Parameters
----------
orientation : str
the orientation
options: 'lower left', 'lower right', 'upper left', 'upper right'
i, j : int
the row, column index
... | 9629af21f1995ccd1b582d4f9a7b1ecf2c621c84 | 3,638,270 |
def t2_function(t, M_0, T2, p):
"""Calculate stretched or un-stretched (p=1) exponential T2 curve
.. math::
f(t) = M_{0} e^{(-2(t/T_{2})^{p}}
Args:
t (array): time series
M_{0} (float): see equation
T_{2} (float): T2 value
p (float): see equation
Returns:
... | be4dabf4436832ca3dde9289610070ad41a3632b | 3,638,271 |
def ry(phi):
"""Returns the rotational matrix for an angle phi around the y-axis
"""
if type(phi) == np.ndarray:
m11 = np.cos(phi)
m12 = np.full(len(phi), 0)
m13 = np.sin(phi)
m22 = np.full(len(phi), 1)
m1 = np.stack((m11, m12, m13), axis=0)
m2 = np.stack((m1... | 06a22e478a0912ac3aeba53ba5b565690b94e652 | 3,638,272 |
def hashed_embedding_lookup_sparse(params,
sparse_values,
dimension,
combiner="mean",
default_value=None,
name=None):
"""Looks up embeddings of... | e7b4e803d04336e1d0a88d4051473b895a422f08 | 3,638,273 |
def DelfFeaturePostProcessing(boxes, descriptors, use_pca, pca_parameters=None):
"""Extract DELF features from input image.
Args:
boxes: [N, 4] float array which denotes the selected receptive box. N is
the number of final feature points which pass through keypoint selection
and NMS steps.
... | dbd55fa19085179fae3f6695c3fb529666c4550d | 3,638,274 |
def render_field(field, **kwargs):
"""Render a field to a Bootstrap layout."""
renderer_cls = get_field_renderer(**kwargs)
return renderer_cls(field, **kwargs).render() | 35a5586991072ba4772df48f5b2b649b1c2d62fd | 3,638,275 |
def bisection(a, b, poly, tolerance):
"""
Assume that poly(a) <= 0 and poly(b) >= 0.
Modify a and b so that abs(b-a) < tolerance and poly(b) >= 0 and poly(a) <= 0.
Return (a+b)/2
:param a: poly(a) <= 0
:param b: poly(b) >= 0
:param poly: polynomial coefficients, low order first
:param to... | 9ff1961a95a63af587c9469dd2f987657f1661a9 | 3,638,276 |
def decrypt_message(key, message):
""" returns the decrypted message """
return translate_message(key, message, 'decrypt') | 74b590d493b21928880e43e5f8ae55acd8265bb2 | 3,638,277 |
def IOU(a_wh, b_wh):
"""
Intersection over Union
Args:
a_wh: (width, height) of box A
b_wh: (width, height) of box B
Returns float.
"""
aw, ah = a_wh
bw, bh = b_wh
I = min(aw, bw) * min(ah, bh)
area_a = aw * ah
area_b = bw * bh
U = area_a + area_b - I
... | 92580147eac219d77e6c8a38875c5ee809783790 | 3,638,278 |
import base64
def decode_image(img_b64):
"""Decode image from base64.
https://jdhao.github.io/2020/03/17/base64_opencv_pil_image_conversion/
"""
img_bytes = base64.b64decode(img_b64)
im_arr = np.frombuffer(img_bytes, dtype=np.uint8)
img = cv2.imdecode(im_arr, flags=cv2.IMREAD_COLOR)
img = ... | 22547d43fe1a20032ee095f3fe16d5550a4f08c8 | 3,638,279 |
from datetime import datetime
def date_from_string(date_str, format_str):
"""
returns a date object by a string
"""
return datetime.strptime(date_str, format_str).date() | 7ba2fa5652264c62e2a6711210a39613cf565e37 | 3,638,280 |
import re
def fix_sensor_name(name):
"""Cleanup sensor name, returns str."""
name = re.sub(r'^(\w+)-(\w+)-(\w+)', r'\1 (\2 \3)', name, re.IGNORECASE)
name = name.title()
name = name.replace('Acpi', 'ACPI')
name = name.replace('ACPItz', 'ACPI TZ')
name = name.replace('Coretemp', 'CoreTemp')
name = name.r... | 6a346ece5f03c60a2b5d23d5a66c52735aef2939 | 3,638,281 |
def get_relevant_coordinates():
"""Returns a numpy ndarray specifying the pixel a lidar ray hits when shot
through the near plane."""
coords_and_angles = np.genfromtxt('coords_and_angles.csv', delimiter=',')
return np.hsplit(coords_and_angles,2) | ad814528122777c99aab13652dfb708282993374 | 3,638,282 |
def _expand_host_port_user(lst):
"""
Input: list containing hostnames, (host, port)-tuples or (host, port, user)-tuples.
Output: list of (host, port, user)-tuples.
"""
def expand(v):
if isinstance(v, basestring):
return (v, None, None)
elif len(v) == 1:
return... | 82cfc80f916ef739fc50d8d79a5e19b4aa4a8fa6 | 3,638,283 |
def noise(line, wl=11):
""" Return the noise after smoothing. """
signal = smooth_and_trim(line, window_len=wl)
noise = np.sqrt((line - signal) ** 2)
return noise | 009f05d1eeabf4d0218d78b6c41ff4877f66a5f5 | 3,638,284 |
from typing import Optional
from typing import Iterator
from typing import Tuple
import itertools
import tqdm
import torch
def _evaluate(
limit_batches: Optional[int],
train_pipeline: TrainPipelineSparseDist,
iterator: Iterator[Batch],
next_iterator: Iterator[Batch],
stage: str,
) -> Tuple[float, ... | f0550b60c3d53192acb9ddd2d5057ade118fa79d | 3,638,285 |
import re
def check_pre_release(tag_name):
"""
Check the given tag to determine if it is a release tag, that is, whether it
is of the form rX.Y.Z. Tags that do not match (e.g., because they are
suffixed with someting like -beta# or -rc#) are considered pre-release tags.
Note that this assumes tha... | 8e24a0a61bfa6fe84e936f004b4228467d724616 | 3,638,286 |
def _get_target_connection_details(target_connection_string):
"""
Returns a tuple with the raw connection details for the target machine extracted from the connection string provided
in the application arguments. It is a specialized parser of that string.
:param target_connection_string: the connection... | 5e6ee870c0e196f54950f26ee6e551476688dce9 | 3,638,287 |
def async_setup_platform(hass, config, async_add_devices, discovery_info=None):
"""Set up an Arlo IP sensor."""
arlo = hass.data.get(DATA_ARLO)
if not arlo:
return False
sensors = []
for sensor_type in config.get(CONF_MONITORED_CONDITIONS):
if sensor_type == 'total_cameras':
... | 875ddac74d1e1d8dd10136214f8487d750094e61 | 3,638,288 |
from .tfr import _compute_tfr
def tfr_array_multitaper(epoch_data, sfreq, freqs, n_cycles=7.0,
zero_mean=True, time_bandwidth=None, use_fft=True,
decim=1, output='complex', n_jobs=1,
verbose=None):
"""Compute Time-Frequency Representation ... | 28a6f998fdaa9acde77a521b5e0c5c51a4709887 | 3,638,289 |
import logging
def card(id: int):
"""
Show the selected card data (by id).
"""
for card in cards["cards"]:
if card["id"] == id:
logging.info("card")
return card
logging.info("card")
return "Card not found." | 8a26ea6add0d3ebe539b8a3c0c5dcbf0a458e923 | 3,638,290 |
def build_norm_layer(cfg, num_features, postfix=""):
""" Build normalization layer
Args:
cfg (dict): cfg should contain:
type (str): identify norm layer type.
layer args: args needed to instantiate a norm layer.
requires_grad (bool): [optional] whether stop gradient u... | ef57209bfbd9ead48585ef478a0c74d74127f42f | 3,638,291 |
def scalarProd(v,w):
""" A sum of 2 vectors in n-space.
Params: A 2 tuple point (V)
another 2 tuple point (W)
returns: Distance of (V,W)
"""
v = x[0] + x[1]
w = y[0] + y[1]
return np.array(v*w) | 604750efbef53dfb21468fcc7d4f41bd07af502d | 3,638,293 |
def sample_summary(df, extra_values=None, params=SummaryParams()):
"""
Returns table showing statistical summary from the sample parameters:
mean, std, mode, hpdi.
Parameters
------------
df : Panda's dataframe
Contains parameter sample values: each column is a parameter.
extra_v... | 0fcedfb54f7a72c3811f7cb4c5df559b4d313383 | 3,638,294 |
from .gnat import GNAT
def classFactory(iface): # pylint: disable=invalid-name
"""Load GNAT class from file GNAT.
:param iface: A QGIS interface instance.
:type iface: QgsInterface
"""
#
return GNAT(iface) | 54036f9fa18d901426d45771409a48ab803302ef | 3,638,295 |
from aiida.common.hashing import get_random_string
def get_quicksetup_password(ctx, param, value): # pylint: disable=unused-argument
"""Determine the password to be used as default for the Postgres connection in `verdi quicksetup`
If a value is explicitly passed, that value is returned. If there is no value... | 6ec0a8548bc632bdf008ba3e8e8b8d2bfdd5244b | 3,638,296 |
from typing import List
def convert(day_input: List[str]) -> List[List[str]]:
"""Breaks down the input into a list of directions for each tile"""
def dirs(line: str) -> List[str]:
dirs, last_c = [], ''
for c in line:
if c in ['e', 'w']:
dirs.append(last_c + c)
... | fd1d683e69dbff8411cecdaa184355f2311d3e8a | 3,638,297 |
import codecs
def read(filepath):
"""Read file content from provided filepath."""
with codecs.open(filepath, encoding='utf-8') as f:
return f.read() | bff53fbb9b1ebe85c6a1fa690d28d6b6bec71f84 | 3,638,298 |
def trend_indicator(trend, style):
"""Get the trend indicator and corresponding color."""
if trend == 0.00042 or np.isnan(trend):
return '?', (0, 0, 0, 0)
arrows = ('→', '↗', '↑', '↓', '↘')
trend = min(max(trend, -1), 1) # limit the trend
trend_color = (1, 0, 0, trend * trend) if (trend > ... | 009e95e45c3ba6f4e459f024c09511a7952053e4 | 3,638,299 |
from typing import Callable
from re import T
from typing import Iterable
def space(fn: Callable[[State], T], verbose: bool=False) -> Iterable[T]:
"""
Return an iterable that generates values from ``fn``
fully exhausting the state space.
During iteration, the function ``fn`` is called repeatedly with ... | b901a3936b6e1020db123bce9f72b600117f5825 | 3,638,300 |
import json
def get_menu_as_json(menu):
"""Build Tree-like JSON structure from the top menu.
From the top menu items, its children and its grandchildren.
"""
top_items = menu.items.filter(parent=None)
menu_data = []
for item in top_items:
top_item_data = get_menu_item_as_dict(item)
... | f191d883f44b5cbed729ebcee7670ba99e28d941 | 3,638,301 |
import numpy
def vortex_contribution_normal(panels):
"""
Builds the vortex contribution matrix for the normal velocity.
Parameters
----------
panels: 1D array of Panel objects
List of panels.
Returns
-------
A: 2D Numpy array of floats
Vortex contribution matr... | e5089509646be80307210cad528357d3f85774e9 | 3,638,302 |
def app():
"""Required by pytest-tornado's http_server fixture"""
return tornado.web.Application() | 556ac2b69eaca3d8c4f934fba0deea820ab4e1ff | 3,638,304 |
import inspect
def is_bound_builtin_method(meth):
"""Helper returning True if meth is a bound built-in method"""
return (inspect.isbuiltin(meth)
and getattr(meth, '__self__', None) is not None
and getattr(meth.__self__, '__class__', None)) | a7a45f0f519119d795e91723657a1333eb6714e4 | 3,638,305 |
def normalize(adj):
"""Row-normalize sparse matrix"""
rowsum = np.array(adj.sum(1))
r_inv = np.power(rowsum, -1).flatten()
r_inv[np.isinf(r_inv)] = 0.
r_mat_inv = np.diag(r_inv)
mx = r_mat_inv.dot(adj)
return mx | c342890befeddd3db01403914e80b9e89dc4f20d | 3,638,306 |
def get_recommendation_and_prediction_from_text(input_text, num_feats=10):
"""
Gets a score and recommendations that can be displayed in the Flask app
:param input_text: input string
:param num_feats: number of features to suggest recommendations for
:return: current score along with recommendations... | 6f5737c5ac293a3e33fed7a95119c30c72fafa1e | 3,638,307 |
def set_title(title, uid='master'):
"""
Sets a new title of the window
"""
try:
_webview_ready.wait(5)
return gui.set_title(title, uid)
except NameError:
raise Exception('Create a web view window first, before invoking this function')
except KeyError:
raise Except... | e2ad0fd3673ab2ad0966527b394e9afdf8e2a531 | 3,638,308 |
def FK42FK5MatrixOLDATTEMPT():
"""
----------------------------------------------------------------------
Experimental.
Create matrix to precess from an epoch in FK4 to an epoch in FK5
So epoch1 is Besselian and epoch2 is Julian
1) Do an epoch transformation in FK4 from input epoch to
1984 January 1d 0h
2) Apply... | bbf98f3073fda4a248190e417332d72645faf5c1 | 3,638,309 |
def _lg_undirected(G, selfloops=False, create_using=None):
"""Return the line graph L of the (multi)graph G.
Edges in G appear as nodes in L, represented as sorted tuples of the form
(u,v), or (u,v,key) if G is a multigraph. A node in L corresponding to
the edge {u,v} is connected to every node corresp... | 172fbe2e1d2ec425c3b37c97429df67d789f2c9c | 3,638,310 |
def get_utxo_provider_client(utxo_provider, config_file):
"""
Get or instantiate our blockchain UTXO provider's client.
Return None if we were unable to connect
"""
utxo_opts = default_utxo_provider_opts( utxo_provider, config_file )
try:
utxo_provider = connect_utxo_provider( utxo_opts )
... | 79d72221f707f36bdb07a57b634a57bb42942b2e | 3,638,311 |
from typing import Dict
from typing import Any
def metadata(
sceneid: str,
pmin: float = 2.0,
pmax: float = 98.0,
hist_options: Dict = {},
**kwargs: Any,
) -> Dict:
"""
Return band bounds and statistics.
Attributes
----------
sceneid : str
CBERS sceneid.
... | c3b5203ddbec575f791bef1fb6689088dfa666a2 | 3,638,312 |
def size_to_string(volume_size):
# type: (int) -> str
"""
Convert a volume size to string format to pass into Kubernetes.
Args:
volume_size: The size of the volume in bytes.
Returns:
The size of the volume in gigabytes as a passable string to Kubernetes.
"""
if volume_size >=... | b1b30f4a383d29951d12189180271a9752e5ba61 | 3,638,313 |
def argToDic(arg):
"""
Converts a parameter sequence into a dict.
Args:
arg (string): specified simulation parameters."""
params = dict()
options = arg.split("_")
if "=" in options[0]:
params["mode"] = ""
else:
params["mode"] = options.pop(0)
# parse arguments ... | 173284e8ee45d9e61d786be33d6d6df60e0f9389 | 3,638,314 |
def geth2hforplayer(matches,name):
"""get all head-to-heads of the player"""
matches = matches[(matches['winner_name'] == name) | (matches['loser_name'] == name)]
h2hs = {}
for index, match in matches.iterrows():
if (match['winner_name'] == name):
if (match['loser_name'] not in h2hs)... | 5bcf3e520085acd00e607cad386708b490937e9f | 3,638,316 |
import random
def backtracking_solver(
starting_event: Event,
**kwargs) -> FiniteSequence:
"""Compose a melodic sequence based upon the
domain and constraints given.
starting_event: Event dictate the starting pitch.
All subsequent events will be of similar duration.
constraints -... | 86f33615a2bb72e0f656ba7e021ab3f49dcc79e2 | 3,638,317 |
def jdos(bs, f, i, occs, energies, kweights, gaussian_width, spin=Spin.up):
"""
Args:
bs: bandstructure object
f: final band
i: initial band
occs: occupancies over all bands.
energies: energy mesh (eV)
kweights: k-point weights
gaussian_width: width of gau... | adc2a9c6c91da91b02c0ed9823016b3f256625fb | 3,638,318 |
def findConstantMetrics(inpath):
"""
Simple function that checks which metrics in a dictionary (read from a CSV) are constant and which change over time.
As a reference, the first record read from the file is used
:param inpath: The path to the CSV file that must be analyzed
:return: The list of me... | 0faefe77cfea5e1d74d2bb0dda33ed622ce87f02 | 3,638,319 |
def scoreGold(playerList, iconCount, highScore):
"""Update each players' score based on the amount of gold that they have collected.
Args:
playerList: A list of all PlayerSprite objects in the game.
iconCount: A list of integers representing how many times each player has gained points from the... | 255b4ee987a6ac4a5274ad5ae7b5bf6698840407 | 3,638,320 |
def image_2d_transformer(pretrained=False, **kwargs):
"""
modified copy from timm
DeiT base model @ 384x384 from paper (https://arxiv.org/abs/2012.12877).
ImageNet-1k weights from https://github.com/facebookresearch/deit.
"""
model_kwargs = dict(patch_size=16, embed_dim=768, depth=12, num_heads... | c5891105446ffc4fac5f19f73b5f401bfc769827 | 3,638,321 |
import torch
def create_fourier_heatmap_from_error_matrix(
error_matrix: torch.Tensor,
) -> torch.Tensor:
"""Create Fourier Heat Map from error matrix (about quadrant 1 and 4).
Note:
Fourier Heat Map is symmetric about the origin.
So by performing an inversion operation about the origin, ... | 25a4a4e2aa2ffda317f28d85c3798682fd72c466 | 3,638,322 |
def get_state_name(state):
"""Maps a mongod node state id to a human readable string."""
if state in REPLSET_MEMBER_STATES:
return REPLSET_MEMBER_STATES[state][0]
else:
return 'UNKNOWN' | ddfbfa53c05941747ebedc242baa8e29bddf6771 | 3,638,324 |
def compute_resilience(ugraph, attack_order):
"""
Alias to bfs or union find
:param ugraph:
:param attack_order:
:return:
"""
if USE_UF:
return uf.compute_resilience_uf(ugraph, attack_order)
else:
return bfs_visited.compute_resilience(ugraph, attack_order) | db623ae30b20a076ff8e0f45fb84a9bb24fa414a | 3,638,326 |
def NumericalFlux(b, r, c):
"""Compute the flux by numerical integration of the surface integral."""
# I'm only coding up a specific case here
assert r <= 1, "Invalid range."
if b < 0:
b = np.abs(b)
# No occ
if b >= 1 + r:
return 1
# Get points of intersection
if b > 1 ... | c2e5918702dfd99f7710adf29eb2e8d668cb1cc0 | 3,638,327 |
from typing import Container
def build_volume_from(volume_from_spec):
"""
volume_from can be either a service or a container. We want to return the
container.id and format it into a string complete with the mode.
"""
if isinstance(volume_from_spec.source, Service):
containers = volume_from... | ee5b997ea1832aa490501da3556faa52c611ada9 | 3,638,328 |
def generate_peripheral(csr, name, **kwargs):
""" Generates definition of a peripheral.
Args:
csr (dict): LiteX configuration
name (string): name of the peripheral
kwargs (dict): additional parameterss, including
'model' and 'properties'
Returns:
stri... | 154428b153b804c23eb9b2a99380e987402c9fb4 | 3,638,329 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.