content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def plot_3d(df, target_variable):
"""
3d plot of data frame columns
:param df: pandas.DataFrame
:param target_variable: pandas.Series
:return: None
"""
unique_labels = target_variable.unique()
ordinal_encoding = [np.where(unique_labels == label)[0][0]
for label in... | 967ab3a90a674e1c7bc008825864025fea29d01a | 3,610,446 |
def user_albums_query(user_id: str, page_number: int) -> dict:
"""
Build User albums query.
:param user_id: User id
:param page_number: page number
:return: Query
"""
return {
"id": 8,
"operationName": "AlbumList",
"query": "query AlbumList($input: AlbumListInput!) {album {list(input: $input) ... | ca490875a999215bd9cfc7f71a5763c8518f5289 | 3,610,447 |
import typing
def _consts(fn: typing.Callable) -> tuple:
"""
Returns a tuple of the function's constants excluding the docstring.
"""
return tuple(x for x in fn.__code__.co_consts if x != fn.__doc__) | bd60a35cf5243fd158d6e65df6e0a16f6fd9051b | 3,610,448 |
def x_y_to_name(x, y) -> str:
"""
Make name form x, y coords
Args:
x: x coordinate
y: y cooridante
Returns: name made from x and y
"""
return f"{x},{y}" | 40ae99a789fdf029407ab0290ae58e85e911833c | 3,610,450 |
def database():
""" Get all raw database details."""
data = db.DB().db_get()
return data | 50cdbefc8e07fab2c2619b4252826d364aa8777d | 3,610,451 |
def indice_PM10(fila, columna):
"""Cálculo del índice de calidad del aire para el PM10 (usando datos de micro gramo sobre metro cúbico).
Las operaciones que se realizan aquí son una normalización para que cada contaminante se mida de acuerdo al índice
de calidad del aire. Esta función se ocupa de calcular ... | f571b67b4ce939325775dd12a3f93911e1b724a8 | 3,610,452 |
def sigmoid_cross_entropy_balanced_back(logits, label, name='cross_entropy_loss'):
"""
Implements Equation [2] in https://arxiv.org/pdf/1504.06375.pdf
Compute edge pixels for each training sample and set as pos_weights to
tf.nn.weighted_cross_entropy_with_logits
"""
y = tf.cast(label, tf.float32... | 6d2fda3ace17516b0278e0a3f9c589ef123509ca | 3,610,453 |
def infer_table_schema_type_from_rdf_term(term_type, term_datatype):
"""Map an RDF literal type to Table Schema field type
:param term_type: type from RDF term
:param term_datatype: datatype from RDF term
"""
if (term_type == 'literal' and
term_datatype is not None):
return _RDF... | 5e75c3aa78fff179c88d464fddb66140912f1cc0 | 3,610,454 |
def _lvl_error(level):
"""Get the lng/lat error for the hilbert curve with the given level
On every level, the error of the hilbert curve is halved, e.g.
- level 0 has lng error of +-180 (only one coding point is available: (0, 0))
- on level 1, there are 4 coding points: (-90, -45), (90, -45), (-90, 4... | 52f8653252de1120d34c9a0377e85c07111874d6 | 3,610,456 |
def make_lowshelf(
frequency: int, samplerate: int, gain_db: float, q_factor: float = 1 / sqrt(2)
) -> IIRFilter:
"""
Creates a low-shelf filter
>>> filter = make_lowshelf(1000, 48000, 6)
>>> filter.a_coeffs + filter.b_coeffs # doctest: +NORMALIZE_WHITESPACE
[3.0409336710888786, -5.60887099222... | 53a1f69182f60fe668435bca3e7a0b2638ed4f83 | 3,610,457 |
import random
def prepare_wikidata_completion(qid=None, pid=None, is_category=False):
"""
Get the subject's label, Wikipedia article, and get property's label to construct the question
:param qid: Entity Id starts with Q
:param pid: Property Id starts with P
:param is_category: flag indicates ... | 50f963d52204a5d9b91f06577b04ac9558d5aaa2 | 3,610,459 |
def _kron_1d(a, b):
"""This function is for internal use.
Returns a⊗b for 1d array.
"""
nb = b.size
d = np.repeat(a, nb).reshape(-1, nb)
d *= b
return d.reshape(-1) | 76973d7f676c7bfeb132958ad20e2bf6ec285cb4 | 3,610,460 |
def micromanager_metadata_to_coords(summary, n_times=None, z_centered=True):
"""
Given the 'Summary' dict from micromanager, parse the information
into coords for a corresponding DataArray.
Parameters
----------
summary : dict
Micromanager metadata dictionary.
n_times : int
... | 2f8cf96d59ab34465fb7fb5a550126356beb617e | 3,610,461 |
def problem1(limit, mod1, mod2):
"""Problem 1"""
result = 0
for cur in range(0, limit):
if cur % mod1 == 0 or cur % mod2 == 0:
result += cur
return result | e0be92fc6e2be4730606f02256e59018420655e6 | 3,610,462 |
def arrayuniqify(X, retainorder=False):
"""
Very fast uniqify routine for numpy arrays.
**Parameters**
**X** : numpy array
Determine the unique elements of this numpy array.
**retainorder** : Boolean, optional
Whether or not to return in... | 35a6297da42881b7a67b5e968da0f857afd6f79c | 3,610,463 |
def atmDensPoly6th(ht, dens_co):
""" Compute the atmosphere density using a 6th order polynomial. This is used in the ablation simulation
for faster execution.
Arguments:
ht: [float] Height above sea level (m).
dens_co: [list] Coeffs of the 6th order polynomial.
Return:
a... | 653b134d513c3fd9b55e72ee37a4c7116aadf8cf | 3,610,464 |
def render_product(context, product):
"""
Render a product snippet as you would see in a browsing display.
This templatetag looks for different templates depending on the UPC and
product class of the passed product. This allows alternative templates to
be used for different product classes.
""... | c9c856ae58c6e0d26c7b1452e47d33bb1108d5a0 | 3,610,465 |
def get_bias_initializer(name: str, dtype=jnp.float32) -> WeightInitializer:
"""Get a bias initializer."""
validate_bias_initializer(name)
return INITIALIZER_CONSTRUCTORS[name](dtype=dtype) | db49bfbc39860d0abed1d058dfffd473a6f6e8f6 | 3,610,467 |
def raw_fashion_train_images_file():
"""
Train images of MNSIT.
:return: filepath
:rtype: str
"""
return data_file('fashion/train-images-idx3-ubyte', GZIP_EXT) | 0579a844332609b70483bc6dda3e6f3422c4ccfa | 3,610,468 |
def comment_staticman(github_token, ci_data):
"""Sequence of functions to get data from github for staticman comment
and then write the comment to github
"""
return sequence(
pr_url,
requests_get(github_token),
lambda x: x.json(),
get("body"),
archieml.loads,
... | 379a6b32245cf6f9f49bf6b0cb4f9b183dab6fd1 | 3,610,469 |
import uuid
def get_file_name() -> str:
"""
Creates a unique file name for datastore by appending timestamp to the file name
:return:
"""
uniq_append_string = uuid.uuid4().hex
return "LOCAL_STORAGE_{}".format(uniq_append_string) | a865199dc688dfcbb7077d9cf0a30aa9f5199849 | 3,610,470 |
def requires_auth(function):
"""
:param function:
:return: the validity of a request
"""
@wraps(function)
def decorated(*args, **kwargs):
p_access = False
auth_token = False
if not auth_token:
auth_token = request.header.get('Authorization')
if not aut... | 22841d539043dcf944ed53a9bcc059e5489a4d1c | 3,610,471 |
import torch
def xyxy2xywh(box2d):
"""
input : [n, 4] [x1, y1, x2, y2]
return : [n, 4] [x, y, w, h]
compatible with both pytorch and numpy
a faster dedicated numpy implementation can be found at lib/fast_util/bbox2d.py
"""
center_x = 0.5 * (box2d[:, 0] + box2d[:, 2])
... | 54002a422ba762c5797f375be27aa4ee9e0b224c | 3,610,472 |
from sosia.processing.querying import base_query
def auth_npubs_retrieve_insert(auth_id, year, conn):
"""Retrieve an author's publication count until a given year, and insert."""
q = f"AU-ID({auth_id}) AND PUBYEAR BEF {year+1}"
npubs = base_query("docs", q, size_only=True)
tp = (auth_id, year, npubs)... | c1561cd7af9f43a1aa6e660cbefbef4f15512724 | 3,610,473 |
def back_url(request):
"""后台通知地址
:param request:
:return:
"""
return HttpResponse("Hello back_url") | d90a9374aa53efbc032d0556268033b332e5e361 | 3,610,474 |
def SignedCharCast(value):
"""Explicitly cast a value to type 'signed char'."""
shift = ConstInt(24)
return RShift(LShift(value, shift), shift) | 0638524bd2835e375bc520d903ee303b5c9c12c7 | 3,610,475 |
def get_nested_plot_frame(obj, key_map, cached=False):
"""Extracts a single frame from a nested object.
Replaces any HoloMap or DynamicMap in the nested data structure,
with the item corresponding to the supplied key.
Args:
obj: Nested Dimensioned object
key_map: Dictionary mapping bet... | 45aa0017c23fc91bfb1cfe142b1db10b735c2e41 | 3,610,476 |
import hashlib
def __str_to_hash(string_to_hash: str, errors: str = 'ignore') -> str:
""" Encodes the given string and generates a hash from it. """
string_hash = string_to_hash.encode(encoding="utf-8", errors=errors)
return hashlib.md5(string_hash).hexdigest() | e7c0c419f9fa39bf5884198ec1dbfe4816fb7383 | 3,610,477 |
def zeros(shape, dtype, force_cpu=False):
"""
The OP creates a tensor of specified :attr:`shape` and :attr:`dtype`, and fills it with 0.
Its :attr:`stop_gradient` will be set to True to stop gradient computation.
Parameters:
shape (tuple|list): Shape of output tensor.
dtype (np.dtype|co... | 793e82b855b0aa60e612bd5149fd00d3abbd38dc | 3,610,478 |
def get_editors(ref_string):
"""
returns list of editors, which can appear anywhere in the reference
:param ref_string:
:return:
"""
if isinstance(ref_string, unicode):
ref_string = unidecode.unidecode(ref_string)
lead_match = LEADING_INIT_AUTHORS_PAT.search(ref_string)
trail_m... | 2424fc7be73e337ab9d2212dc8a9a7b42f65c953 | 3,610,479 |
def extract_ta_features(stock_df):
"""Compute features using TA's technical indicators."""
initial_len = len(stock_df)
stock_df = ta.add_trend_ta(stock_df, high="High", low="Low", close="Close")
stock_df = ta.add_momentum_ta(
stock_df, high="High", low="Low", close="Close", volume="Volume"
... | ca1b70d594dcdba0c3fae3a7589ed4b048cd7440 | 3,610,480 |
import six
def user_pk_to_url_str(user):
"""
This should return a string.
"""
User = get_user_model()
if (hasattr(models, 'UUIDField') and issubclass(
type(User._meta.pk), models.UUIDField)):
if isinstance(user.pk, six.string_types):
return user.pk
return us... | 8216bf095262e28b0baa87b91349f6b7a05c71b2 | 3,610,481 |
def _get_coords(xedges, yedges):
"""Get coordinates given the edges of the histogram."""
global XBUFFER, YBUFFER
if XBUFFER is None:
xcenters = (xedges[:-1] + xedges[1:]) / 2
ycenters = (yedges[:-1] + yedges[1:]) / 2
X, Y = np.meshgrid(xcenters, ycenters)
XBUFFER = X
... | 678e6d9461388735cbdbc7771e1d5cd22c3c105f | 3,610,482 |
def get_information_from_certificate(certificate):
"""
Extract user information from a client certificate
:param certificate: The certificate
:return:
"""
if not certificate:
return None, None
# open certificate
cert_chain = X509CertChain()
try:
cert_chain.parsePemLi... | 3652ef25db3bc978426bc1f7212d6face1385b63 | 3,610,483 |
def create_model_helper(base_model_fn, sequential_inputs, is_training):
"""Helper function for creating model function given base model function.
This function creates a model function that adaptively slices the input
features for improved running speed.
Note that the base model function is required to have i... | 2cbd3c22703c313bce4ec60a029110ae332d9bcd | 3,610,484 |
def check_not_finished_board(board: list) -> bool:
"""
Check if skyscraper board is not finished, i.e., '?' present on the game board.
Return True if finished, False otherwise.
>>> check_not_finished_board(['***21**', '4?????*', '4?????*', '*?????5', '*?????*', \
'*?????*', '*2*1***'])
False
... | 546d68c77f17cca0a418a7852cc671ac2184ea8e | 3,610,485 |
def transform(params):
"""Convert from ConfigSpace params to Orion params"""
return {k: (v if v is not _NoneValue else None) for k, v in params.items()} | e9bf968719f801544b1cd5e1fa90c9d36cebde4f | 3,610,486 |
def template_test():
"""Return a test template"""
return render_template_string(
templates.TEMPLATE, my_string="Wheeeee!", my_list=[0, 1, 2, 3, 4, 5]
) | 87a641e02c8a94c3a0aebe6a972ebdd3b1342657 | 3,610,489 |
def find_overlap_percentage(nominator, denominator):
"""This function is used to find overlap percentage between 2 lists"""
common_skills_set = set(nominator).intersection(denominator)
common_skills_list = list(common_skills_set)
if common_skills_list:
overlap_percentage = len(common_skills_list... | 605f55e4698255a97a800d8a183078b25e6c2a34 | 3,610,490 |
def report_withot_driver_part():
"""Returns part from correct final report"""
return [" 10. Pierre Gasly | SCUDERIA TORO ROSSO HONDA | 0:01:12.941",
" 11. Carlos Sainz | RENAULT | 0:01:12.950"] | 0117401194c9c36f86b6b8f1572f06f673a8b085 | 3,610,492 |
from typing import Union
from typing import Tuple
def get_rationed_resizing(
resized: Union[int, float], length: int, other_length: int
) -> Tuple[int, int]:
"""
Get resized lengths for `length` and `other_length` according to
the ratio between `resized` and `length`.
Parameters
----------
... | dde1ce579c192178090fe07c145fd3e153d92599 | 3,610,493 |
def pyprep_reference(matprep_artifacts):
"""Get the robust re-referenced signal for comparison with MATLAB PREP.
This fixture uses an artifact from MATLAB PREP of the CleanLined EEG signal
right before MATLAB PREP calls ``performReference``. As such, the results
of these tests will not be affected by a... | 71fa40eab30d6893a5d8d2451f0e5049843e4005 | 3,610,494 |
def list_average(value_list: list[int|float]) -> None:
"""Return the average of a list of ints or floats."""
return list_sum(value_list) / len(value_list) | 181bae83e129708efae4579bce4f62d70db599e5 | 3,610,495 |
def data_context_connectivity_context_connectivity_serviceuuid_include_nodetopology_uuidnode_uuid_get(uuid, topology_uuid, node_uuid): # noqa: E501
"""data_context_connectivity_context_connectivity_serviceuuid_include_nodetopology_uuidnode_uuid_get
returns tapi.topology.NodeRef # noqa: E501
:param uuid: ... | bcad7bb85ecb2d9f89f9f6c7dd228612532e785d | 3,610,496 |
def delete_restaurant(request, id):
"""
Delete dish.
Roure for 'remove/d/<int:id>'.
"""
Restaurant.objects.get(id=id).delete()
messages.info(request, "Deleted")
return redirect(f"/management") | 805ad0a3a0728afc40ddeb29e0b8ce6244eadf84 | 3,610,497 |
def is_part_of_branch(action):
"""
Checks if action is part of branch action.
:return: Boolean
"""
try:
branch_action = get_parent_by_tag(element=action, tag="steps_Behaviour")
except AttributeError: # parent with tag="steps_Behaviour" cannot be found --> is not in branch
return... | bd8d55f120b18d2f01c5a48011884d4bffb99e80 | 3,610,498 |
def get_sprite_pos(map_dim, sprite_dim, clip_sprites):
"""Returns a sprite position for a given map and sprite."""
map_w, map_h = map_dim
sprite_w, sprite_h = sprite_dim
if clip_sprites:
x_pos = randint(-sprite_w, map_w)
y_pos = randint(-sprite_h, map_h)
else:
x_pos = randin... | e3d6554758db6268167fd4e335032bd66dc622bb | 3,610,499 |
import collections
def reorder(fields, order, key):
"""
Reorders `fields` list sorting its elements in order they appear in `order` list.
Elements that are not defined in `order` list keep the original order.
:param fields: elements to be reordered
:param order: iterable that defines a new order
... | 48eb32841f5abec38c74a8ae88615a7c39d3087c | 3,610,500 |
def noisify_dfc2018_asymmetric(y_train, noise, random_state=None):
""" mistakes in labelling the land cover classes in 2018 DFC Houstan HSI dataset
class 0 --> class 1, class 3
class 1 --> class 5
class 3 --> class4, class 7
class 4 --> class 3, class7, class 10
class 7 --> class9, class 10, (cl... | 30560a2c351e11e84d194d71acbe942fe6e4cf08 | 3,610,503 |
from typing import Union
from typing import Optional
from typing import List
from typing import Dict
from typing import Any
from typing import Tuple
import io
def encoding_quality(
image: Union[str, Image.Image],
output_path: Optional[str] = None,
quality: int = 50,
metadata: Optional[List[Dict[str, A... | 3babe50b0ba8c657b1c2ea9733c41e8aed544bd1 | 3,610,504 |
def extCheck( extention: str ) -> str:
"""
Ensures a file extention includes the leading '.'
This is just used to error trap the lazy programmer who wrote it.
:param extention: file extention
:type extention: str
:return: Properly formatted file extention
:rtype: str
"""
if extentio... | 7055c23cd8d2fa0e74dd916aa6d06d9547d49b7f | 3,610,505 |
def ui_routes():
"""Import all static routes"""
return [static] | 23e51c0c32b58007d6001a458a3942473763f695 | 3,610,506 |
def create_transaction(sender: str, recipient: str, amount: float):
"""insert new transaction to mempool"""
transaction = transactions.create_transaction(
sender=sender,
recipient=recipient,
amount=amount,
type="transfer",
)
return transaction | 1525a934106c292624dae2722f5b0c7f5e15c3f9 | 3,610,507 |
import logging
def load_data(in_file, max_example=None, relabeling=True):
"""
load CNN / Daily Mail data from {train | dev | test}.txt
relabeling: relabel the entities by their first occurence if it is True.
"""
documents = []
questions = []
answers = []
num_examples = 0
f... | da81dcc56469aaccee3da36d1451ac8eaeb4a2b7 | 3,610,508 |
import json
def sort_dict(original, parent_path=''):
"""Transforms a dict into the format Authy requires"""
flattened_dict = ''
for key in sorted(original):
value = original[key]
if parent_path:
flattened_key = parent_path + '[{0}]'.format(key)
else:
flatt... | f79ea541453bae9f301ca10cd84a97194d019289 | 3,610,509 |
def makeA(laplacian_matrix):
"""
This function create the all neighbor permutations.
The output A multiply by Y will be [ Y_i - Y_j ].T for all j > i
So the maximum will be C^n_2. But it will be less than this value
because of the sparseness of L.
Returns
-------
A : sparse matrix, shap... | b5cf889649077fd8f92a8d659c908d47d6490202 | 3,610,510 |
from ._service import _configure_service
from typing import Optional
from typing import Union
from typing import Callable
from typing import cast
def service(
klass: Optional[C] = None,
*,
singleton: Optional[bool] = None,
scope: Optional[Scope] = Scope.sentinel(),
wiring: Optional[Wiring] = Wirin... | dba3ac7e81a54e017f6da316695dbbdcaace5a5b | 3,610,511 |
def svn_diff_output_fns_invoke_output_diff_modified(_obj, output_baton, original_start, original_length, modified_start, modified_length, latest_start, latest_length):
"""svn_diff_output_fns_invoke_output_diff_modified(svn_diff_output_fns_t _obj, void * output_baton, apr_off_t original_start, apr_off_t original_len... | 4cf2f3bcd6818ea5bfb749f07e6129fd51b188a8 | 3,610,512 |
import copy
def delete_items(dictionary, key_list):
"""
This function performs a deep copy of a dictionary, checks if the
specified keys are included in the copy, and deletes key-value pairs
accordingly.
Parameters:
dictionary (dict): a dictionary
key_list (list): a list of the key... | 45fb652661387ca5d40aea443c1d4a82f74db5bd | 3,610,514 |
from typing import Set
def build_deterministic_service_from_transitions(
transition_function: TransitionFunction,
initial_state: State,
final_states: Set[State],
) -> Service:
"""
Initialize a service from transitions, initial state and final states.
The set of states and the set of actions a... | e9ec2cf5cd9280ae0fa40bfa1b73c39c61ec4b37 | 3,610,515 |
def spreadLambdaProtocol(switching_values, steps, switching_types='auto', kind='cubic', return_tab_function=True):
"""
Takes a list of lambda values (either for sterics or electrostatics) and transforms that list
to be spread out over a given `steps` range to be easily compatible with the OpenMM Discrete1DF... | cbd4ea39988c374f87c8f8061b7d30deacb5590d | 3,610,516 |
def some_method(a1, a2):
"""
some_method returns the larger num
:param a1: num1
:param a2: num2
:return: 1 or 2
"""
if a1 > a2:
return 1
elif a1 < a2:
return 2
else:
return 0 | 2505053aae5b0e0d1e906881d8de50b7ad97a28e | 3,610,517 |
def restartATS(conf:Configuration) -> bool:
"""
A convenience function for calling :func:`setATSStatus` for restarts.
:param conf: An object representing the configuration of :program:`traffic_ops_ort`
:returns: whether or not the restart was successful (or unnecessary)
"""
doRestart = ( conf.mode is Configurat... | 15f9b872a4cd4cec269e4ae718d25e885c968918 | 3,610,518 |
from typing import List
def generate_res_count_graph(
name: str,
cloudwatch_data_source: str,
loadbalancer: str,
target_group: str,
grid_pos: GridPos,
notifications: List[str],
) -> Graph:
"""
Generate res graph
"""
xx2_alias = "2xx"
xx3_alias = "3xx"
xx4_alias = "4xx"... | e33de89621f25e990ac8bd5fca0546dd6b8bf186 | 3,610,519 |
def cost(prog):
"""Find the cost of a program tree."""
if type(prog) == VecOp:
return COSTS["VecOp"] + sum([cost(p) for p in prog.children])
elif type(prog) == Op:
return COSTS["Op"] + sum([cost(p) for p in prog.children])
elif type(prog) == Lit:
return COSTS["Lit"]
elif type... | 37cc80ad1355d5a4f5d7abd0df85ab7340d3c28e | 3,610,520 |
from re import T
def transform_instance_annotations(
annotation, transforms, image_size, *, keypoint_hflip_indices=None
):
"""
Apply transforms to box, segmentation and keypoints annotations of a single instance.
It will use `transforms.apply_box` for the box, and
`transforms.apply_coords` for se... | 582124cbc98e10d00ca0589f689fa7de27382f97 | 3,610,521 |
def to_timestamp(value):
"""
Convert a time zone aware datetime to a POSIX timestamp (with fractional
component.)
"""
return (value - epoch).total_seconds() | 5c065d1056eb38afd25312e1dca5a6e8e260948a | 3,610,522 |
def backends_mapping(custom_backend, private_base_url, lifecycle_hooks):
"""
Create 2 separate backends:
- path to Backend 1: "/echo-api"
- path to Backend 2: "/httpbin"
"""
return {"/echo-api": custom_backend("backend_one", endpoint=private_base_url("echo_api"), hooks=lifecycle_hooks),
... | b98fb61afc00efc902e5bd511fefcea6727a7125 | 3,610,523 |
import requests
def post(json_attributes):
"""HTTP POST request."""
url = f"{API_URL}/v1/summaries/plain-text"
response = requests.post(url, json=json_attributes)
return response | 061e4ea9f5aba2ab8503267c245cc8f4a444c972 | 3,610,524 |
def get_credentials(args):
""" Return current or assumed role credentials """
sess = boto3.session.Session(profile_name=args.profile)
sts = sess.client('sts')
# Find out who we are
ret = sts.get_caller_identity()
if not 'Account' in ret:
raise Exception('STS: Get Caller Identity fa... | 0580e6405a8e8a9b6d0e1365cc57390c14a85ce4 | 3,610,525 |
def inf(shape, dtype, allocator=drv.mem_alloc):
"""
Return an array of the given shape and dtype filled with infs.
Parameters
----------
shape : tuple
Array shape.
dtype : data-type
Data type for the array.
allocator : callable
Returns an object that represents the m... | 394b8ddc7746ed17dd0a697a66042436b3c652ca | 3,610,526 |
def belief_propagation(model: GraphModel,
max_iter: int = 1000,
converge_thr: float = 1e-5,
damp_ratio: float = 0.1) -> InferenceResult:
"""Inference with (loopy) Belief Propagation.
Estimates partition function using Loopy Belief Propagation... | e816dbb83676324e08f29127c980b1f997f84b15 | 3,610,527 |
def model_loss(input_real, input_z, output_channel_dim, alpha):
"""
Get the loss for the discriminator and generator
:param input_real: Images from the real dataset
:param input_z: Z input
:param out_channel_dim: The number of channels in the output image
:return: A tuple of (discriminator loss,... | 0d51ef038536cfbde4989bb1058b359d5be900b6 | 3,610,528 |
import json
def compile_timestamped_transcript_files(json_filenames):
"""
`json_filenames` is a list of filepaths with this filename format:
00900-01000.json
where the left-number represents the starting time offset and
the right-number represents the ending time, in seconds
Each file... | 75dbf7541fbfc4df109a43cb51531d7d68c5e126 | 3,610,529 |
from sympy import Poly
def _solve_inequality(ie, s):
""" A hacky replacement for solve, since the latter only works for
univariate inequalities. """
if not ie.rel_op in ('>', '>=', '<', '<='):
raise NotImplementedError
expr = ie.lhs - ie.rhs
p = Poly(expr, s)
if p.degree() != 1:
... | f90151b25d6225e382c0f5dac686f2ff5529cf0e | 3,610,530 |
def verify_bgp_route_is_received(
device,
vrf,
neighbor_address,
default_rd,
default_vrf,
address_family,
received_routes,
):
""" Verify if VRF and Router Distinguisher have at least one received route
Args:
device ('obj') : Device object
addr... | f8fba8f4fb0869c9fa0fb6a18c2b5e1367e71ad7 | 3,610,531 |
def theils_u_matrix(df):
"""
Wrapper around dython's theils_u. Given a dataframe df
containing only categorical data, it calculates Theil's U
for each combination of columns, filling an output matrix, and
returns the output matrix.
Parameters
----------
df : pandas.DataFrame
The... | f2e370344abf182186f902cd01db2658f7a4c69b | 3,610,532 |
def support(shape1, shape2, direction):
"""Find support for the Minkowski difference in the given direction.
PARAMETERS
----------
shape1, shape2: Shape
The inputs for Minkowski difference. `shape1` is subtracted from `shape2`.
direction: Point
The direction for finding the support... | 4b9292116c9447549f36099d4a6928c4c6e74e28 | 3,610,533 |
def get_service(key_file_location, api_name='analytics', api_version='v3',
scopes = ['https://www.googleapis.com/auth/analytics.edit',
'https://www.googleapis.com/auth/analytics']):
"""Get a service that communicates to a Google API.
Args:
key_file_location: The path to a valid service ac... | b3c06b472eb7ef6bb5d880461bc00d0947dd7214 | 3,610,537 |
def render_html_with_traceback(error: HTTPError) -> str:
"""Bottle's default error handler."""
return tob(template(ERROR_PAGE_TEMPLATE, e=error)) | 5949c68294f832bf24c6ea19de1b1084c7c317a5 | 3,610,538 |
from pathlib import Path
def is_empty(path: Path) -> bool:
"""Checks if a directory has files
Args:
path: The path to the directory to check
Returns:
bool: True if the dir is empty, False if it contains any files
"""
return not any(path.iterdir()) | b99045eee29922c7ef2e91cd1b8b71ab54181e1e | 3,610,539 |
def bounded_1d_kde(
pts, method="Reflection", xlow=None, xhigh=None, *args, **kwargs
):
"""Return a bounded 1d KDE
Parameters
----------
pts: np.ndarray
The datapoints to estimate a bounded kde from
method: str, optional
Method you wish to use to handle the boundaries
xlow: ... | 631168244db3e4a0b57acc6c0caa122e48ff02ce | 3,610,541 |
import json
def parse_manifest_file(filename):
"""
Parses artifacts from a manifest file into a mapping from region to AMI.
Args:
filename: the manifest file to parse
Returns:
A dict mapping region to AMI ID
"""
with open(filename, 'r') as manifest_file:
packer_manifes... | 36391fc6de76c431a6d46a3c2afdbecb6aa38823 | 3,610,542 |
def find_best_group_or_software(obj_tour_list):
""" Find group with step 2 and 3 with 2 or more subtechniques """
# Ideal: find Step 2 and Step 3 with most subtechniques
obj_w_best_step_2_3 = {}
for obj_tour in obj_tour_list:
# First group
if not obj_w_best_step_2_3:
obj_w_... | e23ad122b4f57143c5d271ebfcf42f23637fb2e2 | 3,610,543 |
import math
def detectPupil(image, threshold=101, minimum=5, maximum=50):
"""
Given an image, return the coordinates of the pupil candidates.
"""
# Create the output variable.
bestPupilID = -1
ellipses = []
centers = []
area = []
kernel = np.ones((5, 5), np.uint8)
# Grayscale... | d77d1beff67254a06ab74563398edc476cb99fe9 | 3,610,545 |
def vad_on_unlabelled_data(audio_path: str, output_path: str, session_name: str, strictness_level: int = 3,
word_threshold: int = 1, number_of_thread: int = 0, time_type: str = "timestamp"):
"""
This function is doing the VAD on unlabelled audio data.
It will generate a new csv fi... | 658a81094b5ad0f6ac12a723fd00616fe694f39f | 3,610,546 |
def simplify(g:Graph) -> tuple:
"""
Performs a single iteration of simplification
of Graph instance according to a set or rules.
Returns: tuple: list of Graph instances and
boolean: whether the graph was successfully simplified
"""
choices = {(1,1):4,(2,2):4,(0,0):6,(1,0):3,(2,1):2}
m ... | d9354eb6c2d2fd7cfc13fa2838ef328ecc2ecd91 | 3,610,548 |
def check_duplicates(message):
"""tweet message 를 최신 세 개의 사용자 tweet 과 대조하여 중복된 게시물이 없는지 확인합니다.
전달인자:
message: 게시할 메시지를 포함한 문자열
반환 값:
중복이 발견되었을 경우 True를 나타내는 boolean
"""
last_three = retrieve_own_tweets()
last_three_tweets = [tweet.full_text for tweet in last_three] # 확인할 트윗 메시지 문자열 li... | 0d72de184b2a36741f4a20e1ebe81db7bffc81ca | 3,610,549 |
def myKPCA(X, Y, kernel_type='gauss', c=3, deg=2, ncomp=2, dataset='wine', show=False):
""" Kernel PCA.
Params:
--------------
X: n x d samples matrix
Y: n x 1 vector of class labels
kernel_type: Kernel type (Polynomial, RBF, etc.)
c: Gaussian width (Ignored if kernel... | 132c3fc1711cb83d27c08910c264963b57fbd702 | 3,610,550 |
from typing import Any
from typing import ContextManager
def _open(path: _StrOrPath, *args: Any, **kwargs: Any) -> ContextManager[Any]:
"""Opens the file; this is a hook for the built-in open()."""
return open(path, *args, **kwargs) | 28f5e9339ccee39a355f0fbf0a82c034e5fcc1cd | 3,610,553 |
def partition(groups, train_part=0.8, val_part=0.1, test_part=0.1):
"""Splits groups into training, validation, and test partitions.
Args:
groups (list): list of units (e.g. dicts).
train_part (float): proportion in [0, 1] of units for training.
val_part (float): self-explanatory.
... | c2cf56e54809a7c8c3a75c8b8bdbb3764aa9b988 | 3,610,554 |
def click_z_origin(im):
"""
Records user clicks that indicate the desired origin and z-axis in an
image. These can be used to calculate the r-coordinate measured off the
z-axis.
Parameters
----------
im : (M x N x 3) or (M x N) numpy array of floats or uint8s
Image that will be shown... | ff6a28893d246035db0c112df30581e3965a63ce | 3,610,555 |
from typing import Union
from pathlib import Path
def get_logger_config(caller_file_path: Union[str, Path], name: str=None) -> dict:
"""
Get logger config as dictionary
:param caller_file_path: file path of the caller, __file__
:param name: the name(section in logme.ini) of the config to be passed. (... | c162276330f8d4be205717cf5a365a53592b5f7a | 3,610,556 |
import ast
def _optimizer(program, fun_list, n_features, n_program_sum, metric,
X, y, weight):
"""Simplify a program and then optimize its numerical parameters.
Parameters
----------
program : list
The program to be optimized.
fun_list : list of length 6
List mapping the oper... | 025c8091f672e6bb3759c6fd9bfcc793a02166a7 | 3,610,557 |
def full():
"""Returns human friendly full date of current UTC time"""
return obj().strftime("%A, %d %B %Y %I:%M%p") | 8ceb877afe163c3c55f6195a92f6c709900e13ba | 3,610,558 |
def need_to_login():
"""A route used to indicate the user needs to authenicate for some page."""
year = date.today().year
return render_template("website/login.html",
message="Need to login to proceed further.",
route=Routes,
y... | fef498363ea9bcfca44b5c86c4da7528a80bd266 | 3,610,559 |
def get_peaks(sig, onsets):
"""
Perform an algorithm to identify a series of peaks given a
signal and it's onsets
:param sig: The signal requiring the calculation
:param onsets: An array of containing the list of onsets for the signal
:return: An array containing the list of peaks in the s... | bef20a6c2f13e83bc5d696e8b9983c139edea661 | 3,610,560 |
def phpinfo(interp, arg):
""" Outputs information about PHP's configuration"""
if arg & get_const('standard', 'INFO_MODULES'):
for ext in EXTENSIONS:
interp.writestr(ext + "\n")
return interp.space.w_True | 9bcb3419cbeba3a7466c214a2c41f93f6ae18c54 | 3,610,563 |
import json
def get_graph(name, hetmat=False, directory=None):
"""
If hetmat=True, import graph into a hetmat located on-disk at directory.
"""
if name not in hetnet_urls:
raise ValueError(
f"{name} is not a supported test hetnet.\n"
"Choose from the following currently... | 74c55c180f755f8f0feea34630fd5680900632ac | 3,610,565 |
def insert_project_files(sandbox):
""" Fixture factory for inserting config files into tmp project dir """
def inner(package=False, lock=False):
if package:
sandbox['proj_package'].write_text(PACKAGE_JSON)
if lock:
sandbox['proj_lock'].write_text(LOCK_JSON)
return... | e0ebf65c4aeee01b0d708b4cfd63b684561def07 | 3,610,566 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.