repository_name stringlengths 7 107 | function_path stringlengths 4 190 | function_identifier stringlengths 1 236 | language stringclasses 1
value | function stringlengths 9 647k | docstring stringlengths 5 488k | function_url stringlengths 71 285 | context stringlengths 0 2.51M | license stringclasses 5
values |
|---|---|---|---|---|---|---|---|---|
jeeftor/alfredtoday | src/lib/rsa/transform.py | bytes2int | python | def bytes2int(raw_bytes):
return int(binascii.hexlify(raw_bytes), 16) | r"""Converts a list of bytes or an 8-bit string to an integer.
When using unicode strings, encode it to some encoding like UTF8 first.
>>> (((128 * 256) + 64) * 256) + 15
8405007
>>> bytes2int(b'\x80@\x0f')
8405007 | https://github.com/jeeftor/alfredtoday/blob/f6e2c2228caa71015e654e1fdbf552e2ca4f90ad/src/lib/rsa/transform.py#L40-L52 | from __future__ import absolute_import
try:
import psyco
psyco.full()
except ImportError:
pass
import binascii
from struct import pack
from rsa import common
from rsa._compat import is_integer, b, byte, get_word_alignment, ZERO_BYTE, EMPTY_BYTE | MIT License |
nussl/nussl | nussl/separation/spatial/duet.py | Duet._compute_masks | python | def _compute_masks(self):
best_so_far = np.inf * np.ones_like(self.stft_ch0, dtype=float)
for i in range(0, self.num_sources):
mask_array = np.zeros_like(self.stft_ch0, dtype=bool)
phase = np.exp(-1j * self.frequency_matrix * self.delay_peak[i])
score = np.abs(self.at... | Receives the attenuation and delay peaks and computes a mask to be applied to the signal for source
separation. | https://github.com/nussl/nussl/blob/471e7965c5788bff9fe2e1f7884537cae2d18e6f/nussl/separation/spatial/duet.py#L314-L335 | import numpy as np
from scipy import signal
from .. import MaskSeparationBase
from ...core import utils
from ...core import constants
class Duet(MaskSeparationBase):
def __init__(self, input_audio_signal, num_sources,
attenuation_min=-3, attenuation_max=3, num_attenuation_bins=50,
... | MIT License |
bitmovin/bitmovin-api-sdk-python | bitmovin_api_sdk/models/s3_role_based_input.py | S3RoleBasedInput.role_arn | python | def role_arn(self, role_arn):
if role_arn is not None:
if not isinstance(role_arn, string_types):
raise TypeError("Invalid type for `role_arn`, type has to be `string_types`")
self._role_arn = role_arn | Sets the role_arn of this S3RoleBasedInput.
Amazon ARN of the IAM Role (Identity and Access Management Role) that will be assumed for S3 access. This role has to be created by the owner of the account with the S3 bucket (i.e., you as a customer). For Bitmovin to be able to assume this role, the following has ... | https://github.com/bitmovin/bitmovin-api-sdk-python/blob/79dd938804197151af7cbe5501c7ec1d97872c15/bitmovin_api_sdk/models/s3_role_based_input.py#L123-L137 | from enum import Enum
from six import string_types, iteritems
from bitmovin_api_sdk.common.poscheck import poscheck_model
from bitmovin_api_sdk.models.aws_cloud_region import AwsCloudRegion
from bitmovin_api_sdk.models.external_id_mode import ExternalIdMode
from bitmovin_api_sdk.models.input import Input
import pprint
... | MIT License |
zeliu98/group-free-3d | utils/logger.py | setup_logger | python | def setup_logger(
output=None, distributed_rank=0, *, color=True, name="log", abbrev_name=None
):
logger = logging.getLogger(name)
logger.setLevel(logging.DEBUG)
logger.propagate = False
if abbrev_name is None:
abbrev_name = name
plain_formatter = logging.Formatter(
"[%(asctime)s... | Initialize the detectron2 logger and set its verbosity level to "INFO".
Args:
output (str): a file name or a directory to save log. If None, will not save log file.
If ends with ".txt" or ".log", assumed to be a file name.
Otherwise, logs will be saved to `output/log.txt`.
n... | https://github.com/zeliu98/group-free-3d/blob/ef8b7bb5c3bf5b49b957624595dc6a642b6d0036/utils/logger.py#L31-L87 | import functools
import logging
import os
import sys
from termcolor import colored
class _ColorfulFormatter(logging.Formatter):
def __init__(self, *args, **kwargs):
self._root_name = kwargs.pop("root_name") + "."
self._abbrev_name = kwargs.pop("abbrev_name", "")
if len(self._abbrev_name):
... | MIT License |
microsoft/azure-devops-python-api | azure-devops/azure/devops/v6_0/security/security_client.py | SecurityClient.query_security_namespaces | python | def query_security_namespaces(self, security_namespace_id=None, local_only=None):
route_values = {}
if security_namespace_id is not None:
route_values['securityNamespaceId'] = self._serialize.url('security_namespace_id', security_namespace_id, 'str')
query_parameters = {}
if ... | QuerySecurityNamespaces.
[Preview API] List all security namespaces or just the specified namespace.
:param str security_namespace_id: Security namespace identifier.
:param bool local_only: If true, retrieve only local security namespaces.
:rtype: [SecurityNamespaceDescription] | https://github.com/microsoft/azure-devops-python-api/blob/451cade4c475482792cbe9e522c1fee32393139e/azure-devops/azure/devops/v6_0/security/security_client.py#L205-L223 |
from msrest import Serializer, Deserializer
from ...client import Client
from . import models
class SecurityClient(Client):
def __init__(self, base_url=None, creds=None):
super(SecurityClient, self).__init__(base_url, creds)
client_models = {k: v for k, v in models.__dict__.items() if isinstance(v... | MIT License |
chilcote/unearth | artifacts/active_directory_node.py | fact | python | def fact():
result = "None"
net_config = SCDynamicStoreCreate(None, "net", None, None)
d = SCDynamicStoreCopyValue(net_config, "com.apple.opendirectoryd.ActiveDirectory")
if d:
result = d.get("NodeName", None)
return {factoid: result} | Returns Active Directory node | https://github.com/chilcote/unearth/blob/1aaa79195850aac8920efe2d632911d19d998fa3/artifacts/active_directory_node.py#L6-L16 | from SystemConfiguration import SCDynamicStoreCopyValue, SCDynamicStoreCreate
factoid = "active_directory_node" | Apache License 2.0 |
botfront/rasa-for-botfront | rasa/core/actions/forms.py | FormAction.validate_slots | python | async def validate_slots(
self,
slot_candidates: Dict[Text, Any],
tracker: "DialogueStateTracker",
domain: Domain,
output_channel: OutputChannel,
nlg: NaturalLanguageGenerator,
) -> List[Event]:
logger.debug(f"Validating extracted slots: {slot_candidates}")
... | Validate the extracted slots.
If a custom action is available for validating the slots, we call it to validate
them. Otherwise there is no validation.
Args:
slot_candidates: Extracted slots which are candidates to fill the slots required
by the form.
tra... | https://github.com/botfront/rasa-for-botfront/blob/6e0e48d0059e197b5f686df1e27935769c3641b7/rasa/core/actions/forms.py#L378-L427 | from typing import Text, List, Optional, Union, Any, Dict, Tuple, Set
import logging
import json
from rasa.core.actions import action
from rasa.core.actions.loops import LoopAction
from rasa.core.channels import OutputChannel
from rasa.shared.core.domain import Domain, InvalidDomain, SlotMapping
from rasa.core.actions.... | Apache License 2.0 |
fkie/multimaster_fkie | fkie_node_manager/src/fkie_node_manager/select_dialog.py | SelectDialog.__init__ | python | def __init__(self, items=list(), buttons=QDialogButtonBox.Cancel | QDialogButtonBox.Ok, exclusive=False,
preselect_all=False, title='', description='', icon='', parent=None, select_if_single=True,
checkitem1='', checkitem2='', closein=0, store_geometry=''):
QDialog.__init__(sel... | Creates an input dialog.
@param items: a list with strings
@type items: C{list()} | https://github.com/fkie/multimaster_fkie/blob/386ebf27f41bffdb1896bbcfdccb7c5290ac0eb4/fkie_node_manager/src/fkie_node_manager/select_dialog.py#L58-L165 | from python_qt_binding.QtCore import Qt, Signal, QPoint, QSize
try:
from python_qt_binding.QtGui import QCheckBox, QDialog, QFrame, QDialogButtonBox, QLabel, QLineEdit, QScrollArea, QWidget
from python_qt_binding.QtGui import QFormLayout, QHBoxLayout, QVBoxLayout, QSizePolicy, QSpacerItem
except Exception:
... | BSD 3-Clause New or Revised License |
crpurcell/friendlyvri | Imports/util_tk.py | ScrolledTreeTab.get_indx_selected | python | def get_indx_selected(self):
if self.rowSelected is None:
return None
else:
return int(self.rowSelected) | Return the index of the last row selected. | https://github.com/crpurcell/friendlyvri/blob/d30a99622742e06fe8b8b767b170c7353c281a82/Imports/util_tk.py#L186-L192 | try:
import Tkinter as tk
import ttk
import tkFont
except Exception:
import tkinter as tk
from tkinter import ttk
import tkinter.font as tkFont
import numpy as np
from matplotlib.figure import Figure
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
class ScrolledTreeTab(ttk.Frame)... | MIT License |
directgroup/direct | direct/functionals/challenges.py | fastmri_nmse | python | def fastmri_nmse(gt, pred):
gt = _to_numpy(gt)[:, 0, ...]
pred = _to_numpy(pred)[:, 0, ...]
out = np.linalg.norm(gt - pred) ** 2 / np.linalg.norm(gt) ** 2
return torch.from_numpy(np.array(out)).float() | Compute Normalized Mean Square Error metric (NMSE) compatible with the FastMRI challenge. | https://github.com/directgroup/direct/blob/961989bfac0177988de04e8a3ff563db850575e2/direct/functionals/challenges.py#L47-L52 | import numpy as np
import torch
__all__ = (
"fastmri_ssim",
"fastmri_psnr",
"fastmri_nmse",
"calgary_campinas_ssim",
"calgary_campinas_psnr",
"calgary_campinas_vif",
)
def _to_numpy(tensor):
if isinstance(tensor, np.ndarray):
return tensor
return tensor.cpu().numpy()
def fastmri_... | Apache License 2.0 |
gamer-os/steam-buddy | tests/test_downloader.py | empty_data | python | def empty_data(fs):
fs.create_dir(os.path.expanduser('~'))
yield fs | Mock an empty home directory as it should be on the first run | https://github.com/gamer-os/steam-buddy/blob/2df83290d32c03ce71f694166570a2247684e4cd/tests/test_downloader.py#L8-L11 | import os
import json
import pytest
from chimera_app.data import Downloader
@pytest.fixture | MIT License |
seaglass-project/seaglass | common/scan.py | Bcch_Measurement.document | python | def document(self):
doc = {}
doc['arfcn'] = int(self.arfcn)
doc['rx_lev'] = int(self.rx_lev)
doc['measurement_blob'] = self.blob
bcch = {}
bcch['num_channels'] = int(self.num_channels)
bcch['num_arfcn'] = int(self.num_arfcn)
format_channels = []
fo... | This makes a nice formated document that can be inserted to mongo | https://github.com/seaglass-project/seaglass/blob/04ae18807d188b211167acdb329050a173cba0ba/common/scan.py#L332-L382 | import copy
GPS_FIELDS = ['mode',
'time',
'ept',
'lat',
'lon',
'alt',
'epx',
'epy',
'cpv',
'track',
'speed',
'climb',
'epd',
'eps',
... | BSD 3-Clause New or Revised License |
henriquemiranda/yambopy | yambopy/io/factories.py | PhPhononTasks | python | def PhPhononTasks(structure,kpoints,ecut,qpoints=None):
qe_input = PwIn.from_structure_dict(structure,kpoints=kpoints,ecut=ecut)
qe_scf_task = PwTask.from_input(qe_input)
if qpoints is None: qpoints = qe_input.kpoints
ph_input = PhIn.from_qpoints(qpoints)
ph_task = PhTask.from_scf_task([ph_input,qe_... | Return a ScfTask, a PhTask and Matdyn task | https://github.com/henriquemiranda/yambopy/blob/41b860c47e95a0d65be2a138b0043278508caee9/yambopy/io/factories.py#L425-L442 | from qepy.pw import PwIn
from qepy.ph import PhIn
from qepy.pwxml import PwXML
from qepy.lattice import *
from qepy.matdyn import Matdyn
from qepy import qepyenv
from yambopy.io.inputfile import YamboIn
from yambopy.tools.duck import isiter
from yambopy.flow import PwTask, PhTask, P2yTask, YamboTask, DynmatTask, Yambop... | BSD 3-Clause New or Revised License |
globocom/globonetworkapi-client-python | networkapiclient/ApiEnvironmentVip.py | ApiEnvironmentVip.__init__ | python | def __init__(self, networkapi_url, user, password, user_ldap=None):
super(ApiEnvironmentVip, self).__init__(
networkapi_url,
user,
password,
user_ldap
) | Class constructor receives parameters to connect to the networkAPI.
:param networkapi_url: URL to access the network API.
:param user: User for authentication.
:param password: Password for authentication. | https://github.com/globocom/globonetworkapi-client-python/blob/08dc24c54ee3cd6cdcca1fb33fb4796db8118e6f/networkapiclient/ApiEnvironmentVip.py#L22-L34 | from networkapiclient.ApiGenericClient import ApiGenericClient
from networkapiclient.utils import build_uri_with_ids
class ApiEnvironmentVip(ApiGenericClient): | Apache License 2.0 |
azure/azure-devops-cli-extension | azure-devops/azext_devops/devops_sdk/v5_1/task/task_client.py | TaskClient.delete_timeline | python | def delete_timeline(self, scope_identifier, hub_name, plan_id, timeline_id):
route_values = {}
if scope_identifier is not None:
route_values['scopeIdentifier'] = self._serialize.url('scope_identifier', scope_identifier, 'str')
if hub_name is not None:
route_values['hubNam... | DeleteTimeline.
:param str scope_identifier: The project GUID to scope the request
:param str hub_name: The name of the server hub: "build" for the Build server or "rm" for the Release Management server
:param str plan_id:
:param str timeline_id: | https://github.com/azure/azure-devops-cli-extension/blob/5f33f7d81a9c2d2990044fbd9ffa6b535cbda528/azure-devops/azext_devops/devops_sdk/v5_1/task/task_client.py#L376-L395 |
from msrest import Serializer, Deserializer
from ...client import Client
from . import models
class TaskClient(Client):
def __init__(self, base_url=None, creds=None):
super(TaskClient, self).__init__(base_url, creds)
client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)}... | MIT License |
rwbfd/opencompetition | src/nlp/common/networks/modeling_auto.py | AutoModelForSequenceClassification.from_config | python | def from_config(cls, config):
if isinstance(config, AlbertConfig):
return AlbertForSequenceClassification(config)
elif isinstance(config, CamembertConfig):
return CamembertForSequenceClassification(config)
elif isinstance(config, DistilBertConfig):
return Dist... | r""" Instantiates one of the base model classes of the library
from a configuration.
config: (`optional`) instance of a class derived from :class:`~transformers.PretrainedConfig`:
The model class to instantiate is selected based on the configuration class:
- isIn... | https://github.com/rwbfd/opencompetition/blob/5262fc5fa7efd7b483c1dc09cb7747dd75e37175/src/nlp/common/networks/modeling_auto.py#L554-L587 | import logging
from .configuration_auto import (
AlbertConfig,
BertConfig,
CamembertConfig,
CTRLConfig,
DistilBertConfig,
GPT2Config,
OpenAIGPTConfig,
RobertaConfig,
TransfoXLConfig,
XLMConfig,
XLMRobertaConfig,
XLNetConfig,
)
from .modeling_albert import (
ALBERT_PRE... | Apache License 2.0 |
mlindauer/autofolio | autofolio/feature_preprocessing/standardscaler.py | StandardScalerWrapper.fit | python | def fit(self, scenario: ASlibScenario, config: Configuration):
if config.get("StandardScaler"):
self.active = True
self.scaler = StandardScaler()
self.scaler.fit(scenario.feature_data.values) | fit StandardScaler object to ASlib scenario data
Arguments
---------
scenario: data.aslib_scenario.ASlibScenario
ASlib Scenario with all data in pandas
config: ConfigSpace.Configuration
configuration | https://github.com/mlindauer/autofolio/blob/f296f528b1b684d36837075b0e8160e3fa4124f7/autofolio/feature_preprocessing/standardscaler.py#L39-L54 | import logging
import numpy as np
import pandas as pd
from sklearn.preprocessing import StandardScaler
from ConfigSpace.hyperparameters import CategoricalHyperparameter, UniformFloatHyperparameter, UniformIntegerHyperparameter
from ConfigSpace.conditions import EqualsCondition, InCondition
from ConfigSpace.configura... | BSD 2-Clause Simplified License |
capitalone/rubicon | rubicon_ml/repository/base.py | BaseRepository.create_artifact | python | def create_artifact(self, artifact, data, project_name, experiment_id=None):
artifact_metadata_path = self._get_artifact_metadata_path(
project_name, experiment_id, artifact.id
)
artifact_data_path = self._get_artifact_data_path(project_name, experiment_id, artifact.id)
self.... | Persist an artifact to the configured filesystem.
Parameters
----------
artifact : rubicon.domain.Artifact
The artifact to persist.
data : bytes
The raw data to persist as an artifact.
project_name : str
The name of the project this artifact b... | https://github.com/capitalone/rubicon/blob/86278a98cf5fd0b7e179a2949fce5a12e42fd7be/rubicon_ml/repository/base.py#L247-L268 | import os
import warnings
from pathlib import Path
import fsspec
import pandas as pd
from dask import dataframe as dd
from rubicon_ml import domain
from rubicon_ml.exceptions import RubiconException
from rubicon_ml.repository.utils import json, slugify
class BaseRepository:
def __init__(self, root_dir, **storage_op... | Apache License 2.0 |
cloud-bulldozer/benchmark-wrapper | snafu/fio_wrapper/fio_analyzer.py | Fio_Analyzer.add_fio_result_documents | python | def add_fio_result_documents(self, document_list, starttime):
for document in document_list:
fio_result = {}
fio_result["document"] = document
fio_result["starttime"] = starttime
self.fio_processed_results_list.append(fio_result) | for each new document add it to the results list with its starttime | https://github.com/cloud-bulldozer/benchmark-wrapper/blob/032b0920397888bbae1a62ca27fae28d1be4537c/snafu/fio_wrapper/fio_analyzer.py#L23-L31 | import statistics
import time
class Fio_Analyzer:
def __init__(self, uuid, user, cluster_name):
self.uuid = uuid
self.user = user
self.fio_processed_results_list = []
self.sample_list = []
self.operation_list = []
self.io_size_list = []
self.sumdoc = {}
... | Apache License 2.0 |
chronicle/detection-api | detect/v2/delete_rule.py | delete_rule | python | def delete_rule(http_session: requests.AuthorizedSession, rule_id: str):
url = f"{CHRONICLE_API_BASE_URL}/v2/detect/rules/{rule_id}"
response = http_session.request("DELETE", url)
if response.status_code >= 400:
print(response.text)
response.raise_for_status() | Delete a specific detection rule.
Args:
http_session: Authorized session for HTTP requests.
rule_id: Unique ID of the detection rule to delete ("ru_<UUID>"). It does
not accept version id format ("ru_<UUID>@v_<seconds>_<nanoseconds>").
Raises:
requests.exceptions.HTTPError: HTTP request resulted... | https://github.com/chronicle/detection-api/blob/f0ec1f837c0c1e6af68d003dcd6c5774e524bba5/detect/v2/delete_rule.py#L33-L53 | import argparse
from google.auth.transport import requests
from common import chronicle_auth
from common import regions
CHRONICLE_API_BASE_URL = "https://backstory.googleapis.com" | Apache License 2.0 |
intel/openfl | openfl/cryptography/participant.py | generate_csr | python | def generate_csr(common_name, server=False):
private_key = rsa.generate_private_key(
public_exponent=65537,
key_size=3072,
backend=default_backend()
)
builder = x509.CertificateSigningRequestBuilder()
subject = x509.Name([
x509.NameAttribute(NameOID.COMMON_NAME, common_na... | Issue certificate signing request for server and client. | https://github.com/intel/openfl/blob/4bda3850b6bce7c904a5ac3ed56115bec00be2e0/openfl/cryptography/participant.py#L13-L68 | from cryptography import x509
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.asymmetric import rsa
from cryptography.x509.oid import NameOID | Apache License 2.0 |
jgraving/deepposekit | deepposekit/models/LEAP.py | LEAP.__init__ | python | def __init__(
self,
train_generator,
filters=64,
upsampling=False,
activation="relu",
batchnorm=False,
use_bias=True,
pooling="max",
interpolation="bilinear",
subpixel=False,
initializer="glorot_uniform",
**kwargs
):
... | Define a LEAP model from Pereira et al., 2018 [1]
See `References` for details on the model architecture.
Parameters
----------
train_generator : class deepposekit.io.TrainingGenerator
A deepposekit.io.TrainingGenerator class for generating
images and confidence ... | https://github.com/jgraving/deepposekit/blob/cecdb0c8c364ea049a3b705275ae71a2f366d4da/deepposekit/models/LEAP.py#L26-L115 | from tensorflow.keras import Input, Model
from tensorflow.keras.layers import Conv2D, Conv2DTranspose, BatchNormalization
from deepposekit.models.layers.convolutional import UpSampling2D
from deepposekit.models.layers.util import ImageNormalization
from deepposekit.models.layers.leap import ConvBlock2D, ConvPool2D
from... | Apache License 2.0 |
halit/isip | isip/scapy/contrib/gsm_um.py | systemInformationType2 | python | def systemInformationType2():
a = L2PseudoLength(l2pLength=0x16)
b = TpPd(pd=0x6)
c = MessageType(mesType=0x1a)
d = NeighbourCellsDescription()
e = NccPermitted()
f = RachControlParameters()
packet = a / b / c / d / e / f
return packet | SYSTEM INFORMATION TYPE 2 Section 9.1.32 | https://github.com/halit/isip/blob/fad1f10b02f9e075451588cc6a18a46cc5fbd66b/isip/scapy/contrib/gsm_um.py#L997-L1006 | import logging
from types import IntType
from types import NoneType
from types import StringType
import socket
logging.getLogger("scapy").setLevel(1)
from scapy.all import *
def sendum(x, typeSock=0):
try:
if type(x) is not str:
x = str(x)
if typeSock is 0:
s = socket.socket(... | MIT License |
sergioteula/python-amazon-paapi | amazon/paapi5_python_sdk/offer_listing.py | OfferListing.price | python | def price(self):
return self._price | Gets the price of this OfferListing. # noqa: E501
:return: The price of this OfferListing. # noqa: E501
:rtype: OfferPrice | https://github.com/sergioteula/python-amazon-paapi/blob/9cb744bef17f5127231367430191df12126e9c24/amazon/paapi5_python_sdk/offer_listing.py#L273-L280 | import pprint
import re
import six
from .offer_availability import OfferAvailability
from .offer_condition import OfferCondition
from .offer_delivery_info import OfferDeliveryInfo
from .offer_loyalty_points import OfferLoyaltyPoints
from .offer_merchant_info import OfferMerchantInfo
from .offer_price import... | MIT License |
pelioniot/mbed-cloud-sdk-python | src/mbed_cloud/_backends/update_service/models/firmware_image_eq_neq_filter.py | FirmwareImageEqNeqFilter.datafile | python | def datafile(self, datafile):
self._datafile = datafile | Sets the datafile of this FirmwareImageEqNeqFilter.
:param datafile: The datafile of this FirmwareImageEqNeqFilter.
:type: str | https://github.com/pelioniot/mbed-cloud-sdk-python/blob/71dc67fc2a8d1aff31e35ec781fb328e6a60639c/src/mbed_cloud/_backends/update_service/models/firmware_image_eq_neq_filter.py#L105-L113 | from pprint import pformat
from six import iteritems
import re
class FirmwareImageEqNeqFilter(object):
"""
Attributes:
swagger_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
... | Apache License 2.0 |
autorope/donkeycar | donkeycar/parts/keras.py | conv2d | python | def conv2d(filters, kernel, strides, layer_num, activation='relu'):
return Convolution2D(filters=filters,
kernel_size=(kernel, kernel),
strides=(strides, strides),
activation=activation,
name='conv2d_' + str(layer_nu... | Helper function to create a standard valid-padded convolutional layer
with square kernel and strides and unified naming convention
:param filters: channel dimension of the layer
:param kernel: creates (kernel, kernel) kernel matrix dimension
:param strides: creates (strides, strides) strid... | https://github.com/autorope/donkeycar/blob/688204ca074886321e0d58e75d81d89f04f7a2b6/donkeycar/parts/keras.py#L907-L923 | from abc import ABC, abstractmethod
from collections import deque
import numpy as np
from typing import Dict, Tuple, Optional, Union, List, Sequence, Callable
from logging import getLogger
from tensorflow.python.data.ops.dataset_ops import DatasetV1, DatasetV2
import donkeycar as dk
from donkeycar.utils import normaliz... | MIT License |
rlabbe/filterpy | filterpy/kalman/square_root.py | SquareRootKalmanFilter.Q1_2 | python | def Q1_2(self):
return self._Q1_2 | Sqrt Process uncertainty | https://github.com/rlabbe/filterpy/blob/a437893597957764fb6b415bfb5640bb117f5b99/filterpy/kalman/square_root.py#L281-L283 | from __future__ import (absolute_import, division)
from copy import deepcopy
import numpy as np
from numpy import dot, zeros, eye
from scipy.linalg import cholesky, qr, pinv
from filterpy.common import pretty_str
class SquareRootKalmanFilter(object):
def __init__(self, dim_x, dim_z, dim_u=0):
if dim_z < 1:
... | MIT License |
sk2/ank_legacy_v2 | AutoNetkit/netkit.py | Netkit.connect_to_server | python | def connect_to_server(self):
shell = None
if self.host and self.username:
ssh_link = self.shell
if ssh_link != None:
return ssh_link
shell = pxssh.pxssh()
shell.logfile = self.logfile
LOG.info( "Connecting to {0}"... | Connects to Netkit server (if remote) | https://github.com/sk2/ank_legacy_v2/blob/83a28aa54a4ea74962ee9a8c44f856a006a2e675/AutoNetkit/netkit.py#L102-L147 | __author__ = """\n""".join(['Simon Knight (simon.knight@adelaide.edu.au)',
'Hung Nguyen (hung.nguyen@adelaide.edu.au)'])
import config
import logging
LOG = logging.getLogger("ANK")
try:
import pexpect
import pxssh
except ImportError:
LOG.error("Netkit deployment requires pexpect"... | BSD 3-Clause New or Revised License |
deepmind/xmanager | xmanager/xm/core.py | Experiment.add | python | def add(self, job, args=immutabledict.immutabledict(), role=WorkUnitRole()):
experiment_unit = self._create_experiment_unit(args, role)
async def launch():
await experiment_unit.add(job, args)
return experiment_unit
return asyncio.wrap_future(self._create_task(launch())) | Adds a Job / JobGroup to the experiment.
A new Experiment Unit is created to run the job.
Args:
job: A Job or JobGroup to add.
args: Keyword arguments to be passed to the job. For Job and JobGroup args
are recursively expanded. For example,
```
wu.add(
JobGroup... | https://github.com/deepmind/xmanager/blob/4963986b77228bed72afcb6ada7008a7eb3a1393/xmanager/xm/core.py#L541-L572 | import abc
import asyncio
from concurrent import futures
import functools
import getpass
import inspect
import queue
import threading
from typing import Any, Awaitable, Callable, Dict, Mapping, Optional, Sequence, overload
import attr
import immutabledict
from xmanager.xm import async_packager
from xmanager.xm import i... | Apache License 2.0 |
tensorflow/data-validation | tensorflow_data_validation/utils/stats_util.py | load_stats_binary | python | def load_stats_binary(
input_path: Text) -> statistics_pb2.DatasetFeatureStatisticsList:
stats_proto = statistics_pb2.DatasetFeatureStatisticsList()
stats_proto.ParseFromString(io_util.read_file_to_string(
input_path, binary_mode=True))
return stats_proto | Loads a serialized DatasetFeatureStatisticsList proto from a file.
Args:
input_path: File path from which to load the DatasetFeatureStatisticsList
proto.
Returns:
A DatasetFeatureStatisticsList proto. | https://github.com/tensorflow/data-validation/blob/9855619b40a1c6dab2be3509fa252eaea5120596/tensorflow_data_validation/utils/stats_util.py#L220-L234 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import logging
from typing import Dict, Optional, Text, Union
import numpy as np
import pyarrow as pa
import tensorflow as tf
from tensorflow_data_validation import types
from tensorflow_data_validation.arrow im... | Apache License 2.0 |
numan/py-analytics | analytics/backends/base.py | BaseAnalyticsBackend.get_metrics | python | def get_metrics(self, metric_identifiers, from_date, limit=10, group_by="week", **kwargs):
raise NotImplementedError() | Retrieves a multiple metrics as efficiently as possible.
:param metric_identifiers: a list of tuples of the form `(unique_identifier, metric_name`) identifying which metrics to retrieve.
For example [('user:1', 'people_invited',), ('user:2', 'people_invited',), ('user:1', 'comments_posted',), ('user:2'... | https://github.com/numan/py-analytics/blob/abbc814925c6cc200b3329c7de9f1868e1cb8c01/analytics/backends/base.py#L91-L101 | class BaseAnalyticsBackend(object):
_analytics_backend = None
_prefix = "_analytics"
def __init__(self, settings, **kwargs):
if "prefix" in kwargs:
self._prefix = kwargs.get("prefix")
def track_count(self, unique_identifier, metric, inc_amt=1, **kwargs):
return NotImplemented... | Apache License 2.0 |
imicknl/ha-tahoma | custom_components/tahoma/climate_devices/somfy_thermostat.py | SomfyThermostat.async_set_hvac_mode | python | async def async_set_hvac_mode(self, hvac_mode: str) -> None:
if hvac_mode == self.hvac_mode:
return
if hvac_mode == HVAC_MODE_AUTO:
self._saved_target_temp = self.target_temperature
await self.executor.async_execute_command(COMMAND_EXIT_DEROGATION)
await s... | Set new target hvac mode. | https://github.com/imicknl/ha-tahoma/blob/a0490949f7f416a59019582459aa70c1de108258/custom_components/tahoma/climate_devices/somfy_thermostat.py#L223-L232 | import logging
from typing import Optional
from homeassistant.components.climate import ClimateEntity
from homeassistant.components.climate.const import (
CURRENT_HVAC_HEAT,
CURRENT_HVAC_IDLE,
HVAC_MODE_AUTO,
HVAC_MODE_HEAT,
PRESET_AWAY,
PRESET_HOME,
PRESET_NONE,
SUPPORT_PRESET_MODE,
... | MIT License |
ganeti/ganeti | lib/mcpu.py | Processor._AcquireLocks | python | def _AcquireLocks(self, level, names, shared, opportunistic, timeout,
opportunistic_count=1, request_only=False):
self._CheckLocksEnabled()
if self._cbs:
priority = self._cbs.CurrentPriority()
else:
priority = None
if priority is None:
priority = constants.OP_PRIO_... | Acquires locks via the Ganeti lock manager.
@type level: int
@param level: Lock level
@type names: list or string
@param names: Lock names
@type shared: bool
@param shared: Whether the locks should be acquired in shared mode
@type opportunistic: bool
@param opportunistic: Whether to acq... | https://github.com/ganeti/ganeti/blob/4d21019c72cba4d746f5d17ca22098f4c7682e9c/lib/mcpu.py#L374-L475 | import sys
import logging
import random
import time
import itertools
import traceback
from ganeti import opcodes
from ganeti import opcodes_base
from ganeti import constants
from ganeti import errors
from ganeti import hooksmaster
from ganeti import cmdlib
from ganeti import locking
from ganeti import utils
from ganeti... | BSD 2-Clause Simplified License |
fxihub/hummingbird | src/backend/euxfel.py | EUxfelTrainTranslator._tr_event_id_sqs_pnccd | python | def _tr_event_id_sqs_pnccd(self, values, obj):
timestamp = numpy.array(obj['timestamp.tid'], dtype='int')
rec = Record('Timestamp', timestamp, ureg.s)
rec.timestamp = [timestamp]
values[rec.name] = rec | Translates euxfel train event ID from data source into a hummingbird one | https://github.com/fxihub/hummingbird/blob/0b1bdf5023b92090f31d9bc857e0854a805cf2cd/src/backend/euxfel.py#L326-L333 | from __future__ import print_function
import os
import numpy
import datetime, time
from pytz import timezone
from backend.event_translator import EventTranslator
from backend.record import Record, add_record
from backend import Worker
from . import ureg
import logging
import ipc
import karabo_bridge
import numpy
from ... | BSD 2-Clause Simplified License |
skype4py/skype4py | Skype4Py/client.py | Client.OpenSearchDialog | python | def OpenSearchDialog(self):
self.OpenDialog('SEARCH') | Opens search dialog. | https://github.com/skype4py/skype4py/blob/c48d83f7034109fe46315d45a066126002c6e0d4/Skype4Py/client.py#L222-L225 | __docformat__ = 'restructuredtext en'
import weakref
from enums import *
from errors import SkypeError
from utils import *
class Client(object):
def __init__(self, Skype):
self._SkypeRef = weakref.ref(Skype)
def ButtonPressed(self, Key):
self._Skype._DoCommand('BTN_PRESSED %s' % Key)
def But... | BSD 3-Clause New or Revised License |
googleapis/python-compute | google/cloud/compute_v1/services/url_maps/transports/rest.py | UrlMapsRestTransport.patch | python | def patch(
self,
request: compute.PatchUrlMapRequest,
*,
metadata: Sequence[Tuple[str, str]] = (),
) -> compute.Operation:
body = compute.UrlMap.to_json(
request.url_map_resource,
including_default_value_fields=False,
use_integers_for_enums... | r"""Call the patch method over HTTP.
Args:
request (~.compute.PatchUrlMapRequest):
The request object. A request message for UrlMaps.Patch.
See the method description for details.
metadata (Sequence[Tuple[str, str]]): Strings which should be
... | https://github.com/googleapis/python-compute/blob/703ac1703bc159dcd81e96759606ad896f125996/google/cloud/compute_v1/services/url_maps/transports/rest.py#L533-L614 | import warnings
from typing import Callable, Dict, Optional, Sequence, Tuple
from google.api_core import gapic_v1
from google.api_core import exceptions as core_exceptions
from google.auth import credentials as ga_credentials
from google.auth.transport.grpc import SslCredentials
import grpc
from google.auth.t... | Apache License 2.0 |
autonomousvision/data_aggregation | configs/coil_global.py | set_type_of_process | python | def set_type_of_process(process_type, param=None):
if _g_conf.PROCESS_NAME == "default":
raise RuntimeError(" You should merge with some exp file before setting the type")
if process_type == 'train':
_g_conf.PROCESS_NAME = process_type
elif process_type == "validation":
_g_conf.PROCE... | This function is used to set which is the type of the current process, test, train or val
and also the details of each since there could be many vals and tests for a single
experiment.
NOTE: AFTER CALLING THIS FUNCTION, THE CONFIGURATION CLOSES
Args:
type:
Returns: | https://github.com/autonomousvision/data_aggregation/blob/76777156a465cbb77d6d5ab88da8f1812e7ff043/configs/coil_global.py#L151-L208 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from ast import literal_eval
from coilutils import AttributeDict
import copy
import numpy as np
import os
import yaml
from configs.namer import generate_name
from logger.c... | MIT License |
pyglet/pyglet | pyglet/text/runlist.py | AbstractRunIterator.__getitem__ | python | def __getitem__(self, index): | Get the value at a given index.
See the class documentation for examples of valid usage.
:Parameters:
`index` : int
Document position to query.
:rtype: object | https://github.com/pyglet/pyglet/blob/b9a63ea179735c8f252ac31d51751bdf8a741c9d/pyglet/text/runlist.py#L262-L272 | class _Run:
def __init__(self, value, count):
self.value = value
self.count = count
def __repr__(self):
return 'Run(%r, %d)' % (self.value, self.count)
class RunList:
def __init__(self, size, initial):
self.runs = [_Run(initial, size)]
def insert(self, pos, length):
... | BSD 3-Clause New or Revised License |
maralla/completor.vim | pythonx/completor/__init__.py | Completor.gen_request | python | def gen_request(self, action=b'complete', args=None):
req = self.prepare_request(action=action)
if req and req[-1] != '\n':
req += '\n'
return req | Internal wrapper for preparing a request. | https://github.com/maralla/completor.vim/blob/6ca5f498afe5fe9c659751aef54ef7f2fdc62414/pythonx/completor/__init__.py#L373-L379 | import importlib
import json
import logging
import os
import re
import shlex
import threading
from os.path import expanduser
from ._vim import vim_obj as vim
from ._vim import vim_expand, vim_tempname, vim_support_popup, vim_action_trigger, vim_in_comment_or_string, vim_daemon_send
from ._vim import vim_exists
fro... | MIT License |
crypto-toolbox/btfxwss | btfxwss/client.py | BtfxWss.trades | python | def trades(self, pair):
key = ('trades', pair)
return self.queue_processor.trades[key] | Return a queue containing all received trades data.
:param pair:
:return: Queue() | https://github.com/crypto-toolbox/btfxwss/blob/16827fa6aacb2c0e289aa852bf61a18df6905835/btfxwss/client.py#L122-L129 | import logging
import time
from btfxwss.connection import WebSocketConnection
from btfxwss.queue_processor import QueueProcessor
log = logging.getLogger(__name__)
def is_connected(func):
def wrapped(self, *args, **kwargs):
if self.conn and self.conn.connected.is_set():
return func(self, *args, *... | MIT License |
griquelme/tidyms | tidyms/lcms.py | _build_roi | python | def _build_roi(roi: _TemporaryRoi, rt: np.ndarray, valid_scan: np.ndarray,
start: int, mode: str) -> Roi:
first_scan = roi.scan[0]
last_scan = roi.scan[-1]
size = last_scan + 1 - first_scan
mz_tmp = np.ones(size) * np.nan
spint_tmp = mz_tmp.copy()
scan_index = np.array(roi.scan) -... | Convert to a ROI object
Parameters
----------
rt: array
array of retention times associated to each scan
valid_scan : array
array of scans associated used to build the Rois.
start : int first scan used to create ROI
mode : mode to pass to ROI creation.
Returns
------- | https://github.com/griquelme/tidyms/blob/dd8e6f3ea60dea8efca0fb6bac73362b2a2457be/tidyms/lcms.py#L904-L956 | import bokeh.plotting
import numpy as np
import pyopenms
from collections import deque
from collections import namedtuple
from scipy.interpolate import interp1d
from scipy.ndimage import gaussian_filter1d
from typing import Optional, Iterable, Tuple, Union, List, Callable
from . import peaks
from . import _plot_bokeh
f... | BSD 3-Clause New or Revised License |
vitruvianscience/opendeep | opendeep/utils/midi/MidiOutFile.py | MidiOutFile.sequencer_specific | python | def sequencer_specific(self, data):
self.meta_slice(SEQUENCER_SPECIFIC, data) | data: The data as byte values | https://github.com/vitruvianscience/opendeep/blob/e96efc449101094354b615cf15afe6d03644fc36/opendeep/utils/midi/MidiOutFile.py#L313-L317 | from __future__ import absolute_import
from .MidiOutStream import MidiOutStream
from .RawOutstreamFile import RawOutstreamFile
from .constants import *
from .DataTypeConverters import fromBytes, writeVar
class MidiOutFile(MidiOutStream):
def __init__(self, raw_out=''):
self.raw_out = RawOutstreamFile(raw_ou... | Apache License 2.0 |
inmanta/inmanta-core | src/inmanta/parser/plyInmantaParser.py | p_entity_body_outer_1 | python | def p_entity_body_outer_1(p: YaccProduction) -> None:
p[0] = (None, p[1]) | entity_body_outer : entity_body END | https://github.com/inmanta/inmanta-core/blob/7e57295314e30276204b74ddcb8e2402c0a50b19/src/inmanta/parser/plyInmantaParser.py#L257-L259 | import logging
import re
from typing import List, Optional, Union
import ply.yacc as yacc
from ply.yacc import YaccProduction
import inmanta.warnings as inmanta_warnings
from inmanta.ast import LocatableString, Location, Namespace, Range
from inmanta.ast.blocks import BasicBlock
from inmanta.ast.constraint.expression i... | Apache License 2.0 |
openstack/cinder | cinder/backup/chunkeddriver.py | ChunkedBackupDriver._calculate_sha | python | def _calculate_sha(self, data):
chunk = memoryview(data)
shalist = []
off = 0
datalen = len(chunk)
while off < datalen:
chunk_end = min(datalen, off + self.sha_block_size_bytes)
block = chunk[off:chunk_end]
sha = hashlib.sha256(block).hexdigest... | Calculate SHA256 of a data chunk.
This method cannot log anything as it is called on a native thread. | https://github.com/openstack/cinder/blob/4558e4b53a7e41dc1263417a4824f39bb6fd30e1/cinder/backup/chunkeddriver.py#L484-L501 | import abc
import hashlib
import json
import os
import sys
import eventlet
from oslo_config import cfg
from oslo_log import log as logging
from oslo_service import loopingcall
from oslo_utils import excutils
from oslo_utils import secretutils
from oslo_utils import units
from cinder.backup import driver
from cinder imp... | Apache License 2.0 |
autonomousvision/convolutional_occupancy_networks | src/common.py | get_nearest_neighbors_indices_batch | python | def get_nearest_neighbors_indices_batch(points_src, points_tgt, k=1):
indices = []
distances = []
for (p1, p2) in zip(points_src, points_tgt):
kdtree = KDTree(p2)
dist, idx = kdtree.query(p1, k=k)
indices.append(idx)
distances.append(dist)
return indices, distances | Returns the nearest neighbors for point sets batchwise.
Args:
points_src (numpy array): source points
points_tgt (numpy array): target points
k (int): number of nearest neighbors to return | https://github.com/autonomousvision/convolutional_occupancy_networks/blob/f44d413f8d455657a44c24d06163934c69141a09/src/common.py#L125-L142 | import torch
from src.utils.libkdtree import KDTree
import numpy as np
import math
def compute_iou(occ1, occ2):
occ1 = np.asarray(occ1)
occ2 = np.asarray(occ2)
if occ1.ndim >= 2:
occ1 = occ1.reshape(occ1.shape[0], -1)
if occ2.ndim >= 2:
occ2 = occ2.reshape(occ2.shape[0], -1)
occ1 = (... | MIT License |
tongchangd/text_data_enhancement_with_lasertagger | transformer_decoder.py | DecoderStack.call | python | def call(self, decoder_inputs, encoder_outputs, decoder_self_attention_bias,
attention_bias=None, cache=None):
for n, layer in enumerate(self.layers):
self_attention_layer = layer[0]
feed_forward_network = layer[1]
proj_layer = layer[2]
decoder_inputs = tf.concat([decoder_inputs, ... | Returns the output of the decoder layer stacks.
Args:
decoder_inputs: tensor with shape [batch_size, target_length, hidden_size]
encoder_outputs: tensor with shape [batch_size, input_length, hidden_size]
decoder_self_attention_bias: bias for decoder self-attention layer.
[1, 1, target_len... | https://github.com/tongchangd/text_data_enhancement_with_lasertagger/blob/b8286196e2f0e1decf73da79c665f25bf8a0ff45/transformer_decoder.py#L173-L212 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from typing import Any, Mapping, Text
import tensorflow as tf
from official_transformer import attention_layer
from official_transformer import embedding_layer
from official_transformer import ffn_layer
from off... | Apache License 2.0 |
googleads/google-ads-python | google/ads/googleads/v7/services/services/ad_group_audience_view_service/client.py | AdGroupAudienceViewServiceClientMeta.get_transport_class | python | def get_transport_class(
cls, label: str = None,
) -> Type[AdGroupAudienceViewServiceTransport]:
if label:
return cls._transport_registry[label]
return next(iter(cls._transport_registry.values())) | Return an appropriate transport class.
Args:
label: The name of the desired transport. If none is
provided, then the first transport in the registry is used.
Returns:
The transport class to use. | https://github.com/googleads/google-ads-python/blob/6794993e146abcfe21292677144c66cb546446bc/google/ads/googleads/v7/services/services/ad_group_audience_view_service/client.py#L56-L74 | from collections import OrderedDict
from distutils import util
import os
import re
from typing import Dict, Optional, Sequence, Tuple, Type, Union
from google.api_core import client_options as client_options_lib
from google.api_core import exceptions
from google.api_core import gapic_v1
from google.api_core impor... | Apache License 2.0 |
ibm/superglue-mtl | scripts/rewritting_utils.py | ConstituencyRule.gen_neg_output | python | def gen_neg_output(self, fmt_args, ans, entity_mentions):
neg_output = []
ans_type = None
for ent, ne_type in entity_mentions:
if ans == ent:
ans_type = ne_type
break
if ans_type is None: return []
possible_alternatives = []
for ent, ne_type in e... | switch the NE in ans with another entity of the same type | https://github.com/ibm/superglue-mtl/blob/1eb3e581c0ef3b4c261e0256ec26116d2b657c40/scripts/rewritting_utils.py#L216-L259 | from nltk.corpus import wordnet as wn
import corenlp_utils as corenlp
import sys
MODULE = "../resources/pattern-2.6/"
sys.path.append(MODULE)
from pattern import en as patten
POS_TO_WORDNET = {
'NN': wn.NOUN,
'JJ': wn.ADJ,
'JJR': wn.ADJ,
'JJS': wn.ADJ,
}
POS_TO_PATTERN = {
'vb': 'inf',
'vbp': ... | Apache License 2.0 |
balanced/status.balancedpayments.com | venv/lib/python2.7/site-packages/twilio/rest/resources/phone_numbers.py | PhoneNumber.transfer | python | def transfer(self, account_sid):
a = self.parent.transfer(self.name, account_sid)
self.load(a.__dict__) | Transfer the phone number with sid from the current account to another
identified by account_sid | https://github.com/balanced/status.balancedpayments.com/blob/e51a371079a8fa215732be3cfa57497a9d113d35/venv/lib/python2.7/site-packages/twilio/rest/resources/phone_numbers.py#L74-L80 | import re
from twilio import TwilioException
from twilio.rest.resources.util import change_dict_key, transform_params
from twilio.rest.resources import InstanceResource, ListResource
class AvailablePhoneNumber(InstanceResource):
def __init__(self, parent):
super(AvailablePhoneNumber, self).__init__(parent, ... | MIT License |
bdtinc/maskcam | server/backend/app/db/cruds/crud_device.py | get_devices | python | def get_devices(db_session: Session) -> List[DeviceModel]:
return db_session.query(DeviceModel).all() | Get all devices.
Arguments:
db_session {Session} -- Database session.
Returns:
List[DeviceModel] -- All device instances present in the database. | https://github.com/bdtinc/maskcam/blob/4841c2c49235844765e8c2164f5dd03a7d28bdad/server/backend/app/db/cruds/crud_device.py#L83-L93 | from typing import List, Union, Dict
from app.db.schema import DeviceModel
from sqlalchemy.exc import IntegrityError
from sqlalchemy.orm import Session
from sqlalchemy.orm.exc import NoResultFound
def create_device(
db_session: Session, device_information: Dict = {}
) -> Union[DeviceModel, IntegrityError]:
try:... | MIT License |
opennetworkingfoundation/tapi | RI/flask_server/tapi_server/models/tapi_topology_validation_mechanism.py | TapiTopologyValidationMechanism.validation_mechanism | python | def validation_mechanism(self):
return self._validation_mechanism | Gets the validation_mechanism of this TapiTopologyValidationMechanism.
Name of mechanism used to validate adjacency # noqa: E501
:return: The validation_mechanism of this TapiTopologyValidationMechanism.
:rtype: str | https://github.com/opennetworkingfoundation/tapi/blob/1f3fd9483d5674552c5a31206c97399c8c151897/RI/flask_server/tapi_server/models/tapi_topology_validation_mechanism.py#L79-L87 | from __future__ import absolute_import
from datetime import date, datetime
from typing import List, Dict
from tapi_server.models.base_model_ import Model
from tapi_server import util
class TapiTopologyValidationMechanism(Model):
def __init__(self, layer_protocol_adjacency_validated=None, validation_mechanism=No... | Apache License 2.0 |
alephdata/followthemoney | followthemoney/graph.py | Graph.add | python | def add(self, proxy: EntityProxy) -> None:
if proxy is None:
return
self.queue(proxy.id, proxy)
if proxy.schema.edge:
for (source, target) in proxy.edgepairs():
self._add_edge(proxy, source, target)
else:
self._add_node(proxy) | Add an :class:`~followthemoney.proxy.EntityProxy` to the graph and make
it either a :class:`~followthemoney.graph.Node` or an
:class:`~followthemoney.graph.Edge`. | https://github.com/alephdata/followthemoney/blob/e7e1480aeac64c6284aaeb058a825587b8ff332e/followthemoney/graph.py#L245-L256 | import logging
from typing import Any, Dict, Generator, Iterable, List, Optional, Sequence
from followthemoney.types import registry
from followthemoney.types.common import PropertyType
from followthemoney.schema import Schema
from followthemoney.proxy import EntityProxy
from followthemoney.property import Property
fro... | MIT License |
johnpdowling/custom_components | forked-daapd/media_player.py | ForkedDaapd.play | python | def play(self):
return self._command('play') | Set playback to play and returns the current state. | https://github.com/johnpdowling/custom_components/blob/6019dc02d62ae0f0a16ffeda09438d54b94127e9/forked-daapd/media_player.py#L120-L122 | import logging
import requests
import voluptuous as vol
import os
from homeassistant.components.media_player import (
MediaPlayerDevice, PLATFORM_SCHEMA)
from homeassistant.components.media_player.const import (
MEDIA_TYPE_MUSIC, MEDIA_TYPE_PLAYLIST, SUPPORT_NEXT_TRACK,
SUPPORT_PAUSE, SUPPORT_PLAY, SUPPORT_... | Apache License 2.0 |
pedrolamas/home-assistant-config | config/custom_components/hacs/tasks/manager.py | HacsTaskManager.__init__ | python | def __init__(self, hacs: HacsBase, hass: HomeAssistant) -> None:
self.hacs = hacs
self.hass = hass
self.__tasks: dict[str, HacsTask] = {} | Initialize the setup manager class. | https://github.com/pedrolamas/home-assistant-config/blob/66f1fb80e12468a6fe97ae5dfef64d2691754a41/config/custom_components/hacs/tasks/manager.py#L18-L22 | from __future__ import annotations
import asyncio
from importlib import import_module
from pathlib import Path
from homeassistant.core import HomeAssistant
from ..base import HacsBase
from ..mixin import LogMixin
from .base import HacsTask
class HacsTaskManager(LogMixin): | MIT License |
robertwayne/dpymenus | dpymenus/poll.py | Poll._finish_poll | python | async def _finish_poll(self):
cheaters = await self._get_cheaters()
for voters in self.data.values():
voters -= cheaters
await self.output.clear_reactions()
await self.page.on_next_event(self) | Removes multi-votes and calls the Page on_next function when finished. | https://github.com/robertwayne/dpymenus/blob/35cf9e3e9e6306cc6e6a5266688a56ae1edfa49e/dpymenus/poll.py#L125-L132 | import asyncio
import logging
from typing import Any, Dict, List, Set
from warnings import warn
from discord import RawReactionActionEvent, User
from discord.ext.commands import Context
from dpymenus import ButtonMenu, ButtonsError, EventError, PagesError, SessionError
from dpymenus.hooks import call_hook
class Poll(Bu... | MIT License |
ulule/django-linguist | linguist/utils.py | get_language_fields | python | def get_language_fields(fields):
return [
"%s_%s" % (field, lang)
for field in fields
for lang in get_supported_languages()
] | Takes a list of fields and returns related language fields. | https://github.com/ulule/django-linguist/blob/dad1ccacb02ab9aa3b05da3bcfbade6e1da70ddb/linguist/utils.py#L77-L85 | import copy
import itertools
import collections
from importlib import import_module
from django.db.models import QuerySet
from django.core import exceptions
from django.utils.encoding import force_text
from django.utils.functional import lazy
from django.utils.translation import get_language as _get_language
from . imp... | MIT License |
microsoft/restler-fuzzer | restler/engine/fuzzing_parameters/request_params.py | ParamObject.check_type_mismatch | python | def check_type_mismatch(self, check_value):
if not isinstance(check_value, dict):
return self.tag
for member in self._members:
tag = member.check_type_mismatch(check_value)
if tag:
return tag
return None | Checks to see if the check_value param is a dict object and then
checks each object member for its correct type. If any of the param
types are a mismatch, returns that param's tag.
@param check_value: The body string that is used to compare with this param
@type check_value: Str
... | https://github.com/microsoft/restler-fuzzer/blob/d74a267467a2d43fb37c8a16754d0b28e80b649a/restler/engine/fuzzing_parameters/request_params.py#L411-L430 | import sys
import json
from abc import ABCMeta, abstractmethod
import engine.primitives as primitives
import engine.dependencies as dependencies
from engine.fuzzing_parameters.fuzzing_config import *
TAG_SEPARATOR = '/'
FUZZABLE_GROUP_TAG = "fuzzable_group_tag"
class KeyValueParamBase():
__metaclass__ = ABCMeta
... | MIT License |
finance-hub/financehub | webscrapers/CETIP/getcetipdata.py | CETIP._get_dates | python | def _get_dates(initial_date, end_date):
oldest_date = "2012-08-20"
if initial_date is None or (strptime(initial_date, '%Y-%m-%d') < strptime(initial_date, '%Y-%m-%d')):
initial_date = oldest_date
if end_date is None:
end_date = (datetime.today() - timedelta(1)).strftime('... | :param initial_date: initial date for the time interval. If None, uses the first available date on CETIP
:param end_date: end date for the time interval. If None, uses the previous day.
:return: pandas DataFrame with the time interval specified. | https://github.com/finance-hub/financehub/blob/3968d9965e8e2c3b5850f1852b56c485859a9c89/webscrapers/CETIP/getcetipdata.py#L75-L92 | import pandas as pd
from datetime import datetime, timedelta
from time import strptime
class CETIP(object):
def fetch(self, series_id, initial_date=None, end_date=None):
if type(series_id) is list:
df = pd.DataFrame()
for cod in series_id:
series = self._fetch_single_... | MIT License |
bogdanvuk/pygears | pygears/hls/ast/visitor.py | visit_ast | python | def visit_ast(node, ctx):
if node is None:
return ir.ResExpr(None)
breakpoint()
raise SyntaxError(f"Unsupported language construct", node.lineno) | Used by default. Called if no explicit function exists for a node. | https://github.com/bogdanvuk/pygears/blob/a0b21d445e1d5c89ad66751447b8253536b835ee/pygears/hls/ast/visitor.py#L347-L353 | import inspect
import typing
from pygears.core.infer_ftypes import infer_ftypes
from pygears.core.gear import OutSig, InSig
from pygears.typing import Any, typeof
from functools import singledispatch
from dataclasses import dataclass
from .. import ir
from pygears import reg, Intf
from .utils import add_to_list, get_fu... | MIT License |
hallee/espresso-arm | remi/remi/gui.py | Widget.set_on_touchleave_listener | python | def set_on_touchleave_listener(self, listener, funcname):
self.attributes[self.EVENT_ONTOUCHLEAVE] = "sendCallback('%s','%s');" "event.stopPropagation();event.preventDefault();" "return false;" % (id(self), self.EVENT_ONTOUCHLEAVE)
self.eventManager.register_listener(sel... | Registers the listener for the Widget.ontouchleave event.
Note: the listener prototype have to be in the form on_widget_touchleave(self)
Args:
listener (App, Widget): Instance of the listener. It can be the App or a Widget.
funcname (str): Literal name of the listener function, ... | https://github.com/hallee/espresso-arm/blob/d535cc7d8fa41043c6f27fcefa52f98168df4cd4/remi/remi/gui.py#L710-L722 | import os
import logging
from functools import cmp_to_key
import collections
from .server import runtimeInstances, update_event
log = logging.getLogger('remi.gui')
def decorate_set_on_listener(event_name, params):
def add_annotation(function):
function._event_listener = {}
function._event_listener['... | MIT License |
azure/azure-devops-cli-extension | azure-devops/azext_devops/devops_sdk/v5_0/client_factory.py | ClientFactoryV5_0.get_upack_packaging_client | python | def get_upack_packaging_client(self):
return self._connection.get_client('azure.devops.v5_0.upack_packaging.upack_packaging_client.UPackPackagingClient') | get_upack_packaging_client.
Gets the 5.0 version of the UPackPackagingClient
:rtype: :class:`<UPackPackagingClient> <azure.devops.v5_0.upack_packaging.upack_packaging_client.UPackPackagingClient>` | https://github.com/azure/azure-devops-cli-extension/blob/5f33f7d81a9c2d2990044fbd9ffa6b535cbda528/azure-devops/azext_devops/devops_sdk/v5_0/client_factory.py#L340-L345 |
class ClientFactoryV5_0(object):
def __init__(self, connection):
self._connection = connection
def get_accounts_client(self):
return self._connection.get_client('azure.devops.v5_0.accounts.accounts_client.AccountsClient')
def get_boards_client(self):
return self._connection.get_cli... | MIT License |
nccgroup/depthcharge | python/depthcharge/memory/patch.py | MemoryPatch.from_tuple | python | def from_tuple(cls, src: tuple):
src_len = len(src)
if src_len == 4:
exp = src[2]
desc = src[3]
elif src_len == 3:
exp = src[2] if isinstance(src[2], bytes) else None
desc = src[2] if isinstance(src[2], str) else None
elif src_len == 2:... | Create a :py:class:`.MemoryPatch` object from a tuple with the following elements:
+-------+-------+----------------------------------------------------------------------+
| Index | Type | Description |
+=======+=======+=================... | https://github.com/nccgroup/depthcharge/blob/9b66d1c2a80b9398ac561c83173ebd748aef018d/python/depthcharge/memory/patch.py#L70-L101 | class MemoryPatch:
def __init__(self, addr: int, value: bytes, expected: bytes = None, desc=''):
self._addr = addr
self._val = value
self._exp = expected
self._desc = desc
if expected is not None and len(expected) != len(value):
err = 'Expected data is {:d} bytes,... | BSD 3-Clause New or Revised License |
arangodb-community/pyarango | pyArango/theExceptions.py | AQLFetchError.__init__ | python | def __init__(self, err_message):
Exception.__init__(self, err_message) | Error when unable to fetch.
Parameters
----------
err_message : str
error message. | https://github.com/arangodb-community/pyarango/blob/db758bf6ffab47fee02bec3f960f87065b28bc33/pyArango/theExceptions.py#L196-L205 | class pyArangoException(Exception):
def __init__(self, message, errors = None):
Exception.__init__(self, message)
if errors is None:
errors = {}
self.message = message
self.errors = errors
def __str__(self):
return self.message + ". Errors: " + str(self.errors... | Apache License 2.0 |
sigsep/open-unmix-pytorch | openunmix/filtering.py | _mul_add | python | def _mul_add(a: torch.Tensor, b: torch.Tensor, out: Optional[torch.Tensor] = None) -> torch.Tensor:
target_shape = torch.Size([max(sa, sb) for (sa, sb) in zip(a.shape, b.shape)])
if out is None or out.shape != target_shape:
out = torch.zeros(target_shape, dtype=a.dtype, device=a.device)
if out is a:... | Element-wise multiplication of two complex Tensors described
through their real and imaginary parts.
The result is added to the `out` tensor | https://github.com/sigsep/open-unmix-pytorch/blob/49e65ac367cc2ab9fa3f6f41dd9dd778223ca67d/openunmix/filtering.py#L50-L66 | from typing import Optional
import torch
import torch.nn as nn
from torch import Tensor
from torch.utils.data import DataLoader
def atan2(y, x):
pi = 2 * torch.asin(torch.tensor(1.0))
x += ((x == 0) & (y == 0)) * 1.0
out = torch.atan(y / x)
out += ((y >= 0) & (x < 0)) * pi
out -= ((y < 0) & (x < 0))... | MIT License |
zapatacomputing/z-quantum-core | src/python/zquantum/core/bitstring_distribution/distance_measures/mmd.py | compute_rbf_kernel | python | def compute_rbf_kernel(x_i: np.ndarray, y_j: np.ndarray, sigma: float) -> np.ndarray:
exponent = np.abs(x_i[:, None] - y_j[None, :]) ** 2
try:
gamma = 1.0 / (2 * sigma)
except ZeroDivisionError as error:
print("Handling run-time error:", error)
raise
kernel_matrix = np.exp(-gamma... | Compute the gaussian (RBF) kernel matrix K, with K_ij = exp(-gamma |x_i - y_j|^2)
and gamma = 1/(2*sigma).
Args:
x_i: Samples A (integers).
y_j: Samples B (integers).
sigma: The bandwidth of the gaussian kernel.
Returns:
np.ndarray: The gaussian kernel matrix. | https://github.com/zapatacomputing/z-quantum-core/blob/5fa4fd5d8682bbae696f8c2c2d386133ccf7f378/src/python/zquantum/core/bitstring_distribution/distance_measures/mmd.py#L34-L53 | from typing import TYPE_CHECKING, Dict, List, Sequence, Union
import numpy as np
if TYPE_CHECKING:
from zquantum.core.bitstring_distribution import BitstringDistribution | Apache License 2.0 |
giacomocerquone/univaqbot | libs/utils.py | db_connection | python | def db_connection():
try:
conn = pymongo.MongoClient(os.environ['MONGODB_URI'])
print("Connected successfully!")
except (pymongo.errors.ConnectionFailure) as err:
print("Could not connect to MongoDB: %s" % err)
global DATABASE
DATABASE = conn.get_default_database() | Get MongoDB connection | https://github.com/giacomocerquone/univaqbot/blob/754519befe24dcc3c4a658160b727de7b14a6b21/libs/utils.py#L33-L43 | import logging
import os
import bs4
import requests
import pymongo
from telegram import TelegramError
DATABASE = ""
USERS = {
'telegramID': [],
'disim': [],
'univaq': [],
'discab_general': [],
'discab_biotechnology': [],
'discab_medical':[],
'discab_motor_science': [],
'discab_psychology... | MIT License |
bilylee/siamfc-tensorflow | scripts/build_VID2015_imdb.py | Dataset._get_unique_trackids | python | def _get_unique_trackids(self, video_dir):
x_image_paths = glob.glob(video_dir + '/*.crop.x.jpg')
trackids = [os.path.basename(path).split('.')[1] for path in x_image_paths]
unique_trackids = set(trackids)
return unique_trackids | Get unique trackids within video_dir | https://github.com/bilylee/siamfc-tensorflow/blob/f572dca95f2b3b2861f54de467259753428e468c/scripts/build_VID2015_imdb.py#L47-L52 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import glob
import os
import os.path as osp
import pickle
import sys
import numpy as np
import tensorflow as tf
CURRENT_DIR = osp.dirname(__file__)
sys.path.append(osp.join(CURRENT_DIR, '..'))
from utils.misc_ut... | MIT License |
jefkine/zeta-learn | ztlearn/utils/data_utils.py | minibatches | python | def minibatches(input_data, input_label, batch_size, shuffle):
assert input_data.shape[0] == input_label.shape[0], 'input data and label sizes do not match!'
minibatches = []
indices = np.arange(input_data.shape[0])
if shuffle:
np.random.shuffle(indices)
for idx in range(0, input_data.sh... | generate minibatches on a given input data matrix | https://github.com/jefkine/zeta-learn/blob/04388f90093b52f5df2f334c898f3a1224f5a13f/ztlearn/utils/data_utils.py#L98-L111 | import os
import sys
import gzip
import urllib
import tarfile
import zipfile
import numpy as np
from itertools import chain
from itertools import combinations
from itertools import combinations_with_replacement
def eucledian_norm(vec_a, vec_b):
distance = vec_a - vec_b
return np.linalg.norm(distance, ord = 'fro... | MIT License |
openschc/openschc | src/frag_tile.py | TileList.unset_sent_flag | python | def unset_sent_flag(self, win, bit_list):
def unset_sent_flag_do(wn, tn):
if tn is None:
dprint("last tile case")
return
counter = 0
dprint('unset_sent_flag_do')
for t in self.all_tiles:
if t["w-num"] == wn:
... | set the sent flag to False from True. | https://github.com/openschc/openschc/blob/7b0c165a27936d8f2732a90844a00c5ade23eea5/src/frag_tile.py#L108-L161 | from gen_base_import import *
from gen_utils import dprint
import frag_msg
from compr_core import *
class TileList():
def __init__(self, rule, packet_bbuf, l2word=8):
self.rule = rule
self.t_size = rule[T_FRAG][T_FRAG_PROF][T_FRAG_TILE]
assert self.t_size >= l2word
self.max_fcn = fra... | MIT License |
ebay/accelerator | accelerator/extras.py | json_encode | python | def json_encode(variable, sort_keys=True, as_str=False):
if sort_keys:
dict_type = dict
else:
dict_type = OrderedDict
def typefix(e):
if isinstance(e, dict):
return dict_type((typefix(k), typefix(v)) for k, v in iteritems(e))
elif isinstance(e, (list, tuple, set,)):
return [typefix(v) for v in e]
eli... | Return variable serialised as json bytes (or str with as_str=True).
You can pass tuples and sets (saved as lists).
On py2 you can also pass bytes that will be passed through compat.uni.
If you set sort_keys=False you can use OrderedDict to get whatever
order you like. | https://github.com/ebay/accelerator/blob/4c053465b893e8ece354c26953fd168a36edccc1/accelerator/extras.py#L107-L133 | from __future__ import print_function
from __future__ import division
import os
import datetime
import json
from traceback import print_exc
from collections import OrderedDict
import sys
from accelerator.compat import PY2, PY3, pickle, izip, iteritems, first_value
from accelerator.compat import num_types, uni, unicode,... | Apache License 2.0 |
databiosphere/toil | src/toil/lib/bioio.py | system | python | def system(command):
logger.warning('Deprecated toil method that will be moved/replaced in a future release."')
logger.debug(f'Running: {command}')
subprocess.check_call(command, shell=isinstance(command, str), bufsize=-1) | A convenience wrapper around subprocess.check_call that logs the command before passing it
on. The command can be either a string or a sequence of strings. If it is a string shell=True
will be passed to subprocess.check_call.
:type command: str | sequence[string] | https://github.com/databiosphere/toil/blob/eb2ae8365ae2ebdd50132570b20f7d480eb40cac/src/toil/lib/bioio.py#L25-L34 | import logging
import subprocess
from toil.statsAndLogging import (logger,
root_logger,
set_logging_from_options)
from toil.test import get_temp_file | Apache License 2.0 |
dynatrace-oss/api-client-python | dynatrace/environment_v1/deployment.py | DeploymentService.get_gateway_installer_connection_info | python | def get_gateway_installer_connection_info(self, network_zone: Optional[str] = "default") -> "ActiveGateConnectionInfo":
params = {"networkZone": network_zone}
response = self.__http_client.make_request(path=f"{self.ENDPOINT_INSTALLER_GATEWAY}/connectioninfo", params=params)
return ActiveGateConn... | Gets the connectivity information for Environment ActiveGate.
:param network_zone: The network zone you want the result to be configured with.
:returns ActiveGateConnectionInfo: connectivity information | https://github.com/dynatrace-oss/api-client-python/blob/7749125ab384d36e9a00d5d8dc5964cce4d46f66/dynatrace/environment_v1/deployment.py#L178-L188 | from typing import Optional, Dict, List, Any
from requests import Response
from dynatrace.dynatrace_object import DynatraceObject
from dynatrace.http_client import HttpClient
class DeploymentService:
ENDPOINT_INSTALLER_AGENT = "/api/v1/deployment/installer/agent"
ENDPOINT_INSTALLER_GATEWAY = "/api/v1/deployment... | Apache License 2.0 |
caktus/django-sticky-uploads | stickyuploads/views.py | UploadView.post | python | def post(self, *args, **kwargs):
if self.upload_allowed():
form = self.get_upload_form()
result = {}
if form.is_valid():
storage = self.get_storage()
result['is_valid'] = True
info = form.stash(storage, self.request.path)
... | Save file and return saved info or report errors. | https://github.com/caktus/django-sticky-uploads/blob/a57539655ba991f63f31f0a5c98d790947bcd1b8/stickyuploads/views.py#L18-L35 | from __future__ import unicode_literals
import json
from django.core.files.storage import get_storage_class
from django.http import HttpResponse, HttpResponseForbidden
from django.views.generic import View
from .forms import UploadForm
class UploadView(View):
form_class = UploadForm
storage_class = 'stickyuploa... | BSD 3-Clause New or Revised License |
jmcarp/flask-apispec | flask_apispec/extension.py | FlaskApiSpec._register | python | def _register(self, target, endpoint=None, blueprint=None,
resource_class_args=None, resource_class_kwargs=None):
if isinstance(target, types.FunctionType):
paths = self.view_converter.convert(target, endpoint, blueprint)
elif isinstance(target, ResourceMeta):
p... | Register a view.
:param target: view function or view class.
:param endpoint: (optional) endpoint name.
:param blueprint: (optional) blueprint name.
:param tuple resource_class_args: (optional) args to be forwarded to the
view class constructor.
:param dict resource_... | https://github.com/jmcarp/flask-apispec/blob/de6f5adbcf3e6fce14aa1e1288ac2e401fd9ca35/flask_apispec/extension.py#L127-L152 | import flask
import functools
import types
from apispec import APISpec
from apispec.ext.marshmallow import MarshmallowPlugin
from flask_apispec import ResourceMeta
from flask_apispec.apidoc import ViewConverter, ResourceConverter
class FlaskApiSpec:
def __init__(self, app=None, document_options=True):
self.... | MIT License |
peoplepower/botlab | com.ppc.Lesson6-DataStreams/intelligence/lesson6/location_datastream_microservice.py | LocationDataStreamMicroservice.datastream_updated | python | def datastream_updated(self, botengine, address, content):
if hasattr(self, address):
getattr(self, address)(botengine, content) | Data Stream Message Received
:param botengine: BotEngine environment
:param address: Data Stream address
:param content: Content of the message | https://github.com/peoplepower/botlab/blob/21cc90c558a17b7ef4a42bca247b437d2f968dc0/com.ppc.Lesson6-DataStreams/intelligence/lesson6/location_datastream_microservice.py#L123-L132 | from intelligence.intelligence import Intelligence
from devices.light.light import LightDevice
class LocationDataStreamMicroservice(Intelligence):
def __init__(self, botengine, parent):
Intelligence.__init__(self, botengine, parent)
self.is_present = self.parent.is_present(botengine)
def initial... | Apache License 2.0 |
crespo-otero-group/fromage | fromage/scripts/fro_assign_charges.py | charged_kinds | python | def charged_kinds(in_atoms, in_kinds):
q_kinds = []
for kind in in_kinds:
charges = []
for atom in in_atoms:
if atom.kind == kind:
charges.append(atom.q)
if charges:
avg_charge = sum(charges) / float(len(charges))
else:
avg_ch... | Get charged atom kinds from charged atoms and kinds.
For each kind of atom to be charged, goes through the list of atoms and
makes an average of the partial atomic charge of atoms of that type.
Parameters
----------
in_atoms : Mol object
The atoms should be charged and some of them at leas... | https://github.com/crespo-otero-group/fromage/blob/9b4a80698ed1672268dde292d5512c72a23cb00a/fromage/scripts/fro_assign_charges.py#L119-L154 | import numpy as np
import sys
import argparse
import fromage.io.read_file as rf
def detect_1_connect(in_atoms):
nat_mol = len(in_atoms)
cnct = np.zeros((nat_mol, nat_mol),dtype=int)
for i, i_atom in enumerate(in_atoms):
for j, j_atom in enumerate(in_atoms):
if np.count_nonzero(in_atoms.v... | MIT License |
jest-community/jest-pytest | src/__tests__/integration/home-assistant/homeassistant/components/switch/telnet.py | TelnetSwitch.turn_off | python | def turn_off(self, **kwargs):
self._telnet_command(self._command_off)
if self.assumed_state:
self._state = False | Turn the device off. | https://github.com/jest-community/jest-pytest/blob/b197b0b31e3ca5c411202d97583cbd2d2b0b92e9/src/__tests__/integration/home-assistant/homeassistant/components/switch/telnet.py#L140-L144 | from datetime import timedelta
import logging
import telnetlib
import voluptuous as vol
from homeassistant.components.switch import (
ENTITY_ID_FORMAT, PLATFORM_SCHEMA, SwitchDevice)
from homeassistant.const import (
CONF_COMMAND_OFF, CONF_COMMAND_ON, CONF_COMMAND_STATE, CONF_NAME,
CONF_PORT, CONF_RESOURCE,... | MIT License |
borda/pyimsegm | experiments_ovary_centres/run_center_prediction.py | main | python | def main(params):
params = run_train.prepare_experiment_folder(params, FOLDER_EXPERIMENT)
tl_expt.set_experiment_logger(params['path_expt'])
logging.info('COMPUTER: \n%r', platform.uname())
logging.info(tl_expt.string_dict(params, desc='PARAMETERS'))
tl_expt.create_subfolders(params['path_expt'], LI... | PIPELINE for new detections
:param dict(str,str) params: | https://github.com/borda/pyimsegm/blob/7463cfc7aad8781564dc84c8780f291cc3c17fe3/experiments_ovary_centres/run_center_prediction.py#L122-L161 | import gc
import logging
import os
import platform
import sys
import time
from functools import partial
import pandas as pd
sys.path += [os.path.abspath('.'), os.path.abspath('..')]
import run_center_candidate_training as run_train
import run_center_clustering as run_clust
import imsegm.classification as seg_clf
impo... | BSD 3-Clause New or Revised License |
theirc/cts | shipments/tasks.py | delete_shipment | python | def delete_shipment(shipment_id):
try:
try:
shipment = Shipment.objects.get(pk=shipment_id)
except Shipment.DoesNotExist:
logger.error("In delete_shipment task, no shipment with id %s" % shipment_id)
else:
shipment.fast_delete()
except Exception:
... | Task to delete a shipment, because it can take more than 60 seconds. | https://github.com/theirc/cts/blob/43eb3e3b78c19f9e1dc02158ca12fc0c5d6bb270/shipments/tasks.py#L10-L22 | import logging
from celery.task import task
from shipments.models import Shipment
logger = logging.getLogger(__name__)
@task | BSD 3-Clause New or Revised License |
inquest/omnibus | omnibus-cli.py | Console.do_hibp | python | def do_hibp(self, arg):
result = self.dispatch.submit(self.session, 'hibp', arg)
pp_json(result) | Check HaveIBeenPwned for email address | https://github.com/inquest/omnibus/blob/88dbf5d02f87eaa79a1cfc13d403cf854ee44c40/omnibus-cli.py#L468-L471 | import os
import sys
import cmd2
import json
import argparse
from lib import common
from lib import storage
from lib import asciiart
from lib.mongo import Mongo
from lib.cache import RedisCache
from lib.dispatch import Dispatch
from lib.common import info
from lib.common import mkdir
from lib.common import error
from l... | MIT License |
kozea/weasyprint | weasyprint/text/fonts.py | FontConfiguration.__del__ | python | def __del__(self):
for filename in self._filenames:
try:
os.remove(filename)
except OSError:
continue | Clean a font configuration for a document. | https://github.com/kozea/weasyprint/blob/a149af9aaf902901d5d19134f5393e2637bcd219/weasyprint/text/fonts.py#L282-L292 | import io
import os
import pathlib
import sys
import tempfile
import warnings
from fontTools.ttLib import TTFont, woff2
from ..logger import LOGGER
from ..urls import FILESYSTEM_ENCODING, fetch
from .constants import (
CAPS_KEYS, EAST_ASIAN_KEYS, FONTCONFIG_STRETCH, FONTCONFIG_STYLE,
FONTCONFIG_WEIGHT, LIGATURE... | BSD 3-Clause New or Revised License |
scut-ailab/dcp | dcp/channel_selection/channel_selection.py | LayerChannelSelection.prepare_channel_selection | python | def prepare_channel_selection(self, original_segment, pruned_segment, module, aux_fc, layer_name, block_count):
self.split_segment_into_three_parts(original_segment, pruned_segment, block_count)
pruned_segment, layer = self.replace_layer_with_mask_conv(pruned_segment, module, layer_name, block_count)
... | Prepare for channel selection
1. Split the segment into three parts.
2. Replace the pruned layer with mask convolution.
3. Store the input feature map of the pruned layer in advance to accelerate channel selection. | https://github.com/scut-ailab/dcp/blob/70a2e53ae896573b0b4323eac5817e5660315cb4/dcp/channel_selection/channel_selection.py#L179-L213 | import datetime
import math
import os
import time
import torch
import torch.nn as nn
import dcp.utils as utils
from dcp.mask_conv import MaskConv2d
from dcp.utils.others import concat_gpu_data
from dcp.utils.write_log import write_log
class LayerChannelSelection(object):
def __init__(self, trainer, train_loader, va... | BSD 3-Clause New or Revised License |
rojopolis/terraform-aws-lambda-python-archive | scripts/build_lambda.py | get_hash | python | def get_hash(output_path):
with open(output_path, 'rb') as f:
h = hashlib.sha256()
h.update(f.read())
return base64.standard_b64encode(h.digest()).decode('utf-8', 'strict') | Return base64 encoded sha256 hash of archive file | https://github.com/rojopolis/terraform-aws-lambda-python-archive/blob/0b0dc9cf0870c4280495633aa0cd92fe197bbde2/scripts/build_lambda.py#L61-L68 | from distutils.dir_util import copy_tree
import base64
import errno
import hashlib
import json
import logging
import os
import shutil
import subprocess
import sys
import tempfile
import zipfile
def build(src_dir, output_path, install_dependencies):
with tempfile.TemporaryDirectory() as build_dir:
copy_tree(... | MIT License |
chenwuperth/rgz_rcnn | lib/fast_rcnn/test.py | _rescale_boxes | python | def _rescale_boxes(boxes, inds, scales):
for i in xrange(boxes.shape[0]):
boxes[i,:] = boxes[i,:] / scales[int(inds[i])]
return boxes | Rescale boxes according to image rescaling. | https://github.com/chenwuperth/rgz_rcnn/blob/b526c237fea5c9a77bbe7bd0048f72cf93e733a4/lib/fast_rcnn/test.py#L131-L137 | from fast_rcnn.config import cfg, get_output_dir
import argparse
from utils.timer import Timer
import numpy as np
import cv2
from utils.cython_nms import nms, nms_new
from utils.boxes_grid import get_boxes_grid
from utils.project_bbox import project_bbox_inv
import cPickle
import heapq
from utils.blob import im_list_to... | MIT License |
brython-dev/brython | www/src/Lib/test/test_gdb.py | PrettyPrintTests.assertSane | python | def assertSane(self, source, corruption, exprepr=None):
if corruption:
cmds_after_breakpoint=[corruption, 'backtrace']
else:
cmds_after_breakpoint=['backtrace']
gdb_repr, gdb_output = self.get_gdb_repr(source,
cmds_after_breakpoint... | Run Python under gdb, corrupting variables in the inferior process
immediately before taking a backtrace.
Verify that the variable's representation is the expected failsafe
representation | https://github.com/brython-dev/brython/blob/33aeaab551f1b73209326c5a0aecf98642d4c126/www/src/Lib/test/test_gdb.py#L502-L529 | import os
import platform
import re
import subprocess
import sys
import sysconfig
import textwrap
import unittest
from test import support
from test.support import findfile, python_is_optimized
def get_gdb_version():
try:
cmd = ["gdb", "-nx", "--version"]
proc = subprocess.Popen(cmd,
... | BSD 3-Clause New or Revised License |
zebrium/zebrium-kubernetes-demo | manage.py | list | python | def list(args):
experiments = sorted(os.listdir('./litmus'))
print_color("Available Litmus Chaos Experiments:\n\n")
i = 1
for experiment_file in experiments:
print_color(f"\t{i}. {experiment_file.replace('.yaml', '')}")
i += 1 | List all available Litmus Chaos Experiments available in this repository | https://github.com/zebrium/zebrium-kubernetes-demo/blob/fddf3a05fa798d8f49c40ea3f1ed2f24441f27b7/manage.py#L252-L261 | import argparse
import os
import json
import sys
import time
from datetime import datetime
import subprocess
import yaml
class bcolors:
HEADER = '\033[95m'
OKBLUE = '\033[94m'
OKGREEN = '\033[92m'
WARNING = '\033[93m'
FAIL = '\033[91m'
ENDC = '\033[0m'
BOLD = '\033[1m'
UNDERLINE = '\033[... | MIT License |
onnxbot/onnx-fb-universe | test/verify.py | Errors.failWith | python | def failWith(self, msg):
self.addErr(msg)
self.fail() | Add an error to the error context, and then short-circuit. | https://github.com/onnxbot/onnx-fb-universe/blob/076e15d3d6d48c1ca792566bf9c23d07cb6910e1/test/verify.py#L163-L168 | import torch
import torch.jit
import torch.onnx
import onnx
import onnx.helper
import numpy as np
import difflib
import contextlib
import io
def colonize(msg, sep=": "):
if not msg:
return ""
else:
return msg + sep
class Errors(object):
def __init__(self, msg, rtol=1e-3, atol=1e-7):
... | MIT License |
demisto/demisto-py | demisto_client/demisto_api/models/playbook.py | Playbook.name | python | def name(self, name):
self._name = name | Sets the name of this Playbook.
:param name: The name of this Playbook. # noqa: E501
:type: str | https://github.com/demisto/demisto-py/blob/95d29e07693d27c133f7fe6ef9da13e4b6dbf542/demisto_client/demisto_api/models/playbook.py#L581-L589 | import pprint
import re
import six
from demisto_client.demisto_api.models.playbook_inputs import PlaybookInputs
from demisto_client.demisto_api.models.playbook_outputs import PlaybookOutputs
from demisto_client.demisto_api.models.playbook_task import PlaybookTask
from demisto_client.demisto_api.models.playbook_... | Apache License 2.0 |
twilio/howtos | intercom/gdata/docs/__init__.py | DocumentListAclEntryFromString | python | def DocumentListAclEntryFromString(xml_string):
return atom.CreateClassFromXMLString(DocumentListAclEntry, xml_string) | Converts an XML string into a DocumentListAclEntry object.
Args:
xml_string: string The XML describing a Document List ACL feed entry.
Returns:
A DocumentListAclEntry object corresponding to the given XML. | https://github.com/twilio/howtos/blob/718853f6a89252592d13592638c18f633e061b96/intercom/gdata/docs/__init__.py#L214-L223 | __author__ = ('api.jfisher (Jeff Fisher), '
'api.eric@google.com (Eric Bidelman)')
import atom
import gdata
DOCUMENTS_NAMESPACE = 'http://schemas.google.com/docs/2007'
class Scope(atom.AtomBase):
_tag = 'scope'
_namespace = gdata.GACL_NAMESPACE
_children = atom.AtomBase._children.copy()
_attribute... | MIT License |
aldebaran/qibuild | python/qitest/runner.py | TestSuiteRunner.launcher | python | def launcher(self):
pass | This function should return a :py:class:`.TestLauncher` | https://github.com/aldebaran/qibuild/blob/efea6fa3744664348717fe5e8df708a3cf392072/python/qitest/runner.py#L44-L46 | from __future__ import absolute_import
from __future__ import unicode_literals
from __future__ import print_function
import re
import os
import json
import abc
import qitest.test_queue
from qisys import ui
class TestSuiteRunner(object):
__metaclass__ = abc.ABCMeta
def __init__(self, project):
self.proje... | BSD 3-Clause New or Revised License |
burnash/gspread | gspread/worksheet.py | Worksheet.row_values | python | def row_values(self, row, **kwargs):
try:
data = self.get("A{}:{}".format(row, row), **kwargs)
return data[0] if data else []
except KeyError:
return [] | Returns a list of all values in a `row`.
Empty cells in this list will be rendered as :const:`None`.
:param int row: Row number (one-based).
:param str value_render_option: (optional) Determines how values should
be rendered in the the output. See `ValueRenderOption`_ in
... | https://github.com/burnash/gspread/blob/90a728fac1c8f6fb38f19da588de0337697854cc/gspread/worksheet.py#L414-L430 | from .cell import Cell
from .urls import SPREADSHEET_URL, WORKSHEET_DRIVE_URL
from .utils import (
a1_range_to_grid_range,
a1_to_rowcol,
absolute_range_name,
accepted_kwargs,
cast_to_a1_notation,
cell_list_to_rect,
fill_gaps,
filter_dict_values,
finditem,
is_scalar,
numericis... | MIT License |
reliaqualassociates/ramstk | src/ramstk/views/gtk3/fmea/view.py | FMEAWorkView._do_request_insert_child | python | def _do_request_insert_child(self, __button: Gtk.ToolButton) -> None:
_model, _row = self._pnlPanel.tvwTreeView.get_selection().get_selected()
try:
_parent_id = _model.get_value(_row, 0)
_level = {
1: "mechanism",
2: "cause",
3: "co... | Request to insert a new entity to the FMEA.
:return: None
:rtype: None | https://github.com/reliaqualassociates/ramstk/blob/ffec5a107424914cf0026c6dfe26369c221f79f9/src/ramstk/views/gtk3/fmea/view.py#L219-L246 | from typing import Any, Dict, List
from pubsub import pub
from ramstk.configuration import (
RAMSTK_CONTROL_TYPES,
RAMSTK_CRITICALITY,
RAMSTK_FAILURE_PROBABILITY,
RAMSTKUserConfiguration,
)
from ramstk.logger import RAMSTKLogManager
from ramstk.views.gtk3 import Gtk, _
from ramstk.views.gtk3.assistants ... | BSD 3-Clause New or Revised License |
barrust/pyprobables | probables/cuckoo/countingcuckoo.py | CountingCuckooBin.__repr__ | python | def __repr__(self):
return self.__str__() | how do we represent this? | https://github.com/barrust/pyprobables/blob/f348fb878cdfbe6c1d997be093c073d26f9b05aa/probables/cuckoo/countingcuckoo.py#L274-L276 | import os
import random
from struct import calcsize, pack, unpack
from ..exceptions import CuckooFilterFullError
from .cuckoo import CuckooFilter
class CountingCuckooFilter(CuckooFilter):
__slots__ = [
"__unique_elements",
"_inserted_elements",
"_bucket_size",
"__max_cuckoo_swaps",
... | MIT License |
theislab/diffxpy | diffxpy/testing/det.py | DifferentialExpressionTestLRT.locations | python | def locations(self):
di = self.full_design_loc_info
sample_description = self.sample_description[[f.name() for f in di.factor_infos]]
dmat = self.full_estim.input_data.design_loc
dmat, sample_description = dmat_unique(dmat, sample_description)
retval = self.full_estim.model.inver... | Returns a pandas.DataFrame containing the locations for the different categories of the factors
:return: pd.DataFrame | https://github.com/theislab/diffxpy/blob/b8c6ae0d7d957db72e41bc2e705c240348c66509/diffxpy/testing/det.py#L606-L626 | import abc
try:
import anndata
except ImportError:
anndata = None
import batchglm.api as glm
import dask
import logging
import numpy as np
import patsy
import pandas as pd
from random import sample
import scipy.sparse
import sparse
from typing import Union, Dict, Tuple, List, Set
from .utils import split_x, dma... | BSD 3-Clause New or Revised License |
lisa-lab/pylearn2 | pylearn2/dataset_get/dataset-get.py | unpack_tarball | python | def unpack_tarball( tar_filename, dest_path ):
if os.path.exists(tar_filename):
if file_access_rights(dest_path,os.W_OK,check_above=False):
try:
this_tar_file=tarfile.open(tar_filename,"r:bz2")
except Exception as e:
raise IOError("[tar] cannot open '%... | Unpacks a (bzipped2) tarball to a destination
directory
:param tar_filename: the bzipped2 tar file
:param dest_path: a path to where expand the tarball
:raises: various IOErrors | https://github.com/lisa-lab/pylearn2/blob/af81e5c362f0df4df85c3e54e23b2adeec026055/pylearn2/dataset_get/dataset-get.py#L543-L575 | from __future__ import print_function
__authors__ = "Steven Pigeon"
__copyright__ = "(c) 2012, Université de Montréal"
__contact__ = "Steven Pigeon: pigeon@iro.umontreal.ca"
__version__ = "dataset-get 0.1"
__licence__ = "BSD 3-Clause http://www.opensource.org/licenses/BSD-3-Clause "
import logging
import re,os,... | BSD 3-Clause New or Revised License |
ankush-me/synthtext | synthgen.py | get_text_placement_mask | python | def get_text_placement_mask(xyz,mask,plane,pad=2,viz=False):
_, contour, hier = cv2.findContours(mask.copy().astype('uint8'), mode=cv2.RETR_CCOMP, method=cv2.CHAIN_APPROX_SIMPLE)
contour = [np.squeeze(c).astype('float') for c in contour]
H,W = mask.shape[:2]
pts,pts_fp = [],[]
center = np.array([W,H... | Returns a binary mask in which text can be placed.
Also returns a homography from original image
to this rectified mask.
XYZ : (HxWx3) image xyz coordinates
MASK : (HxW) : non-zero pixels mark the object mask
REGION : DICT output of TextRegions.get_regions
PAD : number of pixels to pad the pla... | https://github.com/ankush-me/synthtext/blob/5687aa78ddf8714fc01ef8c043dd40af1cd09115/synthgen.py#L207-L286 | from __future__ import division
import copy
import cv2
import h5py
from PIL import Image
import numpy as np
import matplotlib.pyplot as plt
import os.path as osp
import scipy.ndimage as sim
import scipy.spatial.distance as ssd
import synth_utils as su
import text_utils as tu
from colorize3_poisson import Colorize
fro... | Apache License 2.0 |
opennetworkingfoundation/tapi | RI/flask_server/tapi_server/models/tapi_oam_get_oam_job.py | TapiOamGetOamJob.__init__ | python | def __init__(self, output=None):
self.openapi_types = {
'output': TapiOamGetoamjobOutput
}
self.attribute_map = {
'output': 'output'
}
self._output = output | TapiOamGetOamJob - a model defined in OpenAPI
:param output: The output of this TapiOamGetOamJob. # noqa: E501
:type output: TapiOamGetoamjobOutput | https://github.com/opennetworkingfoundation/tapi/blob/1f3fd9483d5674552c5a31206c97399c8c151897/RI/flask_server/tapi_server/models/tapi_oam_get_oam_job.py#L19-L33 | from __future__ import absolute_import
from datetime import date, datetime
from typing import List, Dict
from tapi_server.models.base_model_ import Model
from tapi_server.models.tapi_oam_getoamjob_output import TapiOamGetoamjobOutput
from tapi_server import util
class TapiOamGetOamJob(Model): | Apache License 2.0 |
nipy/nilabels | nilabels/tools/caliber/volumes_and_values.py | get_volumes_per_label | python | def get_volumes_per_label(im_segm, labels, labels_names, tot_volume_prior=None, verbose=0):
num_non_zero_voxels = get_total_num_nonzero_voxels(im_segm)
vol_non_zero_voxels_mm3 = num_non_zero_voxels * one_voxel_volume(im_segm)
if tot_volume_prior is None:
tot_volume_prior = vol_non_zero_voxels_mm3
... | Get a separate volume for each label in a data-frame
:param im_segm: nibabel segmentation
:param labels: labels you want to measure, or 'all' if you want them all or 'tot' to have the total of the non zero
labels.
:param labels_names: list with the indexes of labels in the final dataframe... | https://github.com/nipy/nilabels/blob/b065febc611eef638785651b4642d53bb61f1321/nilabels/tools/caliber/volumes_and_values.py#L84-L153 | import numpy as np
import pandas as pa
from nilabels.tools.aux_methods.utils_nib import one_voxel_volume
def get_total_num_nonzero_voxels(im_segm, list_labels_to_exclude=None):
seg = np.copy(im_segm.get_data())
if list_labels_to_exclude is not None:
for label_k in list_labels_to_exclude:
pla... | MIT License |
scqubits/scqubits | scqubits/core/qubit_base.py | QuantumSystem.widget | python | def widget(self, params: Dict[str, Any] = None):
init_params = params or self.get_initdata()
init_params.pop("id_str", None)
ui.create_widget(
self.set_params, init_params, image_filename=self._image_filename
) | Use ipywidgets to modify parameters of class instance | https://github.com/scqubits/scqubits/blob/d8532a3b614e37b1e65b75000493ea2c25c05682/scqubits/core/qubit_base.py#L183-L189 | import functools
import inspect
from abc import ABC, ABCMeta, abstractmethod
from typing import (
TYPE_CHECKING,
Any,
Dict,
Iterable,
List,
Optional,
Tuple,
Union,
overload,
)
import matplotlib.pyplot as plt
import numpy as np
import scipy as sp
from matplotlib.axes import Axes
from ... | BSD 3-Clause New or Revised License |
gepd/deviot | libraries/preferences_bridge.py | PreferencesBridge.get_selected_boards | python | def get_selected_boards(self):
settings = get_setting('boards', [])
boards = self.get_envs_initialized()
if(boards):
settings.extend(boards)
if(settings):
settings = list(set(settings))
return settings | Get Board/s
List of all boards in the project, the list includes
the one selected in deviot, and the one initialized in the
platformio.ini file, they're mixed and excluding the duplicates
Returns:
list -- list of boards | https://github.com/gepd/deviot/blob/150caea06108369b30210eb287a580fcff4904af/libraries/preferences_bridge.py#L60-L79 | from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
from __future__ import unicode_literals
from ..api import deviot
from .tools import get_setting, save_setting
from ..platformio.pio_bridge import PioBridge
from ..libraries.readconfig import ReadConfig
logger = ... | Apache License 2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.