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
microsoft/agogosml
agogosml/agogosml/writer/output_writer.py
OutputWriter.stop_incoming_messages
python
def stop_incoming_messages(self): self.listener.stop() self.logger.event('output.lifecycle.stop')
Stop accepting messages.
https://github.com/microsoft/agogosml/blob/5e603394f037640b2fb7ddee60be47c569ab48c9/agogosml/agogosml/writer/output_writer.py#L31-L34
from typing import Callable from typing import Optional from agogosml.common.abstract_streaming_client import AbstractStreamingClient from agogosml.common.listener_client import ListenerClient from agogosml.utils.logger import Logger class OutputWriter: def __init__(self, streaming_client: AbstractStreamingClient, ...
MIT License
google/init2winit
init2winit/init_lib/sparse_init.py
sparse_init
python
def sparse_init(loss_fn, model, hps, input_shape, output_shape, rng_key, metrics_logger=None, log_every=10): del loss_fn, input_shape, output_shape, rng_key, metrics_logger, log_every activation_functions...
Implements SparseInit initializer. Args: loss_fn: Loss function. model: Flax Model class. hps: HParam object. Required hparams are meta_learning_rate, meta_batch_size, meta_steps, and epsilon. input_shape: Must agree with batch[0].shape[1:]. output_shape: Must agree with batch[1].shape[1:]....
https://github.com/google/init2winit/blob/d54661d82576204bfcc306fae8606b8e7c3838b6/init2winit/init_lib/sparse_init.py#L29-L75
from ml_collections.config_dict import config_dict import numpy as np DEFAULT_HPARAMS = config_dict.ConfigDict(dict(non_zero_connection_weights=15,))
Apache License 2.0
thomasgermain/pymultimatic
pymultimatic/systemmanager.py
SystemManager.set_ventilation_operating_mode
python
async def set_ventilation_operating_mode( self, ventilation_id: str, mode: OperatingMode ) -> None: await self._call_api( urls.set_ventilation_operating_mode, params={"id": ventilation_id}, payload=payloads.ventilation_operating_mode(mode.name), )
Set ventilation at night level. Compatible modes are listed here :class:`~pymultimatic.model.Ventilation.MODES` Args: ventilation_id (str): id of the ventilation mode (OperatingMode): Mode to set
https://github.com/thomasgermain/pymultimatic/blob/9a05d0f1e341bb59f72cd6294aa1e22651803b3f/pymultimatic/systemmanager.py#L749-L764
import asyncio import logging from datetime import date, timedelta from typing import Any, Callable, List, Optional, Tuple, Type from aiohttp import ClientSession from schema import Schema, SchemaError from .api import ApiError, Connector, WrongResponseError, defaults, payloads, schemas, urls from .model import ( C...
MIT License
truckersmp-cli/truckersmp-cli
truckersmp_cli/gamestarter.py
StarterProton.setup_game_env
python
def setup_game_env(env, steamdir): if not Args.disable_proton_overlay: overlayrenderer = os.path.join(steamdir, File.overlayrenderer_inner) if "LD_PRELOAD" in env: env["LD_PRELOAD"] += ":" + overlayrenderer else: env["LD_PRELOAD"] = overlayrend...
Set up environment variables for running the game with Proton. env: A dict of environment variables steamdir: Path to Steam installation
https://github.com/truckersmp-cli/truckersmp-cli/blob/98b0828ca2edca4b5d6cd7788bfb621e00a53882/truckersmp_cli/gamestarter.py#L280-L298
import logging import os import shutil import subprocess as subproc import sys import tempfile import time from .utils import ( activate_native_d3dcompiler_47, find_discord_ipc_sockets, get_proton_version, get_steam_library_dirs, is_d3dcompiler_setup_skippable, log_info_formatted_envars_and_args, print_chil...
MIT License
databand-ai/dbnd
modules/dbnd/src/dbnd/_vendor/cloudpickle/cloudpickle_fast.py
CloudPickler._dynamic_function_reduce
python
def _dynamic_function_reduce(self, func): newargs = self._function_getnewargs(func) state = _function_getstate(func) return (types.FunctionType, newargs, state, None, None, _function_setstate)
Reduce a function that is not pickleable via attribute lookup.
https://github.com/databand-ai/dbnd/blob/ec0076f9a142b20e2f7afd886ed1a18683c553ec/modules/dbnd/src/dbnd/_vendor/cloudpickle/cloudpickle_fast.py#L504-L509
import _collections_abc import abc import copyreg import io import itertools import logging import sys import struct import types import weakref import typing from enum import Enum from collections import ChainMap from .compat import pickle, Pickler from .cloudpickle import ( _extract_code_globals, _BUILTIN_TYPE_NA...
Apache License 2.0
bfreskura/kindle_note_parser
export.py
choose_export
python
def choose_export(export_index, template_dir): author = input( "Enter your name (this will appear on the top of the document): ") if export_index == 0: return exporter.ExportTex(author_name=author, template_path=choose_template( ...
Choose export object based on the user input :param template_dir: Templates directory path :param export_index: Index which was input by user :return: Export object
https://github.com/bfreskura/kindle_note_parser/blob/f560a3146a9199a39a21f1b9261b5e8ab07dd9a7/export.py#L37-L61
import argparse import collections import sys from constants import * from export import exporter from raw_parser import raw_parser def choose_template(template_dir, extension): print("Available templates for the specified format: ") available = {id: name for id, name in enumerate(os.listdir(template_dir)) if ...
MIT License
skamithi/ansible-tower-ldap-settings
library/tower_ldap_settings.py
transform_ldap_group_type
python
def transform_ldap_group_type(group_type): transformed_group_type = '' if group_type == 'NestedActiveDirectoryGroupType': transformed_group_type = 'active_directory' elif group_type == 'NestedGroupOfNamesType': transformed_group_type = 'open_ldap' elif group_type == 'active_directory': ...
This transformation function takes a group type name. If the group type name matches this module group_type options then it outputs the Tower API equivalent output. And the reverse is true.
https://github.com/skamithi/ansible-tower-ldap-settings/blob/24c59dbcb935177803a3720c5c00d91fe54fa4b9/library/tower_ldap_settings.py#L402-L422
from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community'} DOCUMENTATION = ''' --- module: tower_ldap_settings author: "Stanley Karunditu (@linuxsimba)" s...
MIT License
muyeby/amr-dialogue
DialogRG/nn_utils.py
PositionalEncoding.forward
python
def forward(self, x): x = x + self.pe[: x.size(0), :] return self.dropout(x)
r"""Inputs of forward function Args: x: the sequence fed to the positional encoder model (required). Shape: x: [sequence length, batch size, embed dim] output: [sequence length, batch size, embed dim] Examples: >>> output = pos_encoder(x)
https://github.com/muyeby/amr-dialogue/blob/261535c407be6c166016e4759bc81176b1c99957/DialogRG/nn_utils.py#L79-L91
import numpy as np import copy import math import torch import torch.nn as nn from torch.nn import ModuleList import torch.nn.functional as F def has_nan(tensor): return torch.isnan(tensor).any().item() def _get_activation_fn(activation): if activation == "relu": return F.relu elif activation == "ge...
MIT License
sorsnce/red-team
1. Information Gathering/recon-ng/recon/mixins/threads.py
ThreadingMixin._thread_wrapper
python
def _thread_wrapper(self, *args): thread_name = threading.current_thread().name self.debug(f"THREAD => {thread_name} started.") while not self.stopped.is_set(): try: obj = self.q.get_nowait() except Empty: continue try: ...
Wrapper for the worker method defined in the module. Handles calling the actual worker, cleanly exiting upon interrupt, and passing exceptions back to the main process.
https://github.com/sorsnce/red-team/blob/5cd1932ccafcd2c1b92b8642e9a64fa0d2e99324/1. Information Gathering/recon-ng/recon/mixins/threads.py#L7-L27
from queue import Queue, Empty import threading import time class ThreadingMixin(object):
MIT License
ngsutils/ngsutils
ngsutils/bam/count/count.py
_calc_read_regions
python
def _calc_read_regions(read): regions = [] start = read.pos end = read.pos for op, length in read.cigar: if op == 0: end += length elif op == 1: pass elif op == 2: end += length elif op == 3: regions.append((start, end)) ...
Find regions of reference the read covers - breaking on long gaps (N)
https://github.com/ngsutils/ngsutils/blob/417e90dc1918fb553dd84990f2c54bd8cea8f44d/ngsutils/bam/count/count.py#L196-L215
import ngsutils.support.stats import sys import tempfile import ngsutils from ngsutils.bam.t import MockBam assert(MockBam) class TmpCountFile(object): def __init__(self): self.tmpfile = tempfile.TemporaryFile() def write(self, count, coding_len, cols): self.tmpfile.write('%s\t%s\t%s\n' % (cou...
BSD 3-Clause New or Revised License
sfanous/pyecobee
pyecobee/objects/report_job.py
ReportJob.status
python
def status(self): return self._status
Gets the status attribute of this ReportJob instance. :return: The value of the status attribute of this ReportJob instance. :rtype: six.text_type
https://github.com/sfanous/pyecobee/blob/3d6b4aec3c6bc9b796aa3d3fd6626909ffdbac13/pyecobee/objects/report_job.py#L64-L73
from pyecobee.ecobee_object import EcobeeObject class ReportJob(EcobeeObject): __slots__ = ['_job_id', '_status', '_message', '_files'] attribute_name_map = { 'job_id': 'jobId', 'jobId': 'job_id', 'status': 'status', 'message': 'message', 'files': 'files', } attri...
MIT License
jamescooke/flake8-aaa
tests/command_line/test_do_command_line.py
example_file
python
def example_file(tmpdir): f = tmpdir.join('example_file.py') f.write(""" def test(): do_stuff() def test_other(): do_other_stuff() """) f.name = 'example_file.py' return f
Returns: file: Test file like argparse returns which has a 'name' property. This is deliberately named to not look like a test file - which means that the command line functionality of running files regardless of if they're a test file or not can be tested.
https://github.com/jamescooke/flake8-aaa/blob/bc7970d925e43c1fb558dd22533edaabf283f39e/tests/command_line/test_do_command_line.py#L10-L27
import ast import pytest from flake8_aaa.command_line import do_command_line from flake8_aaa.helpers import find_test_functions, is_test_file @pytest.fixture
MIT License
dmlc/gluon-nlp
src/gluonnlp/models/transformer.py
transformer_base
python
def transformer_base(): cfg = CN() cfg.MODEL = CN() cfg.MODEL.src_vocab_size = -1 cfg.MODEL.tgt_vocab_size = -1 cfg.MODEL.max_src_length = -1 cfg.MODEL.max_tgt_length = -1 cfg.MODEL.scale_embed = True cfg.MODEL.pos_embed_type = "sinusoidal" cfg.MODEL.shared_embed = True cfg.MODEL...
Configuration of Transformer WMT EN-DE Base
https://github.com/dmlc/gluon-nlp/blob/5d4bc9eba7226ea9f9aabbbd39e3b1e886547e48/src/gluonnlp/models/transformer.py#L27-L74
__all__ = ['transformer_cfg_reg', 'transformer_base', 'transformer_base_prenorm', 'transformer_iwslt_de_en', 'transformer_wmt_en_de_big', 'transformer_wmt_en_de_big_t2t', 'TransformerEncoderLayer', 'TransformerDecoderLayer', 'TransformerEncoder', 'TransformerDecode...
Apache License 2.0
quantaxis/quantaxis
QUANTAXIS/QASU/save_binance.py
QA_SU_save_binance
python
def QA_SU_save_binance(frequency): if (frequency not in ["1d", "1day", "day"]): return QA_SU_save_binance_min(frequency) else: return QA_SU_save_binance_day(frequency)
Save binance kline "smart"
https://github.com/quantaxis/quantaxis/blob/910cecae70ede6825f5ff58bb1d2186b6fb3dd1d/QUANTAXIS/QASU/save_binance.py#L66-L73
import datetime import time from dateutil.tz import tzutc from dateutil.relativedelta import relativedelta import pandas as pd from QUANTAXIS.QAUtil import ( DATABASE, QASETTING, QA_util_log_info, QA_util_log_expection, QA_util_to_json_from_pandas ) from QUANTAXIS.QAUtil.QADate_Adv import ( QA_u...
MIT License
neccam/slt
signjoey/helpers.py
log_data_info
python
def log_data_info( train_data: Dataset, valid_data: Dataset, test_data: Dataset, gls_vocab: GlossVocabulary, txt_vocab: TextVocabulary, logging_function: Callable[[str], None], ): logging_function( "Data set sizes: \n\ttrain {:d},\n\tvalid {:d},\n\ttest {:d}".format( len(...
Log statistics of data and vocabulary. :param train_data: :param valid_data: :param test_data: :param gls_vocab: :param txt_vocab: :param logging_function:
https://github.com/neccam/slt/blob/90588825f6229474bc19ac7a6b30ea3116635ba3/signjoey/helpers.py#L118-L162
import copy import glob import os import os.path import errno import shutil import random import logging from sys import platform from logging import Logger from typing import Callable, Optional import numpy as np import torch from torch import nn, Tensor from torchtext.data import Dataset import yaml from signjoey.voc...
Apache License 2.0
hpac/elaps
elaps/backends/lsf.py
Backend.__init__
python
def __init__(self, header="#!/bin/bash -l\n#BSUB -o /dev/null\n"): self.jobs = [] self.header = header
Initialize the backend.
https://github.com/hpac/elaps/blob/390bbe8cbeb056ef57adbc91cdf5bcd1f7cbe187/elaps/backends/lsf.py#L13-L16
import subprocess import re class Backend(object): name = "lsf"
BSD 3-Clause New or Revised License
webkom/lego
lego/apps/ical/viewsets.py
ICalViewset.list
python
def list(self, request): token = ICalToken.objects.get_or_create(user=request.user)[0] path = request.get_full_path() data = { "result": { "calendars": [ { "name": "events", "description": "Calendar w...
List all the different icals.
https://github.com/webkom/lego/blob/90204aca73fe1f22df4e356e35baf12e943f9fc7/lego/apps/ical/viewsets.py#L55-L81
from datetime import timedelta from django.utils import timezone from rest_framework import decorators, permissions, viewsets from rest_framework.permissions import IsAuthenticated from rest_framework.response import Response from rest_framework.settings import api_settings from lego.apps.events.models import Event fro...
MIT License
bluemirrors/cvu
cvu/detector/yolov5/backends/yolov5_tensorflow.py
Yolov5.__init__
python
def __init__(self, weight: str = "yolov5s", device='auto') -> None: self._model = None self._device = None self._loaded = None logging.disable(logging.WARNING) os.environ["TF_CPP_MIN_LOG_LEVEL"] = "3" self._set_device(device) self._load_model(weight)
Initiate Model Args: weight (str, optional): path to SavedModel weight files. Alternatively, it also accepts identifiers (such as yolvo5s, yolov5m, etc.) to load pretrained models. Defaults to "yolov5s". device (str, optional): name of the device to be used. Val...
https://github.com/bluemirrors/cvu/blob/2eb10c5844d7cde2a54d2334d9fb8642bccf2b66/cvu/detector/yolov5/backends/yolov5_tensorflow.py#L32-L57
import logging import os from typing import List import numpy as np import tensorflow as tf from tensorflow.keras import mixed_precision from cvu.interface.model import IModel from cvu.utils.general import get_path from cvu.detector.yolov5.backends.common import download_weights from cvu.postprocess.bbox import denorma...
Apache License 2.0
saevon/webdnd
player/modifier_obj.py
ModField.get
python
def get(self): return self._value['value']
Returns the value of this field
https://github.com/saevon/webdnd/blob/4dd5d30ae105ede51bbd92bf5281a6965b7d55f4/player/modifier_obj.py#L58-L62
from collections import defaultdict from itertools import chain from webdnd.shared.utils.decorators import cascade, dirty_cache class StatVal(dict): def __init__(self, value, stats=None): super(StatVal, self).__init__(stats or {}) self['value'] = value class ModField(object): def __init__(self, ...
MIT License
ndrplz/computer_vision_utils
io_helper.py
write_image
python
def write_image(img_path, img, channels_first=False, color_mode='BGR', resize_dim=None, to_normalize=False): color = True if img.ndim == 3 else False if color and channels_first: img = img.transpose(1, 2, 0) if color and color_mode == 'RGB': img = cv2.cvtColor(img, cv2.COLOR_RGB2BGR) if ...
Writes an image (numpy array) on file Parameters ---------- img_path : string Path where to save image img : ndarray Image that has to be saved channels_first: bool Set this True if shape is (c, h, w) color_mode: "RGB", "BGR", optional Whether the image is in RGB...
https://github.com/ndrplz/computer_vision_utils/blob/869ca8d5dcd6a95392d67127aa2a43042b33993c/io_helper.py#L49-L85
import cv2 import numpy as np import os.path as path def read_image(img_path, channels_first, color=True, color_mode='BGR', dtype=np.float32, resize_dim=None): if not path.exists(img_path): raise ValueError('Provided path "{}" does NOT exist.'.format(img_path)) image = cv2.imread(img_path, cv2.IMREAD_CO...
MIT License
quay/quay
data/logs_model/document_logs_model.py
_date_range_in_single_index
python
def _date_range_in_single_index(dt1, dt2): assert isinstance(dt1, date) and isinstance(dt2, date) dt = dt2 - dt1 if not isinstance(dt1, datetime) and not isinstance(dt2, datetime): return dt == timedelta(days=1) if dt < timedelta(days=1) and dt >= timedelta(days=0): return dt2.day == dt1...
Determine whether a single index can be searched given a range of dates or datetimes. If date instances are given, difference should be 1 day. NOTE: dt2 is exclusive to the search result set. i.e. The date range is larger or equal to dt1 and strictly smaller than dt2
https://github.com/quay/quay/blob/f50f37a393fa2273234f8ac0aa9f34a03a77a731/data/logs_model/document_logs_model.py#L72-L95
import json import logging import uuid from time import time from datetime import timedelta, datetime, date from dateutil.parser import parse as parse_datetime from abc import ABCMeta, abstractmethod from six import add_metaclass from elasticsearch.exceptions import ConnectionTimeout, NotFoundError from data import mod...
Apache License 2.0
2ndwatch/cloudendure-python
cloudendure/cloudendure_api/models/cloud_endure_account_request.py
CloudEndureAccountRequest.email
python
def email(self): return self._email
Gets the email of this CloudEndureAccountRequest. # noqa: E501 :return: The email of this CloudEndureAccountRequest. # noqa: E501 :rtype: str
https://github.com/2ndwatch/cloudendure-python/blob/f81d1be1422b7c19adedb06c584803eaaa811919/cloudendure/cloudendure_api/models/cloud_endure_account_request.py#L124-L131
import pprint import re import six class CloudEndureAccountRequest: """ Attributes: swagger_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The key is attribute name and the value is json key in ...
MIT License
restran/fomalhaut
fomalhaut/tests/api_client.py
HMACHandler.response_headers_to_sign
python
def response_headers_to_sign(self, headers): headers_to_sign = {} for name, value in iteritems(headers): if name.startswith(HEADER_X_PREFIX): headers_to_sign[name] = value return headers_to_sign
Select the headers from the request that need to be included in the StringToSign.
https://github.com/restran/fomalhaut/blob/df6762f3aa64c0c0ca50dd8bfd6f2a70b0bced7b/fomalhaut/tests/api_client.py#L80-L90
from __future__ import unicode_literals, absolute_import import hmac import json as json_util import logging import random import time import traceback from base64 import urlsafe_b64encode from hashlib import sha1 import requests from future.moves.urllib.parse import urlparse, urlunparse, urlencode from future.utils im...
MIT License
olitheolix/aiokubernetes
aiokubernetes/models/v1_ip_block.py
V1IPBlock.__init__
python
def __init__(self, cidr=None, _except=None): self._cidr = None self.__except = None self.discriminator = None self.cidr = cidr if _except is not None: self._except = _except
V1IPBlock - a model defined in Swagger
https://github.com/olitheolix/aiokubernetes/blob/266718b210dff2a9b2212183261ea89adf89115e/aiokubernetes/models/v1_ip_block.py#L42-L51
import pprint import re class V1IPBlock(object): """ Attributes: swagger_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The key is attribute name and the value is json key in definition. """...
Apache License 2.0
hibou57/postiats-utilities
postiats/lexemes.py
get_e
python
def get_e(source): return get_char_of_category(source, d.E)
Try to read `E`?.
https://github.com/hibou57/postiats-utilities/blob/2148016083490ba1aeac04fe0f4a3983cd18c707/postiats/lexemes.py#L133-L135
from . import lexemes_defs as d from .lexemes_defs import (Fin, NonFin, Start) class Input: __slots__ = ["source", "length", "pos"] def __init__(self, source): self.source = source self.length = len(source) self.pos = 0 def char(self, offset=0): i = self.pos + offset ...
BSD 2-Clause Simplified License
ieeerobotics/bot
bot/driver/mec_driver.py
MecDriver.rough_rotate_90
python
def rough_rotate_90(self, direction, r_speed=50, r_time=1): if direction == "right": r_speed = -r_speed self.rotate(r_speed) sleep(r_time) self.rotate(0)
rotates 90 degrees by blindly turning.
https://github.com/ieeerobotics/bot/blob/9228b00f55ec949f3c39a0020a1e0f61dc64d601/bot/driver/mec_driver.py#L314-L324
from math import sin, cos, pi, fabs, hypot, atan2, degrees from time import sleep import bot.lib.lib as lib import bot.driver.driver as driver from bot.hardware.dmcc_motor import DMCCMotorSet class MecDriver(driver.Driver): min_speed = 0 max_speed = 100 min_angle = -360 max_angle = 360 min_angular_r...
BSD 2-Clause Simplified License
contextlab/hypertools
hypertools/_externals/srm.py
SRM._srm
python
def _srm(self, data): samples = data[0].shape[1] subjects = len(data) np.random.seed(self.rand_seed) w, voxels = _init_w_transforms(data, self.features) x, mu, rho2, trace_xtx = self._init_structures(data, subjects) shared_response = np.zeros((self.features, samples)) ...
Expectation-Maximization algorithm for fitting the probabilistic SRM. Parameters ---------- data : list of 2D arrays, element i has shape=[voxels_i, samples] Each element in the list contains the fMRI data of one subject. Returns ------- sigma_s : array, ...
https://github.com/contextlab/hypertools/blob/948050a22b345c7dcccf729672c76f49609b1ac8/hypertools/_externals/srm.py#L319-L431
from __future__ import division import logging import numpy as np import scipy from sklearn.base import BaseEstimator, TransformerMixin from sklearn.utils import assert_all_finite from sklearn.utils.validation import NotFittedError __all__ = [ "SRM", "DetSRM" ] logger = logging.getLogger(__name__) def _init_w_trans...
MIT License
mavensdc/cdflib
cdflib/cdfwrite.py
CDF.write_variableattrs
python
def write_variableattrs(self, variableAttrs): if not (isinstance(variableAttrs, dict)): raise ValueError('Variable attribute(s) not in dictionary form') dataType = None numElems = None with self.path.open('rb+') as f: f.seek(0, 2) for attr, attrs in ...
Writes a variable's attributes, provided the variable already exists. Parameters ---------- variableAttrs : dict Variable attribute name and its entry value pair(s). The entry value is also a dictionary of variable id and value pair(s). Variable id can be th...
https://github.com/mavensdc/cdflib/blob/e0b57ed32ab74197d2c9aa4ff948bb92593da5fd/cdflib/cdfwrite.py#L456-L622
from typing import Tuple import logging import numpy as np import sys import struct import gzip import hashlib import platform as pf import binascii import cdflib.epochs as cdfepoch import numbers import math import pathlib import warnings def is_open(func): def ensure_open(self, *args, **kwargs): if self.i...
MIT License
fusionauth/fusionauth-python-client
src/main/python/fusionauth/fusionauth_client.py
FusionAuthClient.action_user
python
def action_user(self, request): return self.start().uri('/api/user/action') .body_handler(JSONBodyHandler(request)) .post() .go()
Takes an action on a user. The user being actioned is called the "actionee" and the user taking the action is called the "actioner". Both user ids are required in the request object. Attributes: request: The action request that includes all of the information about the action being taken in...
https://github.com/fusionauth/fusionauth-python-client/blob/20bf313710eb0af6bfb9c07b7864b52fe5853eb0/src/main/python/fusionauth/fusionauth_client.py#L39-L51
from deprecated import deprecated from fusionauth.rest_client import RESTClient, JSONBodyHandler, FormDataBodyHandler class FusionAuthClient: def __init__(self, api_key, base_url): self.api_key = api_key self.base_url = base_url self.tenant_id = None def set_tenant_id(self, tenant_id): ...
Apache License 2.0
sberbank-ai-lab/lightautoml
lightautoml/reader/base.py
Reader.fit_read
python
def fit_read( self, train_data: Any, features_names: Optional[List[str]] = None, roles: UserRolesDefinition = None, **kwargs: Any ): raise NotImplementedError
Abstract function to get dataset with initial feature selection.
https://github.com/sberbank-ai-lab/lightautoml/blob/51a4e2bd0ebffbe0817fb50434280f8e7c40fa4c/lightautoml/reader/base.py#L100-L108
import logging from copy import deepcopy from typing import Any from typing import Dict from typing import List from typing import Optional from typing import Sequence from typing import TypeVar from typing import Union from typing import cast import numpy as np import pandas as pd from pandas import DataFrame from pan...
Apache License 2.0
tcalmant/ipopo
pelix/utilities.py
EventData.data
python
def data(self): return self.__data
Returns the associated value
https://github.com/tcalmant/ipopo/blob/1d4b81207e67890dfccc8f562336c7104f194c17/pelix/utilities.py#L596-L601
import collections import contextlib import functools import inspect import logging import sys import threading import traceback try: from typing import Any, Optional, Union except ImportError: pass import pelix.constants __version_info__ = (1, 0, 1) __version__ = ".".join(str(x) for x in __version_info__) __do...
Apache License 2.0
readthedocs/readthedocs.org
readthedocs/oauth/migrations/0006_move_oauth_source.py
forwards_move_org_source
python
def forwards_move_org_source(apps, schema_editor): RemoteOrganization = apps.get_model('oauth', 'RemoteOrganization') SocialAccount = apps.get_model('socialaccount', 'SocialAccount') for account in SocialAccount.objects.all(): rows = (RemoteOrganization.objects .filter(users=account....
Use source field to set organization account.
https://github.com/readthedocs/readthedocs.org/blob/2cff8376f0ef8f25ae6d8763bdbec86f47e33ab9/readthedocs/oauth/migrations/0006_move_oauth_source.py#L23-L30
from django.db import migrations def forwards_move_repo_source(apps, schema_editor): RemoteRepository = apps.get_model('oauth', 'RemoteRepository') SocialAccount = apps.get_model('socialaccount', 'SocialAccount') for account in SocialAccount.objects.all(): rows = (RemoteRepository.objects ...
MIT License
dnandha/mopac
softlearning/scripts/console_scripts.py
launch_example_ec2_cmd
python
def launch_example_ec2_cmd(*args, **kwargs): return launch_example_ec2(*args, **kwargs)
Forwards call to `launch_example_cluster` after adding ec2 defaults. This optionally sets the ray autoscaler configuration file to the default ec2 configuration file, and then calls `launch_example_cluster` to execute the original command on autoscaled ec2 cluster by parsing the args. See `launch_exam...
https://github.com/dnandha/mopac/blob/058128183d16b7f8dcdaf2758a38b10f348566aa/softlearning/scripts/console_scripts.py#L174-L183
from __future__ import absolute_import from __future__ import division from __future__ import print_function import logging import click from mopac.examples.instrument import ( run_example_dry, run_example_local, run_example_debug, run_example_cluster, launch_example_cluster, launch_example_gce,...
MIT License
coarse-graining/cgnet
cgnet/feature/utils.py
ShiftedSoftplus.forward
python
def forward(self, input_tensor): return nn.functional.softplus(input_tensor) - np.log(2.0)
Applies the shifted softplus function element-wise Parameters ---------- input_tensor: torch.Tensor Input tensor of size (n_examples, *) where `*` means, any number of additional dimensions. Returns ------- Output: torch.Tensor Same s...
https://github.com/coarse-graining/cgnet/blob/ce7dadb1f8e66771032275ef87b8193ad234d495/cgnet/feature/utils.py#L39-L53
import numpy as np import torch import torch.nn as nn class ShiftedSoftplus(nn.Module): def __init__(self): super(ShiftedSoftplus, self).__init__()
BSD 3-Clause New or Revised License
labd/commercetools-python-sdk
src/commercetools/services/reviews.py
ReviewService.create
python
def create(self, draft: ReviewDraft, *, expand: OptionalListStr = None) -> Review: params = self._serialize_params({"expand": expand}, traits.ExpandableSchema) return self._client._post( endpoint="reviews", params=params, data_object=draft, response_class=Review )
Reviews are used to evaluate products and channels.
https://github.com/labd/commercetools-python-sdk/blob/d8ec285f08d56ede2e4cad45c74833f5b609ab5c/src/commercetools/services/reviews.py#L79-L84
import typing from commercetools.helpers import RemoveEmptyValuesMixin from commercetools.platform.models.review import ( Review, ReviewDraft, ReviewPagedQueryResponse, ReviewUpdate, ReviewUpdateAction, ) from commercetools.typing import OptionalListStr from . import abstract, traits class _ReviewQu...
MIT License
nrel/rdtools
rdtools/analysis_chains.py
TrendAnalysis.set_clearsky
python
def set_clearsky(self, pvlib_location=None, pv_azimuth=None, pv_tilt=None, poa_global_clearsky=None, temperature_cell_clearsky=None, temperature_ambient_clearsky=None, albedo=0.25, solar_position_method='nrel_numpy'): max_timedelta = self.max_timede...
Initialize values for a clearsky analysis which requires configuration of location and orientation details. If optional parameters `poa_global_clearsky`, `temperature_ambient_clearsky` are not passed, they will be modeled based on location and orientation. Parameters ---------- ...
https://github.com/nrel/rdtools/blob/4ca70e3e2cec85fead10cb8e6ef5e098eeb6f686/rdtools/analysis_chains.py#L140-L201
import pvlib import pandas as pd import numpy as np import matplotlib.pyplot as plt from rdtools import normalization, filtering, aggregation, degradation from rdtools import clearsky_temperature, plotting import warnings class TrendAnalysis(): def __init__(self, pv, poa_global=None, temperature_cell=None, temperat...
MIT License
mrknow/filmkodi
plugin.video.mrknow/mylib/pydevd_attach_to_process/winappdbg/breakpoint.py
Breakpoint.set_action
python
def set_action(self, action = None): self.__action = action
Sets a new action callback for the breakpoint. @type action: function @param action: (Optional) Action callback function.
https://github.com/mrknow/filmkodi/blob/0162cde9ae25ddbf4a69330948714833ff2f78c9/plugin.video.mrknow/mylib/pydevd_attach_to_process/winappdbg/breakpoint.py#L382-L389
__revision__ = "$Id$" __all__ = [ 'Breakpoint', 'CodeBreakpoint', 'PageBreakpoint', 'HardwareBreakpoint', 'Hook', 'ApiHook', 'BufferWatch', 'BreakpointWarning', 'BreakpointCallbackWarning', ] from winappdbg import win32 from winappdbg import compat import sys from winappdbg.proce...
Apache License 2.0
rustychris/stompy
stompy/model/fish_ptm/ptm_tools.py
PtmBin.dt_seconds
python
def dt_seconds(self): dnum1,data = self.read_timestep(0) dnum2,data = self.read_timestep(1) return (dnum2-dnum1).total_seconds()
Return the bin file output interval in decimal seconds.
https://github.com/rustychris/stompy/blob/ef04d8b3ee9c9af827c87c72c7b50d365e5e567d/stompy/model/fish_ptm/ptm_tools.py#L131-L137
import os import time import numpy as np import xarray as xr from datetime import datetime import matplotlib.pyplot as plt from ...spatial import wkb2shp from ... import memoize, utils import pandas as pd class PtmBin(object): use_memmap=True fp=None def __init__(self,fn,release_name=None,idx_fn='auto'): ...
MIT License
digital-concrete/light-sync
phue_lib.py
Sensor.state
python
def state(self): data = self._get('state') self._state.clear() self._state.update(data) return self._state
A dictionary of sensor state. Some values can be updated, some are read-only. [dict]
https://github.com/digital-concrete/light-sync/blob/b2f8405971b6204f4d43f5a63ae91381462913f2/phue_lib.py#L412-L417
import json import logging import os import platform import sys import socket if sys.version_info[0] > 2: PY3K = True else: PY3K = False if PY3K: import http.client as httplib else: import httplib logger = logging.getLogger('phue') if platform.system() == 'Windows': USER_HOME = 'USERPROFILE' else: ...
MIT License
berkeley-reclab/reclab
reclab/environments/latent_factors.py
LatentFactorBehavior._get_rating
python
def _get_rating(self, user_id, item_id): raw_rating = (self._user_factors[user_id] @ self._item_factors[item_id] + self._user_biases[user_id] + self._item_biases[item_id] + self._offset) boredom_penalty = 0 for item_id_hist in self._user_histories[user_id]: item...
Compute user's rating of item based on model. Parameters ---------- user_id : int The id of the user making the rating. item_id : int The id of the item being rated. Returns ------- rating : int The rating the item was given b...
https://github.com/berkeley-reclab/reclab/blob/09d5b1639e9b7f6cbd230f181130b681e31cf4f0/reclab/environments/latent_factors.py#L100-L133
import collections import json import os import numpy as np from . import environment from .. import data_utils class LatentFactorBehavior(environment.DictEnvironment): def __init__(self, latent_dim, num_users, num_items, rating_frequency=0.02, num_init_ratings=0, noise=0.0, memory...
MIT License
thunlp-mt/pr4nmt
thumt/nmt.py
RNNsearch.get_attention
python
def get_attention(self, x, xmask, y, ymask): if not hasattr(self, "get_attentioner"): self.get_attentioner = theano.function(inputs = [self.x, self.xmask, self.y, self.ymask], outputs = [self.attention]) return self.get_attentioner(x, xmask, y, ymask)
Get the attention weight of parallel sentences.
https://github.com/thunlp-mt/pr4nmt/blob/104766db729f2babe1db69c5b10a1aa45f578bf3/thumt/nmt.py#L508-L515
import numpy import theano import theano.tensor as tensor from theano.sandbox.rng_mrg import MRG_RandomStreams as RandomStreams import tools from layer import LayerFactory import json import traceback import cPickle import logging class model(object): def __init__(self): pass def sample(self, x, length, n_samples =...
BSD 3-Clause New or Revised License
rapid7/vm-console-client-python
rapid7vmconsole/models/scan_template_vulnerability_checks.py
ScanTemplateVulnerabilityChecks.unsafe
python
def unsafe(self, unsafe): self._unsafe = unsafe
Sets the unsafe of this ScanTemplateVulnerabilityChecks. Whether checks considered \"unsafe\" are assessed during a scan. # noqa: E501 :param unsafe: The unsafe of this ScanTemplateVulnerabilityChecks. # noqa: E501 :type: bool
https://github.com/rapid7/vm-console-client-python/blob/55e1f573967bce27cc9a2d10c12a949b1142c2b3/rapid7vmconsole/models/scan_template_vulnerability_checks.py#L228-L237
import pprint import re import six class ScanTemplateVulnerabilityChecks(object): """ Attributes: swagger_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The key is attribute name and the value i...
MIT License
missionpinball/mpf
mpf/core/platform.py
DriverPlatform.__init__
python
def __init__(self, machine): super().__init__(machine) self.features['has_drivers'] = True self.features['max_pulse'] = 255
Add driver feature and default max_pulse length.
https://github.com/missionpinball/mpf/blob/1eda6ba6892b8f7cc6dedf6cb6472ff92293b8ef/mpf/core/platform.py#L513-L520
import abc import asyncio from collections import namedtuple from enum import Enum from typing import Optional, Dict, List from mpf.core.logging import LogMixin from mpf.core.utility_functions import Util MYPY = False if MYPY: from mpf.devices.switch import Switch from mpf.devices.stepper import Stepper ...
MIT License
opennetworkingfoundation/tapi
RI/flask_server/tapi_server/models/tapi_connectivity_context_augmentation4.py
TapiConnectivityContextAugmentation4.__init__
python
def __init__(self, connectivity_context=None): self.openapi_types = { 'connectivity_context': TapiConnectivityConnectivityContext } self.attribute_map = { 'connectivity_context': 'connectivity-context' } self._connectivity_context = connectivity_context
TapiConnectivityContextAugmentation4 - a model defined in OpenAPI :param connectivity_context: The connectivity_context of this TapiConnectivityContextAugmentation4. # noqa: E501 :type connectivity_context: TapiConnectivityConnectivityContext
https://github.com/opennetworkingfoundation/tapi/blob/1f3fd9483d5674552c5a31206c97399c8c151897/RI/flask_server/tapi_server/models/tapi_connectivity_context_augmentation4.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_connectivity_connectivity_context import TapiConnectivityConnectivityContext from tapi_server import util class TapiConnectivityCon...
Apache License 2.0
datadotworld/data.world-py
datadotworld/client/_swagger/models/oauth_token_reference.py
OauthTokenReference.owner
python
def owner(self, owner): if owner is None: raise ValueError("Invalid value for `owner`, must not be `None`") if owner is not None and len(owner) > 31: raise ValueError("Invalid value for `owner`, length must be less than or equal to `31`") if owner is not None and len(owne...
Sets the owner of this OauthTokenReference. User name of the owner of the OAuth token within data.world. :param owner: The owner of this OauthTokenReference. :type: str
https://github.com/datadotworld/data.world-py/blob/7e5f474b655f4f0c88cc6862353e4d52c0e0bb31/datadotworld/client/_swagger/models/oauth_token_reference.py#L93-L110
from pprint import pformat from six import iteritems import re class OauthTokenReference(object): """ Attributes: swagger_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The key is attribute name a...
Apache License 2.0
geoscienceaustralia/agdc
tests/test_landsat_tiler.py
TestLandsatTiler.get_tile_pathnames
python
def get_tile_pathnames(expected_conn, output_conn): sql = """-- Retrieve list of tile.tile_pathname from each database select tile_type_id, tile_pathname from tile where tile_class_id = 1 """ db_cursor = expected_conn.cursor() db_cursor.exe...
From two different databases, get the tile pathnames from the tile table. Return each as a dictionary of {basename: (tile_type_id, full path)}
https://github.com/geoscienceaustralia/agdc/blob/2e22c6bdd9305555db3615305ff6a5df6219cd51/tests/test_landsat_tiler.py#L503-L521
import sys import os import subprocess import unittest import dbutil import dbcompare from osgeo import gdal import numpy import re class TestLandsatTiler(unittest.TestCase): def process_args(self): MODULE = 'new_ingest_benchmark' SUITE = 'benchmark' self.INPUT_DIR = dbutil.input_directory(M...
BSD 3-Clause New or Revised License
faucetsdn/ryu
ryu/lib/bfdlib.py
ARPPacket.arp_packet
python
def arp_packet(opcode, src_mac, src_ip, dst_mac, dst_ip): pkt = packet.Packet() eth_pkt = ethernet.ethernet(dst_mac, src_mac, ETH_TYPE_ARP) pkt.add_protocol(eth_pkt) arp_pkt = arp.arp_ip(opcode, src_mac, src_ip, dst_mac, dst_ip) pkt.add_protocol(arp_pkt) pkt.serialize() ...
Generate ARP packet with ethernet encapsulated.
https://github.com/faucetsdn/ryu/blob/537f35f4b2bc634ef05e3f28373eb5e24609f989/ryu/lib/bfdlib.py#L596-L610
import logging import time import random import six from ryu.base import app_manager from ryu.controller import event from ryu.controller import ofp_event from ryu.controller.handler import CONFIG_DISPATCHER, MAIN_DISPATCHER from ryu.controller.handler import set_ev_cls from ryu.exception import RyuException from ryu.o...
Apache License 2.0
hewlettpackard/python-ilorest-library-old
src/redfish/ris/rmc_helper.py
RmcClient.get_cache_dirname
python
def get_cache_dirname(self): parts = urlparse2.urlparse(self.get_base_url()) pathstr = '%s/%s' % (parts.netloc, parts.path) return pathstr.replace('//', '/')
The rest client's current base URL converted to path
https://github.com/hewlettpackard/python-ilorest-library-old/blob/b00fd417024485a77c4f71f913135831d674a177/src/redfish/ris/rmc_helper.py#L224-L228
import os import json import errno import logging import hashlib import urlparse2 import redfish.rest from .ris import (RisMonolith) from .sharedtypes import (JSONEncoder) from .config import (AutoConfigParser) LOGGER = logging.getLogger(__name__) class RdmcError(Exception): errcode = 1 def __init__(self, messa...
Apache License 2.0
sohamtriveous/dbdump
dbdump.py
del_folder
python
def del_folder(devicename, path): cmd = add_adb_device(devicename) cmd = cmd + 'shell rm -r ' new_cmd = cmd + path (status, output) = commands.getstatusoutput(new_cmd) if status: print 'Could not delete', path, sys.stderr return False else: return True
delete files at a particular path :param devicename: device :param path: path to be deleted :return:
https://github.com/sohamtriveous/dbdump/blob/f800723c40285df8dd22203990d902c4105ace7d/dbdump.py#L74-L91
__author__ = 'sohammondal' import sys import commands import re def exec_cmd(cmd): (status, output) = commands.getstatusoutput(cmd) if status: print 'Could not execute', cmd, sys.stderr return False return True def find_all(pat, string): matches = re.findall(pat, string) if matches: ...
Apache License 2.0
microsoft/dowhy
dowhy/causal_estimator.py
CausalEstimator._generate_bootstrap_estimates
python
def _generate_bootstrap_estimates(self, num_bootstrap_simulations, sample_size_fraction): simulation_results = np.zeros(num_bootstrap_simulations) sample_size = int(sample_size_fraction * len(self._data)) if sample_size > len(self._data): self.lo...
Helper function to generate causal estimates over bootstrapped samples. :param num_bootstrap_simulations: Number of simulations for the bootstrap method. :param sample_size_fraction: Fraction of the dataset to be resampled. :returns: A collections.namedtuple containing a list of bootstrapped es...
https://github.com/microsoft/dowhy/blob/9c1371efc580fde142cd2017bf7789e1a8e53814/dowhy/causal_estimator.py#L269-L313
import logging import numpy as np import pandas as pd import sympy as sp from collections import namedtuple from sklearn.utils import resample import dowhy.interpreters as interpreters from dowhy.utils.api import parse_state class CausalEstimator: DEFAULT_NUMBER_OF_SIMULATIONS_STAT_TEST = 1000 DEFAULT_NUMBER_OF...
MIT License
onshape-public/onshape-clients
python/onshape_client/oas/models/btp_statement_loop_for_in279.py
BTPStatementLoopForIn279.__init__
python
def __init__( self, _check_type=True, _from_server=False, _path_to_item=(), _configuration=None, **kwargs ): self._data_store = {} self._check_type = _check_type self._from_server = _from_server self._path_to_item = _path_to_item ...
btp_statement_loop_for_in279.BTPStatementLoopForIn279 - a model defined in OpenAPI Keyword Args: _check_type (bool): if True, values for parameters in openapi_types will be type checked and a TypeError will be raised if the wrong type ...
https://github.com/onshape-public/onshape-clients/blob/20843a00c628e516e7219e17a23ec4ef2bf9f16f/python/onshape_client/oas/models/btp_statement_loop_for_in279.py#L195-L279
from __future__ import absolute_import import re import sys import six import nulltype from onshape_client.oas.model_utils import ( ModelComposed, ModelNormal, ModelSimple, date, datetime, file_type, int, none_type, str, validate_get_composed_info, ) try: from onsha...
MIT License
pelioniot/mbed-cloud-sdk-python
src/mbed_cloud/_backends/iam/models/account_info.py
AccountInfo.idle_timeout
python
def idle_timeout(self): return self._idle_timeout
Gets the idle_timeout of this AccountInfo. The reference token expiration time in minutes for this account. :return: The idle_timeout of this AccountInfo. :rtype: str
https://github.com/pelioniot/mbed-cloud-sdk-python/blob/71dc67fc2a8d1aff31e35ec781fb328e6a60639c/src/mbed_cloud/_backends/iam/models/account_info.py#L557-L565
from pprint import pformat from six import iteritems import re class AccountInfo(object): """ Attributes: swagger_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The key is attribute name and the v...
Apache License 2.0
paulgilmartin/graph_wrap
graph_wrap/tastypie/api_transformer.py
field_transformer
python
def field_transformer(tastypie_field): try: transformer_class = FieldTransformerMeta.registry[ (tastypie_field.dehydrated_type, tastypie_field.is_m2m)] except KeyError: raise KeyError('Dehydrated type not recognized') return transformer_class(tastypie_field)
Instantiate the appropriate FieldTransformer class. This acts as a factory-type function, which, given a tastypie field as input, instantiates the appropriate concrete FieldTransformer class for that field.
https://github.com/paulgilmartin/graph_wrap/blob/7fff829dc7d2818c57de00d3055fc6c50fae7484/graph_wrap/tastypie/api_transformer.py#L42-L54
from __future__ import unicode_literals import json from abc import abstractmethod from decimal import Decimal as _Decimal import six from graphene import ( String, Int, Float, Boolean, Decimal, List, Field, Scalar, ObjectType, ) from graphene.types.generic import GenericScalar from ...
MIT License
ox-it/humfrey
humfrey/streaming/base.py
StreamingParser.get
python
def get(self): if self._cached_get is None: sparql_results_type = self.get_sparql_results_type() if sparql_results_type == 'resultset': self._cached_get = SparqlResultList(self.get_fields(), self.get_bindings()) elif sparql_results_type == 'boolean': ...
Returns an in-memory object representing the stream. You will either get a SparqlResultsList, a bool, or a ConjunctiveGraph.
https://github.com/ox-it/humfrey/blob/c92e46a24a9bf28aa9638a612f166d209315e76b/humfrey/streaming/base.py#L109-L132
import abc import types import rdflib from humfrey.sparql.results import SparqlResultList from humfrey.utils.namespaces import NS from humfrey.utils.statsd import statsd class ModeError(Exception): pass class StreamingParser(object): __metaclass__ = abc.ABCMeta def __init__(self, stream, encoding='utf-8'): ...
BSD 3-Clause New or Revised License
retr0h/gilt
gilt/shell.py
overlay
python
def overlay(ctx): args = ctx.obj.get("args") filename = args.get("config") debug = args.get("debug") _setup(filename) for c in config.config(filename): with fasteners.InterProcessLock(c.lock_file): util.print_info("{}:".format(c.name)) if not os.path.exists(c.src): ...
Install gilt dependencies
https://github.com/retr0h/gilt/blob/afb6e22f74d2c8a4d064a684964dc5fba0414f7a/gilt/shell.py#L80-L106
import os import click import click_completion import fasteners import gilt from gilt import config from gilt import git from gilt import util click_completion.init() class NotFoundError(Exception): pass @click.group() @click.option( "--config", default="gilt.yml", help="Path to config file. Default gi...
MIT License
kuri65536/python-for-android
python-modules/twisted/twisted/lore/tree.py
addMtime
python
def addMtime(document, fullpath): for node in domhelpers.findElementsWithAttribute(document, "class","mtime"): txt = dom.Text() txt.data = time.ctime(os.path.getmtime(fullpath)) node.appendChild(txt)
Set the last modified time of the given document. @type document: A DOM Node or Document @param document: The output template which defines the presentation of the last modified time. @type fullpath: C{str} @param fullpath: The file name from which to take the last modified time. @return: C{N...
https://github.com/kuri65536/python-for-android/blob/26402a08fc46b09ef94e8d7a6bbc3a54ff9d0891/python-modules/twisted/twisted/lore/tree.py#L63-L79
from itertools import count import re, os, cStringIO, time, cgi, string, urlparse from xml.dom import minidom as dom from xml.sax.handler import ErrorHandler, feature_validation from xml.dom.pulldom import SAX2DOM from xml.sax import make_parser from xml.sax.xmlreader import InputSource from twisted.python import htmli...
Apache License 2.0
autofitcloud/isitfit
isitfit/tags/tagsCsvDiff.py
TagsCsvDiff.droppedTags
python
def droppedTags(self): if len(self.old_minus_new)==0: return logger.info("There are %i deleted tag(s)"%len(self.old_minus_new)) logger.info("") old_processed = set() for ni in self.old_minus_new: confirm_msg = colored('Did you completely delete the tag "%s"? yes/[no] '%ni, 'cyan') ...
Identify if some tags are completely dropped. Ask the user if indeed dropped, or accident. Follows the idea of django/db/migrations/questioner.py where django asks if fields are renamed or dropped https://github.com/django/django/blob/e90af8bad44341cf8ebd469dac57b61a95667c1d/django/db/migrations/questio...
https://github.com/autofitcloud/isitfit/blob/6ffc0c67c00140120f5d5ad8dfe11c8f0f7dacc1/isitfit/tags/tagsCsvDiff.py#L121-L152
from isitfit.cli.click_descendents import IsitfitCliError from isitfit.utils import logger from termcolor import colored class TagsCsvDiff: def __init__(self, df_old, df_new): self.df_old = df_old self.df_new = df_new self.old_minus_new = set() self.new_minus_old = set() self.migrations = [] def...
Apache License 2.0
azure/autorest.python
test/vanilla/legacy/Expected/AcceptanceTests/ModelFlattening/modelflattening/operations/_auto_rest_resource_flattening_test_service_operations.py
AutoRestResourceFlatteningTestServiceOperationsMixin.put_dictionary
python
def put_dictionary( self, resource_dictionary=None, **kwargs ): cls = kwargs.pop("cls", None) error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} error_map.update(kwargs.pop("error_map", {})) content_type = ...
Put External Resource as a Dictionary. :param resource_dictionary: External Resource as a Dictionary to put. :type resource_dictionary: dict[str, ~modelflattening.models.FlattenedProduct] :keyword callable cls: A custom type or function that will be passed the direct response :return: N...
https://github.com/azure/autorest.python/blob/90d60a965788e3b4c0809e6686bdc3525acac89c/test/vanilla/legacy/Expected/AcceptanceTests/ModelFlattening/modelflattening/operations/_auto_rest_resource_flattening_test_service_operations.py#L470-L513
import functools from typing import TYPE_CHECKING import warnings from azure.core.exceptions import ( ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error, ) from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import Http...
MIT License
berkeleyautomation/autolab_core
autolab_core/image.py
Image._preprocess_data
python
def _preprocess_data(self, data): original_type = data.dtype if len(data.shape) == 1: data = data[:, np.newaxis, np.newaxis] elif len(data.shape) == 2: data = data[:, :, np.newaxis] elif len(data.shape) == 0 or len(data.shape) > 3: raise ValueError( ...
Converts a data array to the preferred 3D structure. Parameters ---------- data : :obj:`numpy.ndarray` The data to process. Returns ------- :obj:`numpy.ndarray` The data re-formatted (if needed) as a 3D matrix Raises ------ ...
https://github.com/berkeleyautomation/autolab_core/blob/cda081d2e07e3fe6cc9f3e8c86eea92330910d20/autolab_core/image.py#L137-L165
from abc import ABCMeta, abstractmethod import logging import os import cv2 import numpy as np import PIL.Image as PImage import matplotlib.pyplot as plt import scipy.signal as ssg import scipy.ndimage.filters as sf import scipy.ndimage.interpolation as sni import scipy.ndimage.morphology as snm import scipy.spatial.di...
Apache License 2.0
spyder-ide/spyder-unittest
spyder_unittest/widgets/configdialog.py
ConfigDialog.__init__
python
def __init__(self, frameworks, config, parent=None): super(ConfigDialog, self).__init__(parent) self.setWindowTitle(_('Configure tests')) layout = QVBoxLayout(self) framework_layout = QHBoxLayout() framework_label = QLabel(_('Test framework')) framework_layout.addWidget(f...
Construct a dialog window. Parameters ---------- frameworks : dict of (str, type) Names of all supported frameworks with their associated class (assumed to be a subclass of RunnerBase) config : Config Initial configuration parent : QWidget
https://github.com/spyder-ide/spyder-unittest/blob/fc29baa9edd8614a341bbcfde93aa6fea5c4afb5/spyder_unittest/widgets/configdialog.py#L47-L112
from collections import namedtuple import os.path as osp from qtpy.compat import getexistingdirectory from qtpy.QtCore import Slot from qtpy.QtWidgets import (QApplication, QComboBox, QDialog, QDialogButtonBox, QHBoxLayout, QLabel, QLineEdit, QPushButton, QVBoxLay...
MIT License
crespo-otero-group/fromage
fromage/utils/mol/_geom.py
coord_array
python
def coord_array(self): if self.geom.ignore_kinds: self.set_connectivity list_coord = [] for atom in self: add_atom = True if self.geom.ignore_hydrogens: if atom.elem == 'H': add_atom = False if self.geom.ignore_kinds: if atom.kind in se...
Return a numpy array of the coordinates Returns ------- coord_arr : Nat x 3 numpy array Array of the form [[x1,y1,z1],[x2,y2,z2],...]
https://github.com/crespo-otero-group/fromage/blob/9b4a80698ed1672268dde292d5512c72a23cb00a/fromage/utils/mol/_geom.py#L53-L81
import numpy as np import fromage.utils.array_operations as ao class GeomInfo(object): def __init__(self): self.coord_array = np.array([0]) self.plane_coeffs = np.array([0]) self.prin_ax = np.array([0]) self.sec_ax = np.array([0]) self.perp_ax = np.array([0]) self.ign...
MIT License
kriaga/health-checker
HealthChecker/venv/Lib/site-packages/nltk/classify/maxent.py
MaxentFeatureEncodingI.labels
python
def labels(self): raise NotImplementedError()
:return: A list of the \"known labels\" -- i.e., all labels ``l`` such that ``self.encode(fs,l)`` can be a nonzero joint-feature vector for some value of ``fs``. :rtype: list
https://github.com/kriaga/health-checker/blob/3d9ce933f131bcbb897103b0f509cc45393cae4a/HealthChecker/venv/Lib/site-packages/nltk/classify/maxent.py#L377-L384
from __future__ import print_function, unicode_literals try: import numpy except ImportError: pass import tempfile import os import re from collections import defaultdict from six import integer_types from nltk import compat from nltk.data import gzip_open_unicode from nltk.util import OrderedDict from nltk.pro...
MIT License
ryry013/rai
cogs/owner.py
Owner.database
python
async def database(self, ctx, depth, *, args): config = self.bot.db if '=' in args: args = f"{depth} {args}" depth = 1 split = args.split(' = ') + [''] path = split[0] set_to = split[1] def process_arg(arg): if arg.startswith('ctx'): ...
Shows or edits database
https://github.com/ryry013/rai/blob/8a8ce07c78a67967a8fc9cb5dabc68329bf85f9b/cogs/owner.py#L163-L255
from discord.ext import commands import asyncio import traceback import discord import textwrap from contextlib import redirect_stdout import io import sys import codecs import json from .utils import helper_functions as hf import re from ast import literal_eval import importlib import datetime from datetime import dat...
MIT License
uwdata/termite-visualizations
web2py/gluon/dal.py
ConnectionPool.after_connection_hook
python
def after_connection_hook(self): if callable(self._after_connection): self._after_connection(self) self.after_connection()
hook for the after_connection parameter
https://github.com/uwdata/termite-visualizations/blob/79da58bc607893bbd5db703f7d87a89b5e97c311/web2py/gluon/dal.py#L619-L623
__all__ = ['DAL', 'Field'] DEFAULTLENGTH = {'string':512, 'password':512, 'upload':512, 'text':2**15, 'blob':2**31} TIMINGSSIZE = 100 SPATIALLIBS = { 'Windows':'libspatialite', 'Linux':'libspatialite.so', 'Darwin':'libspatialite.dylib' ...
BSD 3-Clause New or Revised License
yeti-platform/yeti
core/web/api/file.py
File.get_id
python
def get_id(self, id): try: fileobj = self.objectmanager.objects.get(id=id) return Response(fileobj.body.stream_contents(), mimetype=fileobj.mime_type) except DoesNotExist: abort(404)
Retrieves a file's content. :<id ObjectId corresponding to the file ObjectId
https://github.com/yeti-platform/yeti/blob/fcd3ee3d3d064df772d0392c20c22aad2bc4c8e6/core/web/api/file.py#L57-L66
from __future__ import unicode_literals import zipfile import magic from flask import request, Response, abort from flask_classy import route from mongoengine import DoesNotExist from core import observables from core.database import AttachedFile from core.helpers import stream_sha256 from core.web.api.api import rende...
Apache License 2.0
thriftrw/thriftrw-python
thriftrw/compile/scope.py
Scope.resolve_service_spec
python
def resolve_service_spec(self, name, lineno): if name in self.service_specs: return self.service_specs[name].link(self) if '.' in name: include_name, component = name.split('.', 2) if include_name in self.included_scopes: return self.included_scopes[ ...
Finds and links the ServiceSpec with the given name.
https://github.com/thriftrw/thriftrw-python/blob/22f6ab645f5af48cae2fee0dc1431dfacb971348/thriftrw/compile/scope.py#L114-L131
from __future__ import absolute_import, unicode_literals, print_function import types from ..errors import ThriftCompilerError __all__ = ['Scope'] class Scope(object): __slots__ = ( 'const_specs', 'type_specs', 'module', 'service_specs', 'included_scopes', 'path' ) def __init__(self, name, p...
MIT License
nastools/homeassistant
homeassistant/components/light/isy994.py
ISYLightDevice.is_on
python
def is_on(self) -> bool: return self.state == STATE_ON
Get whether the ISY994 light is on.
https://github.com/nastools/homeassistant/blob/7ca1180bd42713f2d77bbc3f0b27b231ba8784aa/homeassistant/components/light/isy994.py#L53-L55
import logging from typing import Callable from homeassistant.components.light import ( Light, SUPPORT_BRIGHTNESS, ATTR_BRIGHTNESS) import homeassistant.components.isy994 as isy from homeassistant.const import STATE_ON, STATE_OFF, STATE_UNKNOWN from homeassistant.helpers.typing import ConfigType _LOGGER = logging.g...
MIT License
placeware/thisplace
thisplace.py
WordHasher.to_bytes
python
def to_bytes(self, integer): bytes = [integer & 0b11111111] for n in range(1,6): div = 2**(n*8) bytes.append((integer//div) & 0b11111111) bytes.reverse() return bytes
Convert a 48bit `integer` to a list of 6bytes
https://github.com/placeware/thisplace/blob/8c69fbc494a7fa4261398f0fdc0b3821a4e9f89a/thisplace.py#L168-L176
import random import geohash def get_words(fname): lines = open(fname) words = [] for word in lines: words.append(word.strip()) lines.close() random.seed(634634) random.shuffle(words) words = words[:2**15] assert len(words) == len(set(words)) return words GOOGLE_WORDLIST = ge...
MIT License
quantmind/lux
lux/utils/files.py
Filehandler.open
python
def open(self, name, mode='rb'): raise NotImplementedError()
Retrieves the specified file from storage, using the optional mixin class to customize what features are available on the File returned.
https://github.com/quantmind/lux/blob/7318fcd86c77616aada41d8182a04339680a554c/lux/utils/files.py#L54-L58
import os import re import itertools __all__ = ['Filehandler'] def skipfile(name): return name.startswith('.') or name.startswith('_') def directory(dir): bd, fname = os.path.split(dir) return dir if fname else bd def get_rel_dir(dir, base, res=''): dir = directory(dir) base = directory(base) if...
BSD 3-Clause New or Revised License
square/mimicandrephrase
src/utils/token_mapper.py
TokenMapper.map_token
python
def map_token(self, token: str) -> int: offset = sum([mapping.output_size() for mapping in self.unk_mappings]) for mapping in self.mappings: if mapping.match(token): return offset + mapping.map(token) offset += mapping.output_size() return -1
This attempts to map a token to one of the special mappings we have in this TokenMapper. The first mapping that triggers wins ties. If no mappings fire, this returns -1. :param token: the token to map :return: an offset into the output matrix, or -1 if no match
https://github.com/square/mimicandrephrase/blob/bd29a995b211cb4f7933fa990b0bba1564c22450/src/utils/token_mapper.py#L175-L188
from typing import List, Sequence, Dict from abc import ABC, abstractmethod import re import TensorflowModel_pb2 as proto def simple_hash(token: str, output_size: int) -> int: encoded = token.encode("utf-8") hash_sum = 0 for letter in encoded: hash_sum = ((31 * hash_sum) + letter) % output_size ...
MIT License
craylabs/smartsim
smartsim/launcher/local/local.py
LocalLauncher.run
python
def run(self, step): if not self.task_manager.actively_monitoring: self.task_manager.start() out, err = step.get_output_files() output = open(out, "w+") error = open(err, "w+") cmd = step.get_launch_cmd() task_id = self.task_manager.start_task( cmd...
Run a local step created by this launcher. Utilize the shell library to execute the command with a Popen. Output and error files will be written to the entity path. :param step: LocalStep instance to run :type step: LocalStep
https://github.com/craylabs/smartsim/blob/0c4b198650a026d7bd960f38b1866fb3b8c59a96/smartsim/launcher/local/local.py#L84-L103
from ...error import LauncherError from ...settings import RunSettings from ...utils import get_logger from ..step import LocalStep from ..stepInfo import UnmanagedStepInfo from ..stepMapping import StepMapping from ..taskManager import TaskManager logger = get_logger(__name__) class LocalLauncher: def __init__(sel...
BSD 2-Clause Simplified License
wolph/python-progressbar
progressbar/bar.py
ProgressBar.__init__
python
def __init__(self, min_value=0, max_value=None, widgets=None, left_justify=True, initial_value=0, poll_interval=None, widget_kwargs=None, custom_len=utils.len_color, max_error=True, prefix=None, suffix=None, variables=None, min_poll_interval=None, **kw...
Initializes a progress bar with sane defaults
https://github.com/wolph/python-progressbar/blob/8eb963c6cc97949bc7ac3fc57e645506a2c9ae0c/progressbar/bar.py#L283-L361
from __future__ import absolute_import from __future__ import division from __future__ import unicode_literals from __future__ import with_statement import sys import math import os import time import timeit import logging import warnings from datetime import datetime from copy import deepcopy try: from collectio...
BSD 3-Clause New or Revised License
tzhangwps/turbulence-and-systemic-risk
src/main.py
MainProcess.append_prices_and_returns
python
def append_prices_and_returns(self): print('\nRequesting data from Yahoo Finance...') self.prices = pd.read_pickle(path.prices_path_historical) self.prices = get.GetPrices().update_weekly_prices(self.prices) self.prices.to_pickle(path.prices_path_current) self.prices = get.Calcul...
Appends new data to the prices dataset and the returns dataset.
https://github.com/tzhangwps/turbulence-and-systemic-risk/blob/ceb7d1c6a1914da5a2316603f289238a4bb6a826/src/main.py#L26-L35
import pandas as pd import os import TurbulenceSuite_paths as path import src.get_data as get import src.calculate as calc class MainProcess: def __init__(self): self.prices = pd.DataFrame() self.returns = pd.DataFrame() self.turbulence = pd.DataFrame() self.systemic_risk = pd.DataFr...
MIT License
brython-dev/brython
www/speed/benchmarks/util.py
run_benchmark
python
def run_benchmark(options, num_runs, bench_func, *args): if options.profile: import cProfile prof = cProfile.Profile() prof.runcall(bench_func, num_runs, *args) prof.print_stats(sort=options.profile_sort) else: data = bench_func(num_runs, *args) if options.take_ge...
Run the given benchmark, print results to stdout. Args: options: optparse.Values instance. num_runs: number of times to run the benchmark bench_func: benchmark function. `num_runs, *args` will be passed to this function. This should return a list of floats (benchmark execution ...
https://github.com/brython-dev/brython/blob/33aeaab551f1b73209326c5a0aecf98642d4c126/www/speed/benchmarks/util.py#L10-L32
__author__ = "collinwinter@google.com (Collin Winter)" import math import operator from functools import reduce
BSD 3-Clause New or Revised License
openmined/pyariesfl
aries_cloudagent/admin/server.py
WebhookTarget.__init__
python
def __init__( self, endpoint: str, topic_filter: Sequence[str] = None, retries: int = None ): self.endpoint = endpoint self._topic_filter = None self.retries = retries self.topic_filter = topic_filter
Initialize the webhook target.
https://github.com/openmined/pyariesfl/blob/dd78dcebc771971abfee301b80cdd5d246c14840/aries_cloudagent/admin/server.py#L81-L89
import asyncio import logging from typing import Coroutine, Sequence, Set import uuid from aiohttp import web, ClientSession from aiohttp_apispec import docs, response_schema, setup_aiohttp_apispec import aiohttp_cors from marshmallow import fields, Schema from ..classloader import ClassLoader from ..config.base import...
Apache License 2.0
ifding/wavenet-speech-to-text
model/networks.py
ResidualBlock.__init__
python
def __init__(self, res_channels, skip_channels, dilation): super(ResidualBlock, self).__init__() self.dilated = DilatedCausalConv1d(res_channels, dilation=dilation) self.conv_res = torch.nn.Conv1d(res_channels, res_channels, 1) self.conv_skip = torch.nn.Conv1d(res_channels, skip_channels...
Residual block :param res_channels: number of residual channel for input, output :param skip_channels: number of skip channel for output :param dilation:
https://github.com/ifding/wavenet-speech-to-text/blob/4d786c2280527ff38ba615974dd227c4f44c93b2/model/networks.py#L61-L75
import torch import numpy as np from utils.exceptions import InputSizeError class DilatedCausalConv1d(torch.nn.Module): def __init__(self, channels, dilation=1): super(DilatedCausalConv1d, self).__init__() self.conv = torch.nn.Conv1d(channels, channels, kernel_siz...
MIT License
adafruit/adafruit_python_gpio
Adafruit_GPIO/SPI.py
BitBang.set_clock_hz
python
def set_clock_hz(self, hz): pass
Set the speed of the SPI clock. This is unsupported with the bit bang SPI class and will be ignored.
https://github.com/adafruit/adafruit_python_gpio/blob/a12fee39839665966bd124fd22588b2c87ced9d2/Adafruit_GPIO/SPI.py#L173-L177
import operator import time import Adafruit_GPIO as GPIO MSBFIRST = 0 LSBFIRST = 1 class SpiDev(object): def __init__(self, port, device, max_speed_hz=500000): import spidev self._device = spidev.SpiDev() self._device.open(port, device) self._device.max_speed_hz=max_speed_hz ...
MIT License
datadotworld/data.world-py
datadotworld/client/_swagger/models/file_summary_response.py
FileSummaryResponse.created
python
def created(self, created): if created is None: raise ValueError("Invalid value for `created`, must not be `None`") self._created = created
Sets the created of this FileSummaryResponse. Date and time when file was created. :param created: The created of this FileSummaryResponse. :type: str
https://github.com/datadotworld/data.world-py/blob/7e5f474b655f4f0c88cc6862353e4d52c0e0bb31/datadotworld/client/_swagger/models/file_summary_response.py#L90-L101
from pprint import pformat from six import iteritems import re class FileSummaryResponse(object): """ Attributes: swagger_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The key is attribute name a...
Apache License 2.0
twisted/axiom
axiom/item.py
Empowered._getPowerupInterfaces
python
def _getPowerupInterfaces(self): powerupInterfaces = getattr(self.__class__, "powerupInterfaces", ()) pifs = [] for x in powerupInterfaces: if isinstance(x, type(Interface)): pifs.append((x, 0)) else: pifs.append(x) m = getattr(self...
Collect powerup interfaces this object declares that it can be installed on.
https://github.com/twisted/axiom/blob/28191ede99287e9a87c1ff561b831f7d80aaa2fe/axiom/item.py#L379-L402
__metaclass__ = type import gc from zope.interface import implementer, Interface from inspect import getabsfile from weakref import WeakValueDictionary from twisted.python import log from twisted.python.reflect import qual, namedAny from twisted.python.util import mergeFunctionMetadata from twisted.application.service ...
MIT License
user-cont/conu
conu/backend/nspawn/container.py
NspawnContainer.inspect
python
def inspect(self, refresh=True): return self.get_metadata(refresh=refresh)
return cached metadata by default (a convenience method) :param refresh: bool, returns up to date metadata if set to True :return: dict
https://github.com/user-cont/conu/blob/0d8962560f6f7f17fe1be0d434a4809e2a0ea51d/conu/backend/nspawn/container.py#L108-L116
import logging import subprocess import time from copy import deepcopy from conu.apidefs.container import Container from conu.exceptions import ConuException from conu.utils import run_cmd, random_str, convert_kv_to_dict, command_exists from conu.backend.nspawn import constants logger = logging.getLogger(__name__) clas...
MIT License
facebookresearch/mephisto
mephisto/operations/utils.py
get_extra_argument_dicts
python
def get_extra_argument_dicts(customizable_class: Any) -> List[Dict[str, Any]]: dict_fields = fields(customizable_class.ArgsClass) usable_fields = [] group_field = None for f in dict_fields: if not f.name.startswith("_"): usable_fields.append(f) elif f.name == "_group": ...
Produce the argument dicts for the given customizable class (Blueprint, Architect, etc)
https://github.com/facebookresearch/mephisto/blob/ff81d7c8ef1f90ef400fc102cc0312a83d848764/mephisto/operations/utils.py#L218-L235
import os import sys, glob, importlib import shlex from distutils.dir_util import copy_tree import functools from mephisto.data_model.constants import NO_PROJECT_NAME from mephisto.operations.config_handler import ( add_config_arg, get_config_arg, CORE_SECTION, DATA_STORAGE_KEY, DEFAULT_CONFIG_FILE,...
MIT License
danielnyga/pracmln
python2/pracmln/logic/common.py
Logic.templ_atoms
python
def templ_atoms(self): templ_atoms = [] for literal in self.literals(): for templ in literal.template_variants(): templ_atoms.append(templ) return templ_atoms
Returns a list of template variants of all atoms that can be generated from this formula and the given mln. :Example: foo(?x, +?y) ^ bar(?x, +?z) --> [foo(?x, X1), foo(?x, X2), ..., bar(?x, Z1), bar(?x...
https://github.com/danielnyga/pracmln/blob/bbda65696fb8753b11ff007e991280ebe42d78f9/python2/pracmln/logic/common.py#L234-L248
import sys from dnutils import logs, ifnone from pracmln.mln.util import fstr, dict_union, colorize from pracmln.mln.errors import NoSuchDomainError, NoSuchPredicateError from collections import defaultdict import itertools from pracmln.mln.constants import HARD, auto, predicate_color, inherit from grammar import Stand...
BSD 2-Clause Simplified License
netzkolchose/django-computedfields
computedfields/graph.py
Graph.get_cycles
python
def get_cycles(self): left_edges = OrderedDict() cycles = {} for edge in self.edges: left_edges.setdefault(edge.left, []).append(edge) for edge in self.edges: self._get_cycles(edge, left_edges, cycles) return cycles
Gets all cycles in graph. This is not optimised by any means, it simply walks the whole graph recursively and aborts as soon a seen edge gets entered again. Therefore use this and all dependent properties (``edge_cycles`` and ``node_cycles``) for in-depth cycle inspection only. ...
https://github.com/netzkolchose/django-computedfields/blob/ffa7c963cb0e70d2afe5954f2fdca241c0407b3f/computedfields/graph.py#L268-L298
from collections import OrderedDict from django.core.exceptions import FieldDoesNotExist from django.db.models import ForeignKey from computedfields.helper import pairwise, is_sublist, modelname, parent_to_inherited_path, skip_equal_segments class ComputedFieldsException(Exception): class CycleException(ComputedFieldsE...
MIT License
wayneweiqiang/gmma
gmma/utils/validation.py
check_memory
python
def check_memory(memory): if memory is None or isinstance(memory, str): if parse_version(joblib.__version__) < parse_version('0.12'): memory = joblib.Memory(cachedir=memory, verbose=0) else: memory = joblib.Memory(location=memory, verbose=0) elif not hasattr(memory, 'cach...
Check that ``memory`` is joblib.Memory-like. joblib.Memory-like means that ``memory`` can be converted into a joblib.Memory instance (typically a str denoting the ``location``) or has the same interface (has a ``cache`` method). Parameters ---------- memory : None, str or object with the jobli...
https://github.com/wayneweiqiang/gmma/blob/30b116edb83f495341fef8e9ad4baa50e4e1f76a/gmma/utils/validation.py#L208-L238
from functools import wraps import warnings import numbers import numpy as np import scipy.sparse as sp from inspect import signature, isclass, Parameter from numpy.core.numeric import ComplexWarning import joblib from contextlib import suppress from .fixes import _object_dtype_isnan, parse_version from .. import get_c...
MIT License
ethereum/trinity
p2p/kademlia.py
KademliaRoutingTable.get_least_recently_updated_log_distance
python
def get_least_recently_updated_log_distance(self) -> int: try: bucket_index = self.bucket_update_order[-1] except IndexError: raise ValueError("Routing table is empty") else: return bucket_index + 1
Get the log distance whose corresponding bucket was updated least recently. Only non-empty buckets are considered. If all buckets are empty, a `ValueError` is raised.
https://github.com/ethereum/trinity/blob/6383280c5044feb06695ac2f7bc1100b7bcf4fe0/p2p/kademlia.py#L443-L453
import collections import functools import ipaddress import itertools import operator import random import struct from typing import ( Any, Dict, Iterable, List, Type, TypeVar, Tuple, Deque, Iterator) from urllib import parse as urlparse from cached_property import cached_property from eth_u...
MIT License
slicermorph/slicermorph
IDAVLMConverter/IDAVLMConverter.py
IDAVLMConverterLogic.isValidInputOutputData
python
def isValidInputOutputData(self, inputVolumeNode, outputVolumeNode): if not inputVolumeNode: logging.debug('isValidInputOutputData failed: no input volume node defined') return False if not outputVolumeNode: logging.debug('isValidInputOutputData failed: no output volume node defined') re...
Validates if the output is not the same as input
https://github.com/slicermorph/slicermorph/blob/67c622c4ab15f0a1dee2bb00dffde8dbcd5a91be/IDAVLMConverter/IDAVLMConverter.py#L148-L160
import os import unittest import vtk, qt, ctk, slicer from slicer.ScriptedLoadableModule import * import logging class IDAVLMConverter(ScriptedLoadableModule): def __init__(self, parent): ScriptedLoadableModule.__init__(self, parent) self.parent.title = "IDAVLMConverter" self.parent.categories = ["Slicer...
BSD 2-Clause Simplified License
geertj/python-ad
lib/ad/protocol/asn1.py
Decoder.leave
python
def leave(self): if self.m_stack is None: raise Error, 'No input selected. Call start() first.' if len(self.m_stack) == 1: raise Error, 'Tag stack is empty.' del self.m_stack[-1] self.m_tag = None
Leave the last entered constructed tag.
https://github.com/geertj/python-ad/blob/3089eae072bd2e871c11251961ec35a09b83dd38/lib/ad/protocol/asn1.py#L283-L290
Boolean = 0x01 Integer = 0x02 OctetString = 0x04 Null = 0x05 ObjectIdentifier = 0x06 Enumerated = 0x0a Sequence = 0x10 Set = 0x11 TypeConstructed = 0x20 TypePrimitive = 0x00 ClassUniversal = 0x00 ClassApplication = 0x40 ClassContext = 0x80 ClassPrivate = 0xc0 import re class Error(Exception): class Encoder(object): ...
MIT License
ucam-smt/sgnmt
cam/sgnmt/predictors/tf_t2t.py
T2TPredictor.predict_next
python
def predict_next(self): log_probs = self.mon_sess.run(self._log_probs, {self._inputs_var: self.src_sentence, self._targets_var: utils.oov_to_unk( self.consumed + [text_encoder.PAD_ID], self.trg_vocab_size, self._t2t_unk_id)}) lo...
Call the T2T model in self.mon_sess.
https://github.com/ucam-smt/sgnmt/blob/c663ec7b251552e36b6b4f992f0ac21aad87cb7b/cam/sgnmt/predictors/tf_t2t.py#L332-L341
import logging import os from cam.sgnmt import utils, tf_utils from cam.sgnmt.predictors.core import Predictor from cam.sgnmt.misc.trie import SimpleTrie POP = "##POP##" try: from tensor2tensor import models from tensor2tensor import problems as problems_lib from tensor2tensor.utils import usr_dir f...
Apache License 2.0
sphinx-toolbox/sphinx-toolbox
sphinx_toolbox/testing.py
Sphinx.add_enumerable_node
python
def add_enumerable_node( self, node: Type[nodes.Element], figtype: str, title_getter: Optional[TitleGetter] = None, override: bool = False, **kwargs: Tuple[Callable, Callable], ) -> None: self.registry.add_enumerable_node( node, figtype, title_getter, override=override, ) ...
Register a Docutils node class as a numfig target.
https://github.com/sphinx-toolbox/sphinx-toolbox/blob/cee88c6bceac20a9ae0e381ada2fb2453ca3fc0b/sphinx_toolbox/testing.py#L236-L255
import copy import sys import tempfile from functools import partial from types import SimpleNamespace from typing import Any, Callable, Dict, List, NamedTuple, Optional, Set, Tuple, Type, Union, cast import pytest import sphinx.application from bs4 import BeautifulSoup from coincidence.regressions import check_fil...
MIT License
thingsboard/python_tb_rest_client
tb_rest_client/models/models_pe/dashboard.py
Dashboard.owner_id
python
def owner_id(self, owner_id): self._owner_id = owner_id
Sets the owner_id of this Dashboard. :param owner_id: The owner_id of this Dashboard. # noqa: E501 :type: EntityId
https://github.com/thingsboard/python_tb_rest_client/blob/87c6a3703974fc8a86e4c72c444168ee2b758ecb/tb_rest_client/models/models_pe/dashboard.py#L300-L308
import pprint import re import six class Dashboard(object): swagger_types = { 'assigned_customers': 'list[ShortCustomerInfo]', 'configuration': 'str', 'created_time': 'int', 'customer_id': 'CustomerId', 'id': 'DashboardId', 'image': 'str', 'mobile_hide': 'bo...
Apache License 2.0
nrel/floris
floris/tools/power_rose.py
PowerRose.__init__
python
def __init__(self,):
Instantiate a PowerRose object. No explicit arguments required, and an additional method will need to be called to populate the PowerRose object with data.
https://github.com/nrel/floris/blob/ef4934ec7feb7afd2615772d364a1eaa28db93e9/floris/tools/power_rose.py#L43-L48
import os import pickle import numpy as np import pandas as pd import matplotlib.pyplot as plt from floris.utilities import wrap_180 class PowerRose:
Apache License 2.0
georgebrock/git-browse
gitbrowse/git.py
GitFileHistory.line_mapping
python
def line_mapping(self, start, finish): key = start + '/' + finish if key in self._line_mappings: return self._line_mappings[key] forward, backward = self._build_line_mappings(start, finish) self._line_mappings[start + '/' + finish] = forward self._line_mappings[finish...
Returns a dict that represents how lines have moved between versions of a file. The keys are the line numbers in the version of the file at start, the values are where those lines have ended up in the version at finish. For example if at start the file is two lines, and at finis...
https://github.com/georgebrock/git-browse/blob/a77031683f08bfded5959bed9f836503b3a1219a/gitbrowse/git.py#L130-L155
import os class GitCommit(object): def __init__(self, sha, author, message): self.sha = sha self.author = author self.message = message class GitBlameLine(object): def __init__(self, sha, line, current, original_line, final_line): self.sha = sha self.line = line s...
MIT License
pyansys/pymapdl
ansys/mapdl/core/_commands/solution/nonlinear_options.py
NonLinearOptions.arclen
python
def arclen(self, key="", maxarc="", minarc="", **kwargs): command = f"ARCLEN,{key},{maxarc},{minarc}" return self.run(command, **kwargs)
Activates the arc-length method. APDL Command: ARCLEN Parameters ---------- key Arc-length key: OFF - Do not use the arc-length method (default). ON - Use the arc-length method. maxarc Maximum multiplier of the reference arc-le...
https://github.com/pyansys/pymapdl/blob/e5cc21471c3a8fcef1f7b88359e38aa89cd63f73/ansys/mapdl/core/_commands/solution/nonlinear_options.py#L2-L72
class NonLinearOptions:
MIT License
komuw/sewer
sewer/dns_providers/aliyundns.py
AliyunDns.delete_dns_record
python
def delete_dns_record(self, domain_name, domain_dns_value): self.logger.info("delete_dns_record start: %s", (domain_name, domain_dns_value)) root, _, acme_txt = self.extract_zone(domain_name) record_id = self.query_recored_id(root, acme_txt) if not record_id: msg = "failed to...
delete a txt record we created just now. :param str domain_name: the value sewer client passed in, like *.menduo.example.com :param str domain_dns_value: the value sewer client passed in. we do not use this. :return _ResponseForAliyun: :return:
https://github.com/komuw/sewer/blob/056ac64fe294fb284ec5b920ec1a9425dd254e92/sewer/dns_providers/aliyundns.py#L180-L205
import json from aliyunsdkcore import client import aliyunsdkalidns.request.v20150109 from aliyunsdkalidns.request.v20150109 import ( DescribeDomainRecordsRequest, AddDomainRecordRequest, DeleteDomainRecordRequest, ) from . import common class _ResponseForAliyun(object): def __init__(self, status_co...
MIT License
kuri65536/python-for-android
python-build/python-libs/gdata/build/lib/gdata/Crypto/Util/RFC1751.py
_key2bin
python
def _key2bin(s): kl=map(lambda x: ord(x), s) kl=map(lambda x: binary[x/16]+binary[x&15], kl) return ''.join(kl)
Convert a key into a string of binary digits
https://github.com/kuri65536/python-for-android/blob/26402a08fc46b09ef94e8d7a6bbc3a54ff9d0891/python-build/python-libs/gdata/build/lib/gdata/Crypto/Util/RFC1751.py#L15-L19
__revision__ = "$Id: RFC1751.py,v 1.6 2003/04/04 15:15:10 akuchling Exp $" import string, binascii binary={0:'0000', 1:'0001', 2:'0010', 3:'0011', 4:'0100', 5:'0101', 6:'0110', 7:'0111', 8:'1000', 9:'1001', 10:'1010', 11:'1011', 12:'1100', 13:'1101', 14:'1110', 15:'1111'}
Apache License 2.0
jhuapl-boss/boss
django/bosscore/test/setup_db.py
SetupTestDB.insert_downsample_data
python
def insert_downsample_data(self): self.add_coordinate_frame('cf_ds_aniso', 'Description for cf2', 0, 4096, 0, 4096, 0, 128, 4, 4, 35) self.add_experiment('col1', 'exp_ds_aniso', 'cf_ds_aniso', 5, 500, 1) aniso_chan = self.add_channel('col1', 'exp_ds_aniso', 'channel1', 0, 0, 'uint8', 'image') ...
Some resources for small downsample tests Returns: (Tuple[Channel, Channel]): The channels created for the downsample test.
https://github.com/jhuapl-boss/boss/blob/c2e26d272bd7b8d54abdc2948193163537e31291/django/bosscore/test/setup_db.py#L219-L232
from django.contrib.auth.models import User from django.contrib.auth.models import Group from django.contrib.contenttypes.models import ContentType from guardian.shortcuts import assign_perm from ..models import Collection, Experiment, CoordinateFrame, Channel, BossLookup, BossRole, BossGroup from ..views.views_resourc...
Apache License 2.0
purestorage-openconnect/py-pure-client
pypureclient/pure1/Pure1_1_0/models/drive_get_response.py
DriveGetResponse.to_dict
python
def to_dict(self): result = {} for attr, _ in six.iteritems(self.swagger_types): if hasattr(self, attr): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( lambda x: x.to_dict() if hasat...
Returns the model properties as a dict
https://github.com/purestorage-openconnect/py-pure-client/blob/2d9fdef0b73321cea9613e7d1eb881b42845099b/pypureclient/pure1/Pure1_1_0/models/drive_get_response.py#L78-L104
import pprint import re import six import typing from ....properties import Property if typing.TYPE_CHECKING: from pypureclient.pure1.Pure1_1_0 import models class DriveGetResponse(object): swagger_types = { 'continuation_token': 'str', 'total_item_count': 'int', 'items': 'list[Drive]' ...
BSD 2-Clause Simplified License
superkogito/pydiogment
pydiogment/utils/filters.py
butter_bandpass
python
def butter_bandpass(low_cut, high_cut, fs, order=5): nyq = 0.5 * fs low = low_cut / nyq high = high_cut / nyq b, a = butter(order, [low, high], btype='band') return b, a
Design band pass filter. Args: - low_cut (float) : the low cutoff frequency of the filter. - high_cut (float) : the high cutoff frequency of the filter. - fs (float) : the sampling rate. - order (int) : order of the filter, by default defined to 5.
https://github.com/superkogito/pydiogment/blob/000a07b2ad8d3480535e7d900aed1ed3358a5d4a/pydiogment/utils/filters.py#L49-L68
from scipy.signal import butter, lfilter def butter_lowpass(cutoff, fs, order=5): nyq = 0.5 * fs low = cutoff / nyq b, a = butter(order, low, btype='low', analog=False) return b, a def butter_highpass(cutoff, fs, order=5): nyq = 0.5 * fs high = cutoff / nyq b, a = butter(order, high, btype='...
BSD 3-Clause New or Revised License
voxel51/eta
eta/core/module.py
ModuleMetadata.get_input
python
def get_input(self, name): return self.inputs[name]
Returns the ModuleInput instance for input `name`.
https://github.com/voxel51/eta/blob/e51510fda0722ac7cadb17b109bad413a6602ed3/eta/core/module.py#L629-L631
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from builtins import * from future.utils import iteritems from collections import OrderedDict from glob import glob import logging import os import eta from eta.core.confi...
Apache License 2.0
nikcub/cexbot
cexbot/appdirs.py
site_config_dir
python
def site_config_dir(appname=None, appauthor=None, version=None, multipath=False): if sys.platform in [ "win32", "darwin" ]: path = site_data_dir(appname, appauthor) if appname and version: path = os.path.join(path, version) else: path = os.getenv('XDG_CONFIG_DIRS', '/etc/xdg') pathlist = [ os....
Return full path to the user-shared data dir for this application. "appname" is the name of application. If None, just the system directory is returned. "appauthor" (only required and used on Windows) is the name of the appauthor or distributing body for this application. Typically it is the ...
https://github.com/nikcub/cexbot/blob/0dd0b60415afd9c1feb959186d32b1a683887975/cexbot/appdirs.py#L182-L229
__version_info__ = (1, 3, 0) __version__ = '.'.join(map(str, __version_info__)) import sys import os PY3 = sys.version_info[0] == 3 if PY3: unicode = str def user_data_dir(appname=None, appauthor=None, version=None, roaming=False): if sys.platform == "win32": if appauthor is None: appauthor = appname ...
MIT License