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
lostindarkmath/pedantic-python-decorators
pedantic/type_checking_logic/check_types.py
_get_base_generic
python
def _get_base_generic(cls: Any) -> Any: origin = cls.__origin__ if hasattr(cls, '__origin__') else None name = cls._name if hasattr(cls, '_name') else None if name is not None: return getattr(typing, name) elif origin is not None: return origin return cls
>>> from typing import List, Union, Tuple, Callable, Dict, Set >>> _get_base_generic(List) typing.List >>> _get_base_generic(List[float]) typing.List >>> _get_base_generic(List[List[float]]) typing.List >>> _get_base_generic(List[Union[int, float]]) typing...
https://github.com/lostindarkmath/pedantic-python-decorators/blob/66865a958a36440b48e790f22ea42d2beb725b16/pedantic/type_checking_logic/check_types.py#L413-L455
import inspect import typing from io import BytesIO, StringIO, BufferedWriter, TextIOWrapper from typing import Any, Dict, Iterable, ItemsView, Callable, Union, Optional, Tuple, Mapping, TypeVar, NewType import collections import sys from pedantic.constants import TypeVar as TypeVar_ from pedantic.exceptions import Ped...
Apache License 2.0
seung-lab/chunkflow
chunkflow/chunk/base.py
Chunk.ndoffset
python
def ndoffset(self) -> tuple: if self.ndim == 4: return (0, *self.voxel_offset) else: return self.voxel_offset
make the voxel offset have the same dimension with array
https://github.com/seung-lab/chunkflow/blob/0e032cdf4f2ba104af4f7809ac11df17352384ed/chunkflow/chunk/base.py#L395-L402
from typing import Union import os from numbers import Number import h5py import numpy as np import nrrd from numpy.core.numerictypes import issubdtype from numpy.lib.mixins import NDArrayOperatorsMixin from scipy.ndimage import gaussian_filter import tifffile import cc3d from cloudvolume.lib import yellow, Bbox from c...
Apache License 2.0
twisted/axiom
axiom/tags.py
Catalog.tagNames
python
def tagNames(self): return self.store.query(_TagName, _TagName.catalog == self).getColumn("name")
Return an iterator of unicode strings - the unique tag names which have been applied objects in this catalog.
https://github.com/twisted/axiom/blob/28191ede99287e9a87c1ff561b831f7d80aaa2fe/axiom/tags.py#L83-L88
from epsilon.extime import Time from axiom.item import Item from axiom.attributes import text, reference, integer, AND, timestamp class Tag(Item): typeName = 'tag' schemaVersion = 1 name = text(doc=""" The short string which is being applied as a tag to an Item. """) created = timestamp(doc=""" ...
MIT License
fredhutch/proxmox-tools
prox/cmdprox.py
ssh_exec
python
def ssh_exec(user, pwd, commands, host): if not isinstance(commands, list): print('commands parameter in ssh_exec needs to be a list') return False ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy( paramiko.AutoAddPolicy()) ssh.connect(host, username=user, password=pwd)...
execute list of commands via ssh
https://github.com/fredhutch/proxmox-tools/blob/cfd4d7333969d3ad8af80f15be56d0d5052fee4e/prox/cmdprox.py#L949-L961
import sys, os, subprocess, re, platform, getpass, argparse, logging, hostlist import time, warnings, functools, random, json, requests, paramiko, socket try: import easygui except: pass with warnings.catch_warnings(): warnings.filterwarnings("ignore", category=DeprecationWarning) try: from .pyp...
Apache License 2.0
derfies/panda3d-editor
src/pandaEditor/ui/mainFrame.py
MainFrame.OnFileSave
python
def OnFileSave(self, evt, saveAs=False): if self.base.doc.file_path is None or saveAs: filePath = self._GetSavePath() if filePath: self.base.doc.file_path = filePath else: return self.base.doc.save()
Save the document.
https://github.com/derfies/panda3d-editor/blob/a50939bd4bfa5c22d27a9ddee090717e8d95f404/src/pandaEditor/ui/mainFrame.py#L248-L262
import os import sys import wx import wx.aui import wx.propgrid as wxpg from pubsub import pub import panda3d.core as pm import p3d from direct.showbase.PythonUtil import getBase as get_base from wxExtra import utils as wxUtils, ActionItem from wxExtra.logpanel import LogPanel from wxExtra import AuiManagerConfig, Cust...
MIT License
obi-wan3/ob13-cogs
mentionhelp/mentionhelp.py
MentionHelp._mention_help
python
async def _mention_help(self, ctx: commands.Context):
Send a message when a user mentions the bot (with no other text).
https://github.com/obi-wan3/ob13-cogs/blob/716527f8581e0345802ea2626d43324f87edf941/mentionhelp/mentionhelp.py#L79-L80
import re import discord from redbot.core import commands, Config class MentionHelp(commands.Cog): def __init__(self, bot): self.bot = bot self.config = Config.get_conf(self, 14000605, force_registration=True) default_guild = { "toggle": True } default_global = { ...
MIT License
medtagger/medtagger
backend/medtagger/repositories/label_tags.py
enable
python
def enable(label_tag_key: str) -> None: enabling_query = LabelTag.query.filter(LabelTag.key == label_tag_key) updated = enabling_query.update({'disabled': False}, synchronize_session='fetch') if not updated: raise InternalErrorException(f'Label Tag "{label_tag_key}" was not enabled due to unknown da...
Enable existing Label Tag.
https://github.com/medtagger/medtagger/blob/8b7575e55764a95d2040f3b9bcd23b6ff846ecaa/backend/medtagger/repositories/label_tags.py#L75-L80
from typing import List from medtagger.database import db_transaction_session from medtagger.database.models import LabelTag from medtagger.definitions import LabelTool from medtagger.exceptions import InternalErrorException from medtagger.types import TaskID def get_all_tags(include_disabled: bool = False) -> List[Lab...
Apache License 2.0
linmx0130/ya_mxdet
train_faster_rcnn.py
train_dataset
python
def train_dataset(): train_dataset = VOCDataset(annotation_dir=cfg.annotation_dir, img_dir=cfg.img_dir, dataset_index=cfg.dataset_index, transform=train_transformation, resize_func=img_resize) ...
prepare a custom dataset return: train_dataset
https://github.com/linmx0130/ya_mxdet/blob/eaa6de7faf819f3720d8dac64c57a42dec38eed7/train_faster_rcnn.py#L37-L47
from faster_rcnn.config import cfg from VOCDataset import VOCDataset from faster_rcnn.faster_rcnn import FasterRCNN import mxnet as mx from faster_rcnn.utils import random_flip, imagenetNormalize, img_resize, random_square_crop, select_class_generator, bbox_inverse_transform, softmax_celoss_with_ignore from faster_rcnn...
MIT License
usc-isi-i2/rltk
rltk/record.py
remove_raw_object
python
def remove_raw_object(cls): cls._remove_raw_object = True return cls
Decorator for Record class. If a Record class is decorated, raw_object will be removed once all mark properties are cached.
https://github.com/usc-isi-i2/rltk/blob/aee10ed5dd561583e60db3373ed82fe1208da1e9/rltk/record.py#L75-L81
import re from typing import Callable re_record_id = re.compile(r'^[^*]{1,255}$') re_valid_property_name = re.compile(r'^[A-Za-z_]{1}[\w]*$') class Record(object): _remove_raw_object = False def __init__(self, raw_object): self.raw_object = raw_object @property def id(self): raise NotImp...
MIT License
google-research/long-range-arena
lra_benchmarks/models/reformer/reformer.py
ReformerDualEncoder.apply
python
def apply(self, inputs1, inputs2, vocab_size=None, inputs1_positions=None, inputs2_positions=None, inputs1_segmentation=None, inputs2_segmentation=None, use_bfloat16=False, emb_dim=512, num_heads=8, ...
Applies Transformer model on text similarity. A deliberate choice to distinguish this from NLI because we may want to do different things to the model later. Dual Encoding mode enforces that we do not do cross attention between pairs. Args: inputs1: input data. inputs2: target data. ...
https://github.com/google-research/long-range-arena/blob/09c2916c3f33a07347dcc70c8839957d3c9d4062/lra_benchmarks/models/reformer/reformer.py#L204-L284
from flax import nn import jax.numpy as jnp from lra_benchmarks.models.layers import common_layers from lra_benchmarks.models.reformer import reformer_attention class ReformerBlock(nn.Module): def apply(self, inputs, qkv_dim, mlp_dim, num_heads, dtype=jnp.fl...
Apache License 2.0
beartype/beartype
beartype/_decor/_code/_pep/pepcode.py
_unmemoize_pep_code
python
def _unmemoize_pep_code( data: BeartypeData, func_wrapper_code: str, pith_repr: str, hint_forwardrefs_class_basename: tuple, ) -> str: assert data.__class__ is BeartypeData, f'{repr(data)} not @beartype data.' assert isinstance(func_wrapper_code, str), ( f'{repr(func_wrapper_code)} not s...
Convert the passed memoized code snippet type-checking any parameter or return of the decorated callable into a memoized code snippet type-checking a specific parameter or return of that callable. Specifically, this function (in order): #. Globally replaces all references to the :data:`PEP_CODE...
https://github.com/beartype/beartype/blob/9da0bbebe408d281d5bfb6cc203dc6969e241aa4/beartype/_decor/_code/_pep/pepcode.py#L237-L331
from beartype.roar import BeartypeDecorHintPepException from beartype._decor._cache.cachetype import ( bear_typistry, register_typistry_forwardref, ) from beartype._decor._code.codesnip import ARG_NAME_TYPISTRY from beartype._decor._code._pep._pephint import pep_code_check_hint from beartype._decor._code._pep._...
MIT License
visualcomputinginstitute/3d-semantic-segmentation
tools/lazy_decorator.py
lazy_property
python
def lazy_property(function): attribute = '_cache_' + function.__name__ @property @functools.wraps(function) def decorator(self): if not hasattr(self, attribute): setattr(self, attribute, function(self)) return getattr(self, attribute) return decorator
caches the output of the property and just returns the value for next calls :param function: property to be cached :return: cached output of property
https://github.com/visualcomputinginstitute/3d-semantic-segmentation/blob/1dfc010b370a346902ad29460c9ad969c1892a97/tools/lazy_decorator.py#L10-L25
import functools
MIT License
nuagenetworks/vspk-python
vspk/v5_0/nuvirtualip.py
NUVirtualIP.associated_floating_ip_id
python
def associated_floating_ip_id(self): return self._associated_floating_ip_id
Get associated_floating_ip_id value. Notes: Id of Floating IP address associated to this virtual ip This attribute is named `associatedFloatingIPID` in VSD API.
https://github.com/nuagenetworks/vspk-python/blob/375cce10ae144ad6017104e57fcd3630898cc2a6/vspk/v5_0/nuvirtualip.py#L253-L263
from .fetchers import NUMetadatasFetcher from .fetchers import NUGlobalMetadatasFetcher from .fetchers import NUEventLogsFetcher from bambou import NURESTObject class NUVirtualIP(NURESTObject): __rest_name__ = "virtualip" __resource_name__ = "virtualips" CONST_IP_TYPE_IPV6 = "IPV6" CONST_IP_TYPE_IPV4 = ...
BSD 3-Clause New or Revised License
v7labs/darwin-py
darwin/dataset/remote_dataset.py
RemoteDataset.push
python
def push( self, files_to_upload: Optional[List[Union[PathLike, LocalFile]]], *, blocking: bool = True, multi_threaded: bool = True, fps: int = 0, as_frames: bool = False, files_to_exclude: Optional[List[PathLike]] = None, path: Optional[str] = None...
Uploads a local dataset (images ONLY) in the datasets directory. Parameters ---------- files_to_upload : Optional[List[Union[PathLike, LocalFile]]] List of files to upload. Those can be folders. blocking : bool If False, the dataset is not uploaded and a generato...
https://github.com/v7labs/darwin-py/blob/694253ec520ec32d791eb4a2d0b8acc9ad686b33/darwin/dataset/remote_dataset.py#L88-L168
import json import shutil import tempfile import zipfile from datetime import datetime from pathlib import Path from typing import TYPE_CHECKING, Any, Callable, Dict, Iterator, List, Optional, Union from urllib import parse from darwin.dataset.download_manager import download_all_images_from_annotations from darwin.dat...
MIT License
prajdabre/yanmtt
transformers/src/transformers/models/t5/modeling_tf_t5.py
TFT5Attention.compute_bias
python
def compute_bias(self, query_length, key_length): context_position = tf.range(query_length)[:, None] memory_position = tf.range(key_length)[None, :] relative_position = memory_position - context_position relative_position_bucket = self._relative_position_bucket( relative_po...
Compute binned relative position bias
https://github.com/prajdabre/yanmtt/blob/4d329c3bcb81ca432d5947bb4673897086ee7f32/transformers/src/transformers/models/t5/modeling_tf_t5.py#L226-L240
import copy import itertools import math import warnings from typing import Tuple import tensorflow as tf from ...activations_tf import get_tf_activation from ...file_utils import ( DUMMY_INPUTS, DUMMY_MASK, add_start_docstrings, add_start_docstrings_to_model_forward, replace_return_docstrings, ) fr...
MIT License
asteroid-team/asteroid
asteroid/dsp/overlap_add.py
LambdaOverlapAdd.ola_forward
python
def ola_forward(self, x): assert x.ndim == 3 batch, channels, n_frames = x.size() unfolded = torch.nn.functional.unfold( x.unsqueeze(-1), kernel_size=(self.window_size, 1), padding=(self.window_size, 0), stride=(self.hop_size, 1), ) ...
Heart of the class: segment signal, apply func, combine with OLA.
https://github.com/asteroid-team/asteroid/blob/64e10e9de840ada77719ff4fa280be42a19aa51c/asteroid/dsp/overlap_add.py#L84-L131
import torch from torch import nn from ..losses.pit_wrapper import PITReorder class LambdaOverlapAdd(torch.nn.Module): def __init__( self, nnet, n_src, window_size, hop_size=None, window="hanning", reorder_chunks=True, enable_grad=False, ): ...
MIT License
conchylicultor/musicgenerator
deepmusic/modulemanager.py
ModuleManager.save
python
def save(self, config_group): config_group[self.name] = ' '.join([self.module_name] + self.module_parameters)
Save the current module parameters Args: config_group (dict): dictionary where to write the configuration
https://github.com/conchylicultor/musicgenerator/blob/adea76dccaba923b7d3807082ec6f5b512d16bb9/deepmusic/modulemanager.py#L111-L117
from collections import OrderedDict class ModuleManager: def __init__(self, name): self.name = name self.modules = OrderedDict() self.module_instance = None self.module_name = '' self.module_parameters = [] def register(self, module): assert not module.get...
Apache License 2.0
markblundeberg/openswap
lib/util.py
bh2u
python
def bh2u(x): return hfu(x).decode('ascii')
str with hex representation of a bytes-like object >>> x = bytes((1, 2, 10)) >>> bh2u(x) '01020A' :param x: bytes :rtype: str
https://github.com/markblundeberg/openswap/blob/7de04aa80dab79bebe4b64483011dad70a48694c/lib/util.py#L356-L367
import binascii import os, sys, re, json from collections import defaultdict from datetime import datetime import decimal from decimal import Decimal import traceback import threading import hmac import stat from .i18n import _ import queue def inv_dict(d): return {v: k for k, v in d.items()} base_units = {'BCH':8,...
MIT License
spilchen/yahoo_fantasy_api
yahoo_fantasy_api/league.py
League.edit_date
python
def edit_date(self): if self.edit_date_cache is None: json = self.yhandler.get_settings_raw(self.league_id) t = objectpath.Tree(json) edit_key = t.execute('$..edit_key[0]') self.edit_date_cache = datetime.datetime.strptime(edit_key, '%Y-%m-%d').date...
Return the next day that you can edit the lineups. :return: edit date :rtype: :class: datetime.date
https://github.com/spilchen/yahoo_fantasy_api/blob/867444eecffe46541c9c099f4ffc06ab5c178bd2/yahoo_fantasy_api/league.py#L579-L591
import yahoo_fantasy_api as yfa from yahoo_fantasy_api import yhandler import objectpath import datetime import re class League: def __init__(self, sc, league_id): self.sc = sc self.league_id = league_id self.yhandler = yhandler.YHandler(sc) self.current_week_cache = None sel...
MIT License
iristyle/chocolateypackages
EthanBrown.SublimeText2.WebPackages/tools/PackageCache/SublimeLinter/sublimelinter/modules/libs/pyflakes/checker.py
Checker._runDeferred
python
def _runDeferred(self, deferred): for handler, scope in deferred: self.scopeStack = scope handler()
Run the callables in C{deferred} using their associated scope stack.
https://github.com/iristyle/chocolateypackages/blob/8c9833710577de6db6e8b1db5d9196e19e19d117/EthanBrown.SublimeText2.WebPackages/tools/PackageCache/SublimeLinter/sublimelinter/modules/libs/pyflakes/checker.py#L229-L235
import __builtin__ import os.path import _ast from pyflakes import messages try: import ast iter_child_nodes = ast.iter_child_nodes except (ImportError, AttributeError): def iter_child_nodes(node, astcls=_ast.AST): for name in node._fields: field = getattr(node, name, None) i...
MIT License
artyompal/tpu_models
models/official/detection/evaluation/coco_utils.py
generate_annotation_file
python
def generate_annotation_file(groundtruth_generator, annotation_file): groundtruths = {} tf.logging.info('Loading groundtruth annotations from dataset to memory...') for groundtruth in groundtruth_generator(): for k, v in six.iteritems(groundtruth): if k not in groundtruths: ...
Generates COCO-style annotation JSON file given a groundtruth generator.
https://github.com/artyompal/tpu_models/blob/639306f30e085bb1cdb5b1118a4c96a2dbe14e3e/models/official/detection/evaluation/coco_utils.py#L345-L361
from __future__ import absolute_import from __future__ import division from __future__ import print_function import copy import json import numpy as np from PIL import Image from pycocotools import coco from pycocotools import mask as mask_utils import six import tensorflow as tf from dataloader import tf_example_decod...
Apache License 2.0
e-loue/pyke
pyke/target_pkg.py
target_pkg.reset
python
def reset(self, check_sources = True): if debug: print >> sys.stderr, "target_pkg.reset" self.dirty = False self.check_sources = check_sources self.source_packages = {} self.compiled_targets = set() self.rb_names = set()
This should be called once by engine.__init__ prior to calling add_source_package.
https://github.com/e-loue/pyke/blob/cfe95d8aaa06de123264f9b7f5bea20eb5924ecd/pyke/target_pkg.py#L180-L192
from __future__ import with_statement import os, os.path import time import sys import re import pyke debug = False Name_test = re.compile(r'[a-zA-Z_][a-zA-Z0-9_]*$') class target_pkg(object): def __init__(self, module_name, filename = None, pyke_version = pyke.version, ...
MIT License
zomux/deepy
deepy/trainers/base.py
NeuralTrainer.load_params
python
def load_params(self, path, exclude_free_params=False): self.network.load_params(path, exclude_free_params=exclude_free_params) self.best_params = self.copy_params() if self.network.train_logger.progress() > 0 or self.network.train_logger.epoch() > 0: self.skip(self.network.train_log...
Load parameters for the training. This method can load free parameters and resume the training progress.
https://github.com/zomux/deepy/blob/090fbad22a08a809b12951cd0d4984f5bd432698/deepy/trainers/base.py#L144-L153
import sys import time import numpy as np import theano from ..conf import TrainerConfig from ..core import env, runtime from ..utils import Timer from ..dataset import Dataset from controllers import TrainingController from abc import ABCMeta, abstractmethod from logging import getLogger logging = getLogger("trainer")...
MIT License
neuropycon/graphpype
graphpype/labeled_mask.py
compute_ROI_nii_from_ROI_coords_files
python
def compute_ROI_nii_from_ROI_coords_files( ref_img_file, MNI_coords_file, labels_file, neighbourhood=1): ref_image = nib.load(ref_img_file) ref_image_data = ref_image.get_data() ref_image_data_shape = ref_image_data.shape ref_image_data_sform = ref_image.get_sform() ROI_MNI_coords_list = np....
Export single file VOI binary nii image
https://github.com/neuropycon/graphpype/blob/409a370e7d293c3fcff0d733bf7af50850dfa9e4/graphpype/labeled_mask.py#L256-L309
import nipype.interfaces.spm as spm from nipype.utils.filemanip import split_filename as split_f from graphpype.utils import check_np_dimension import itertools as iter import numpy as np import nibabel as nib import glob import os from scipy import ndimage as ndimg from scipy.spatial.distance import cdist def _coord_t...
BSD 3-Clause New or Revised License
sanic-org/sanic
sanic/server/socket.py
remove_unix_socket
python
def remove_unix_socket(path: Optional[str]) -> None: if not path: return try: if stat.S_ISSOCK(os.stat(path, follow_symlinks=False).st_mode): with socket.socket(socket.AF_UNIX) as testsock: try: testsock.connect(path) except Connect...
Remove dead unix socket during server exit.
https://github.com/sanic-org/sanic/blob/3262878ebd41aa2230ef15d4475bbcf223b2356b/sanic/server/socket.py#L74-L87
from __future__ import annotations import os import secrets import socket import stat from ipaddress import ip_address from typing import Optional def bind_socket(host: str, port: int, *, backlog=100) -> socket.socket: try: ip = ip_address(host) host = str(ip) sock = socket.socket( ...
MIT License
alexmohr/sonyapilib
tests/device_test.py
SonyDeviceTest.create_device
python
def create_device(): sonyapilib.device.TIMEOUT = 0.1 device = SonyDevice("test", "test") device.api_version = 3 device.cookies = jsonpickle.decode(read_file("data/cookies.json")) return device
Create a new device instance
https://github.com/alexmohr/sonyapilib/blob/50fd5839e5ffe057c472ae41d3c40e98b92b55a0/tests/device_test.py#L898-L904
import os.path import sys import unittest from inspect import getsourcefile from unittest import mock from urllib.parse import ( urljoin ) import jsonpickle from requests import HTTPError, URLRequired, RequestException from tests.testutil import read_file current_dir = os.path.dirname(os.path.abspath(getsourcefile(...
MIT License
opencivicdata/pupa
pupa/importers/base.py
BaseImporter.import_data
python
def import_data(self, data_items): record = { 'insert': 0, 'update': 0, 'noop': 0, 'start': utcnow(), 'records': { 'insert': [], 'update': [], 'noop': [], } } for json_id, data in self._prepare_import...
import a bunch of dicts together
https://github.com/opencivicdata/pupa/blob/8087e221fc527a80262192d22c2f50966c20604d/pupa/importers/base.py#L220-L244
import os import copy import glob import json import logging from django.db.models import Q from django.db.models.signals import post_save from django.contrib.contenttypes.models import ContentType from opencivicdata.legislative.models import LegislativeSession from pupa import settings from pupa.exceptions import Dupl...
BSD 3-Clause New or Revised License
botfront/rasa-for-botfront
rasa/shared/utils/validation.py
YamlValidationException.__init__
python
def __init__( self, message: Text, validation_errors: Optional[List[SchemaError.SchemaErrorEntry]] = None, filename: Optional[Text] = None, content: Any = None, ) -> None: super(YamlValidationException, self).__init__(filename) self.message = message s...
Create The Error. Args: message: error message validation_errors: validation errors filename: name of the file which was validated content: yaml content loaded from the file (used for line information)
https://github.com/botfront/rasa-for-botfront/blob/6e0e48d0059e197b5f686df1e27935769c3641b7/rasa/shared/utils/validation.py#L34-L53
import logging import os from typing import Text, Dict, List, Optional, Any from packaging import version from packaging.version import LegacyVersion from pykwalify.errors import SchemaError from ruamel.yaml.constructor import DuplicateKeyError import rasa.shared from rasa.shared.exceptions import ( YamlException, ...
Apache License 2.0
containers/podman-py
podman/domain/pods_manager.py
PodsManager.prune
python
def prune(self, filters: Optional[Dict[str, str]] = None) -> Dict[str, Any]: response = self.client.post("/pods/prune", params={"filters": api.prepare_filters(filters)}) response.raise_for_status() deleted: List[str] = list() for item in response.json(): if item["Err"] is not...
Delete unused Pods. Returns: Dictionary Keys: - PodsDeleted (List[str]): List of pod ids deleted. - SpaceReclaimed (int): Always zero. Raises: APIError: when service reports error
https://github.com/containers/podman-py/blob/7cff4162c6cbe3161d9a36bc645e1f11972bf2a9/podman/domain/pods_manager.py#L86-L109
import json import logging from typing import Any, Dict, List, Optional, Union from podman import api from podman.domain.manager import Manager from podman.domain.pods import Pod from podman.errors import APIError logger = logging.getLogger("podman.pods") class PodsManager(Manager): @property def resource(self)...
Apache License 2.0
muges/audiotsm
audiotsm/base/tsm.py
TSM.write_to
python
def write_to(self, writer): raise NotImplementedError
Writes as many result samples as possible to ``writer``. :param writer: a :class:`audiotsm.io.base.Writer`. :returns: a tuple (``n``, ``finished``), with: - ``n`` the number of samples that were written to ``writer`` - ``finished`` a boolean that is ``True`` when there are no s...
https://github.com/muges/audiotsm/blob/cf3875842bda44d81930c44b008937e72109ae9f/audiotsm/base/tsm.py#L95-L110
class TSM(object): def clear(self): raise NotImplementedError def flush_to(self, writer): raise NotImplementedError def get_max_output_length(self, input_length): raise NotImplementedError def read_from(self, reader): raise NotImplementedError def run(self, reader, wr...
MIT License
opennetworkingfoundation/tapi
RI/flask_server/tapi_server/models/tapi_connectivity_connectivity_constraint.py
TapiConnectivityConnectivityConstraint.service_layer
python
def service_layer(self): return self._service_layer
Gets the service_layer of this TapiConnectivityConnectivityConstraint. :return: The service_layer of this TapiConnectivityConnectivityConstraint. :rtype: TapiCommonLayerProtocolName
https://github.com/opennetworkingfoundation/tapi/blob/1f3fd9483d5674552c5a31206c97399c8c151897/RI/flask_server/tapi_server/models/tapi_connectivity_connectivity_constraint.py#L87-L94
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_common_capacity import TapiCommonCapacity from tapi_server.models.tapi_common_forwarding_direction import TapiCommonForwardingDirec...
Apache License 2.0
mikeshardmind/sinbadcogs
channelredirect/redirect.py
ChannelRedirect.rset_add_chan
python
async def rset_add_chan(self, ctx, *channels: discord.TextChannel): if not channels: return await ctx.send_help() gsets = await self.config.guild(ctx.guild).all() mode = gsets["mode"] if not mode: return await ctx.send( "You need to set a mode usin...
Adds one or more channels to the current mode's settings.
https://github.com/mikeshardmind/sinbadcogs/blob/e9353fb63f18f5c2025e177f89b028aa7ac7a63d/channelredirect/redirect.py#L185-L207
from __future__ import annotations import asyncio import contextlib from typing import Set import discord from redbot.core import checks, commands from redbot.core.config import Config from .converters import CogOrCOmmand, CommandConverter, TrinaryBool class ChannelRedirect(commands.Cog): __version__ = "2021.03" ...
Apache License 2.0
giampaolo/pyftpdlib
pyftpdlib/authorizers.py
DummyAuthorizer.add_user
python
def add_user(self, username, password, homedir, perm='elr', msg_login="Login successful.", msg_quit="Goodbye."): if self.has_user(username): raise ValueError('user %r already exists' % username) if not isinstance(homedir, unicode): homedir = homedir.decode('utf8'...
Add a user to the virtual users table. AuthorizerError exceptions raised on error conditions such as invalid permissions, missing home directory or duplicate usernames. Optional perm argument is a string referencing the user's permissions explained below: Read permissions: ...
https://github.com/giampaolo/pyftpdlib/blob/5793ee5f61029d232f940a69a92bf67996be7f00/pyftpdlib/authorizers.py#L75-L117
import errno import os import sys import warnings from ._compat import PY3 from ._compat import unicode from ._compat import getcwdu __all__ = ['DummyAuthorizer', ] class AuthorizerError(Exception): class AuthenticationFailed(Exception): class DummyAuthorizer(object): read_perms = "elr" write_perms =...
MIT License
pypa/pipenv
pipenv/patched/notpip/_vendor/urllib3/connectionpool.py
HTTPSConnectionPool._new_conn
python
def _new_conn(self): self.num_connections += 1 log.debug( "Starting new HTTPS connection (%d): %s:%s", self.num_connections, self.host, self.port or "443", ) if not self.ConnectionCls or self.ConnectionCls is DummyConnection: ra...
Return a fresh :class:`httplib.HTTPSConnection`.
https://github.com/pypa/pipenv/blob/9378cb515189d11841a4de49a5ac3c01fca509ec/pipenv/patched/notpip/_vendor/urllib3/connectionpool.py#L950-L984
from __future__ import absolute_import import errno import logging import sys import warnings from socket import error as SocketError, timeout as SocketTimeout import socket from .exceptions import ( ClosedPoolError, ProtocolError, EmptyPoolError, HeaderParsingError, HostChangedError, LocationVa...
MIT License
100/solid
Solid/HarmonySearch.py
HarmonySearch._score
python
def _score(self, harmony): pass
Returns score of a harmony :param harmony: a harmony :return: score of harmony
https://github.com/100/solid/blob/f38ca4906b7a253bfbb74f271229625d0f1df175/Solid/HarmonySearch.py#L97-L104
from abc import ABCMeta, abstractmethod from random import choice, random, uniform from numpy import argmax, argmin class HarmonySearch: __metaclass__ = ABCMeta cur_steps = None hms = None hmcr = None par = None fw = None memory = None scores = None best = None max_steps = None ...
MIT License
google/aiyprojects-raspbian
src/aiy/leds.py
Leds.rgb
python
def rgb(state, rgb): return {i + 1 : Leds.Channel(state, rgb[i]) for i in range(3)}
Creates a configuration for the RGB channels: 1 (red), 2 (green), 3 (blue). Generally, you should instead use convenience constructors such as :func:`rgb_on` and :func:`rgb_pattern`. Args: state: Either :attr:`Channel.ON`, :attr:`Channel.OFF`, or :attr:`Channel.PATT...
https://github.com/google/aiyprojects-raspbian/blob/964f07f5b4bd2ec785cfda6f318e50e1b67d4758/src/aiy/leds.py#L197-L212
import math import os _DEVICE_PATH = '/sys/class/leds/ktd202x:led1/device/' def _tflash_reg(duration_ms): if duration_ms <= 128: return 0 if duration_ms <= 384: return 1 return min((int(round(duration_ms / 128))) - 2, 126) def _pwm1_reg(percent): return int(round(256.0 * percent)) def _t...
Apache License 2.0
googleapis/synthtool
autosynth/multi.py
_list_issues_cached
python
def _list_issues_cached(gh, *args, **kwargs): return list(gh.list_issues(*args, **kwargs))
A caching wrapper for listing issues, so we don't expend our quota.
https://github.com/googleapis/synthtool/blob/d4ff3cd9a9b2567cc00ab67290eeb89992b20318/autosynth/multi.py#L134-L136
import argparse import functools import importlib import os import pathlib import subprocess import sys import typing from typing import Any, List import requests import yaml from synthtool.report import make_report from autosynth import executor, github, synth from autosynth.log import logger Runner = typing.Callable[...
Apache License 2.0
tmcknight/movie-and-tv-show-search-alfred-workflow
mako/runtime.py
Context.lookup
python
def lookup(self): return self._with_template.lookup
Return the :class:`.TemplateLookup` associated with this :class:`.Context`.
https://github.com/tmcknight/movie-and-tv-show-search-alfred-workflow/blob/243959cd26f2abc194bbc7f9231faf4f1ab28e31/mako/runtime.py#L50-L55
from mako import exceptions, util, compat from mako.compat import compat_builtins import sys class Context(object): def __init__(self, buffer, **data): self._buffer_stack = [buffer] self._data = data self._kwargs = data.copy() self._with_template = None self._outputting_as_un...
MIT License
yoseflab/cassiopeia
cassiopeia/preprocess/utilities.py
convert_alleletable_to_lineage_profile
python
def convert_alleletable_to_lineage_profile( allele_table, cut_sites: Optional[List[str]] = None, collapse_duplicates: bool = True, ) -> pd.DataFrame: if cut_sites is None: cut_sites = get_default_cut_site_columns(allele_table) agg_recipe = dict( zip([cutsite for cutsite in cut_sites]...
Converts an AlleleTable to a lineage profile. Takes in an allele table that summarizes the indels observed at individual cellBC-intBC pairs and produces a lineage profile, which essentially is a pivot table over the cellBC / intBCs. Conceptually, these lineage profiles are identical to character matric...
https://github.com/yoseflab/cassiopeia/blob/6a4479e260a5fbefc663e0cecb7dfd51a4a01376/cassiopeia/preprocess/utilities.py#L480-L555
import functools import itertools import os import time from typing import Callable, Dict, List, Optional, Tuple import warnings from collections import defaultdict, OrderedDict import matplotlib import matplotlib.pyplot as plt import ngs_tools as ngs import numpy as np import pandas as pd import pylab import pysam imp...
MIT License
a3data/hermione
hermione/module_templates/__IMPLEMENTED_BASE__/src/ml/model/wrapper.py
Wrapper.get_metrics
python
def get_metrics(self): return self.artifacts["metrics"]
Return metrics Parameters ---------- self : object Wrapper Returns ------- dict
https://github.com/a3data/hermione/blob/4a833e96664fc91c65bdd28b2637c291f4f5a4d6/hermione/module_templates/__IMPLEMENTED_BASE__/src/ml/model/wrapper.py#L150-L162
from joblib import dump, load from datetime import date import mlflow.pyfunc from mlflow import pyfunc from interpret.ext.blackbox import TabularExplainer, MimicExplainer from interpret.ext.glassbox import * import pandas as pd from util import load_yaml, load_json class Wrapper(mlflow.pyfunc.PythonModel): def __in...
Apache License 2.0
ansible-community/ansible-lint
src/ansiblelint/prerun.py
_write_module_stub
python
def _write_module_stub( filename: str, name: str, namespace: Optional[str] = None, collection: Optional[str] = None, ) -> None: body = ANSIBLE_MOCKED_MODULE.format( name=name, collection=collection, namespace=namespace ) with open(filename, "w") as f: f.write(body)
Write module stub to disk.
https://github.com/ansible-community/ansible-lint/blob/306573167ad21c37a5aa72017bda57e1bad28c80/src/ansiblelint/prerun.py#L354-L365
import json import logging import os import pathlib import re import subprocess import sys from functools import lru_cache from typing import Any, Dict, List, Optional, Tuple, Type, Union import packaging import tenacity from packaging import version from ansiblelint.config import ( ansible_collections_path, co...
MIT License
dmontagu/fastapi-utils
fastapi_utils/api_settings.py
get_api_settings
python
def get_api_settings() -> APISettings: return APISettings()
This function returns a cached instance of the APISettings object. Caching is used to prevent re-reading the environment every time the API settings are used in an endpoint. If you want to change an environment variable and reset the cache (e.g., during testing), this can be done using the `lru_cache` ins...
https://github.com/dmontagu/fastapi-utils/blob/af95ff4a8195caaa9edaa3dbd5b6eeb09691d9c7/fastapi_utils/api_settings.py#L60-L69
from functools import lru_cache from typing import Any, Dict from pydantic import BaseSettings class APISettings(BaseSettings): debug: bool = False docs_url: str = "/docs" openapi_prefix: str = "" openapi_url: str = "/openapi.json" redoc_url: str = "/redoc" title: str = "FastAPI" version: st...
MIT License
therve/twotp
twotp/packer.py
Packer.pack_float
python
def pack_float(self, term): term = "%.20e" % (term,) packetData = self.packChar(self.MAGIC_FLOAT) packetData += term nullPadStr = "\0" * (31 - len(term)) return packetData + nullPadStr
Pack a float.
https://github.com/therve/twotp/blob/67d0c9475c5c211e8f9d6280f8c3e04fff944a73/twotp/packer.py#L110-L118
import struct import zlib from twotp.term import ConstantHolder, Atom class UnhandledClass(KeyError): class Packer(ConstantHolder): MAX_INT = pow(2, 32) MAX_SHORT = pow(2, 16) MAX_CHAR = pow(2, 8) def packChar(self, char): return chr(char) def packShort(self, short): if short >= self...
MIT License
bigpon/qpnet
src/nets/qpnet.py
DilatedConv1d.forward
python
def forward(self, xC, xP): xC = self.convC(xC) xP = self.convP(xP) return xC + xP
Forward calculation Arg: xC (tensor): float tensor variable with the shape (B x C x T) xP (tensor): float tensor variable with the shape (B x C x T) Return: (tensor): float tensor variable with the shape (B x C x T)
https://github.com/bigpon/qpnet/blob/657fcb01b23e9e3371b5a4b2ebeec5757ad33e2d/src/nets/qpnet.py#L98-L108
from __future__ import division import logging import sys import time import yaml import torch import numpy as np import torch.nn.functional as F from torch import nn from numpy.matlib import repmat def encode_mu_law(x, mu=256): mu = mu - 1 fx = np.sign(x) * np.log(1 + mu * np.abs(x)) / np.log(1 + mu) retur...
Apache License 2.0
paddlepaddle/paddle
python/paddle/fluid/layers/sequence_lod.py
sequence_slice
python
def sequence_slice(input, offset, length, name=None): assert not in_dygraph_mode(), ( "sequence layer is not supported in dygraph mode yet.") helper = LayerHelper("sequence_slice", **locals()) check_variable_and_dtype(input, 'input', ['float32', 'float64', 'int32', 'int6...
:api_attr: Static Graph **Sequence Slice Layer** The layer crops a subsequence from given sequence with given start offset and subsequence length. It only supports sequence data (LoDTensor with lod_level equal to 1). .. code-block:: text - Case: Given the input Variab...
https://github.com/paddlepaddle/paddle/blob/056b87414880e0520bb4560fc40d5b62db9c5175/python/paddle/fluid/layers/sequence_lod.py#L560-L647
from __future__ import print_function from .layer_function_generator import templatedoc from ..framework import Variable, in_dygraph_mode from ..layer_helper import LayerHelper from ..data_feeder import check_variable_and_dtype, check_type, check_dtype from ..core import VarDesc __all__ = [ 'sequence_conv', 'se...
Apache License 2.0
azure/azure-devops-cli-extension
azure-devops/azext_devops/devops_sdk/v5_1/work_item_tracking/work_item_tracking_client.py
WorkItemTrackingClient.delete_comment_reaction
python
def delete_comment_reaction(self, project, work_item_id, comment_id, reaction_type): route_values = {} if project is not None: route_values['project'] = self._serialize.url('project', project, 'str') if work_item_id is not None: route_values['workItemId'] = self._serializ...
DeleteCommentReaction. [Preview API] Deletes an existing reaction on a comment. :param str project: Project ID or project name :param int work_item_id: WorkItem ID :param int comment_id: Comment ID :param CommentReactionType reaction_type: Type of the reaction :rtype: :cl...
https://github.com/azure/azure-devops-cli-extension/blob/5f33f7d81a9c2d2990044fbd9ffa6b535cbda528/azure-devops/azext_devops/devops_sdk/v5_1/work_item_tracking/work_item_tracking_client.py#L521-L543
 from msrest import Serializer, Deserializer from ...client import Client from . import models class WorkItemTrackingClient(Client): def __init__(self, base_url=None, creds=None): super(WorkItemTrackingClient, self).__init__(base_url, creds) client_models = {k: v for k, v in models.__dict__.items()...
MIT License
google/clusterfuzz
src/clusterfuzz/_internal/base/retry.py
get_delay
python
def get_delay(num_try, delay, backoff): return delay * (backoff**(num_try - 1))
Compute backoff delay.
https://github.com/google/clusterfuzz/blob/e9e105d66f009356c4f3fe9ae7873ffff126b234/src/clusterfuzz/_internal/base/retry.py#L32-L34
import functools import inspect import sys import time from clusterfuzz._internal.metrics import logs def sleep(seconds): time.sleep(seconds)
Apache License 2.0
dynatrace/dynatrace-cli
dtcli.py
parsePipelineInfo
python
def parsePipelineInfo(pipelineinfofile): pipelineinfo = None with open(pipelineinfofile) as json_data: pipelineinfo = json.load(json_data) return pipelineinfo
will parse the pipelineinfo file
https://github.com/dynatrace/dynatrace-cli/blob/4954a85fddce4db3723d1d5c9a0e5e5ba937003d/dtcli.py#L517-L524
import sys import io import re import os import json import time import datetime import operator import urllib import requests import urllib3 import uuid urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning) API_ENDPOINT_APPLICATIONS = "/api/v1/entity/applications" API_ENDPOINT_SERVICES = "/api/v1/entity/...
Apache License 2.0
wildltr/ptranking
ptranking/data/data_utils.py
clip_query_data
python
def clip_query_data(qid, list_docids=None, feature_mat=None, std_label_vec=None, binary_rele=False, unknown_as_zero=False, clip_query=None, min_docs=None, min_rele=1, presort=None): if binary_rele: std_label_vec = np.clip(std_label_vec, a_min=-10, a_max=1) if unknown_as_zero: std_label_vec ...
Clip the data associated with the same query if required
https://github.com/wildltr/ptranking/blob/8f54be4dbfa0b0aba4c9c80b647ddbe7e571cf26/ptranking/data/data_utils.py#L406-L435
import os import random import numpy as np from pathlib import Path from enum import Enum, unique, auto from sklearn.preprocessing import MinMaxScaler, RobustScaler, StandardScaler import torch import torch.utils.data as data from ptranking.ltr_adhoc.util.bin_utils import batch_count from ptranking.utils.numpy.np_exten...
MIT License
netromdk/slacker
slacker/commands/command.py
Command.name
python
def name(self): pass
Returns the name of the command. This is the actual command, like 'download'.
https://github.com/netromdk/slacker/blob/56ab630ba11451c254c5ec377f76033b692c61ce/slacker/commands/command.py#L32-L34
import re from cachetools import TTLCache from abc import ABC, abstractmethod from slacker.logger import Logger from slacker.slack_api import SlackAPI from prompt_toolkit.completion import WordCompleter COMMAND_NAME_REGEX = re.compile("([\w\d][\w\d\.]*)?[\w\d]+") class Command(ABC): def __init__(self): self.__val...
MIT License
neuropower/neurodesign
source/src/neurodesign.py
experiment.countstim
python
def countstim(self): self.trial_duration = self.stim_duration + self.t_pre + self.t_post if self.ITImodel == "uniform": self.ITImean = (self.ITImax + self.ITImin) / 2 if self.duration: if not self.restnum == 0: blockdurNR = self.restnum * ...
Function to compute some arguments depending on other arguments.
https://github.com/neuropower/neurodesign/blob/605b97a616b53f4e9ea767460471fc7c8d9bdd77/source/src/neurodesign.py#L434-L470
from __future__ import division from . import msequence, generate, report from numpy import transpose as t from scipy.special import gamma from collections import Counter from numpy.linalg import inv from scipy import linalg import sklearn.cluster import scipy.linalg import pandas as pd import progressbar import numpy ...
MIT License
avatartwo/avatar2
avatar2/protocols/unicorn_protocol.py
UnicornProtocol._worker_emu_start
python
def _worker_emu_start(self, single_step=False): self._worker_queue.put(UnicornWorkerEmuStartMessage(single_step))
Start the emulation inside the worker.
https://github.com/avatartwo/avatar2/blob/86a824072ef991a3a240688600f109eec8ad1ff7/avatar2/protocols/unicorn_protocol.py#L305-L307
import sys if sys.version_info < (3, 0): import Queue as queue else: import queue import struct import unicorn import logging from threading import Thread from collections import namedtuple from avatar2.message import UpdateStateMessage, RemoteMemoryReadMessage, RemoteMemoryWriteMessage, BreakpointHitMessage...
Apache License 2.0
gilch/drython
drython/core.py
identity
python
def identity(x): return x
The identity function. Returns its argument. not to be confused with the id() builtin >>> identity('foo') 'foo'
https://github.com/gilch/drython/blob/eb1773c14060e31e2544f5fb69dd31621d0bc291/drython/core.py#L265-L272
from __future__ import absolute_import, division, print_function from abc import ABCMeta, abstractmethod from collections import Mapping import sys from itertools import islice, chain from functools import wraps if sys.version_info[0] == 2: from itertools import izip_longest as zip_longest else: from iterto...
Apache License 2.0
christophreich1996/toeffipy
autograd/nn/functional.py
cross_entropy_loss
python
def cross_entropy_loss(prediction: Tensor, label: Tensor, reduction: str = 'mean') -> Tensor: assert label.shape == prediction.shape, 'Shape of label must match with prediction' loss = - (label * autograd.log(prediction)) return _apply_reduction(tensor=loss, reduction=reduction)
Function implements the multi class cross entropy loss in autograd :param prediction: (Tensor) Prediction tensor :param label: (Tensor) One hot encoded label tensor :param reduction: (str) Type of reduction to perform after apply the loss (mean, sum or none) :return: (Tensor) Loss value
https://github.com/christophreich1996/toeffipy/blob/34ca9cd97a488cdc58d2b909ba963edb80ae2b76/autograd/nn/functional.py#L735-L748
from typing import List, Union, Tuple, Optional import autograd from autograd import Tensor from autograd.tensor import Dependency import numpy as np def _conv_2d_core(input: np.ndarray, kernel: np.ndarray) -> np.ndarray: input = input.transpose((0, 2, 3, 1)) kernel = kernel.transpose((2, 3, 1, 0)) input = ...
MIT License
abhisharma404/vault
src/lib/utilities/mac_changer/mac_changer.py
MACChanger.startProcess
python
def startProcess(self): self.changeMAC(self.newMAC) checkMAC = self.interfaceMAC() if checkMAC == self.newMAC: colors.success('MAC address succesfully changed to : {}' .format(self.newMAC)) choice = str(input('>> Do you want to restore to defaul...
Change the MAC address of the interface
https://github.com/abhisharma404/vault/blob/0303cf425f028ce38cfaf40640d625861b7c805a/src/lib/utilities/mac_changer/mac_changer.py#L169-L187
import subprocess import re import sys import time import random import colors import os class MACChanger(object): def __init__(self, mac_addr=None, interface=None): self.is_root() if mac_addr is None: self.newMAC = self.generateMAC() elif self.validateMAC(mac_addr): ...
MIT License
bbn-q/auspex
src/auspex/instruments/prologix.py
PrologixSocketResource.connect
python
def connect(self, ipaddr=None, gpib=None): if ipaddr is not None: self.ipaddr = ipaddr if gpib is not None: self.gpib = gpib try: self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_TCP) self.sock.settimeout...
Connect to a GPIB device through a Prologix GPIB-ETHERNET controller. box. Args: ipaddr: The IP address of the Prologix GPIB-ETHERNET. gpib: The GPIB address of the instrument to be controlled. Returns: None.
https://github.com/bbn-q/auspex/blob/e9763e1907546ad49210415a6b8c2f6d9999f31a/src/auspex/instruments/prologix.py#L58-L98
__all__ = ['PrologixSocketResource'] import os import numpy as np import socket import functools from auspex.log import logger from pyvisa.util import _converters, from_ascii_block, to_ascii_block, to_ieee_block, from_binary_block class PrologixError(Exception): class PrologixSocketResource(object): def __init__(se...
Apache License 2.0
pytorch/fairseq
examples/speech_synthesis/utils.py
gross_pitch_error
python
def gross_pitch_error(true_t, true_f, est_t, est_f): correct_frames = _true_voiced_frames(true_t, true_f, est_t, est_f) gross_pitch_error_frames = _gross_pitch_error_frames( true_t, true_f, est_t, est_f ) return np.sum(gross_pitch_error_frames) / np.sum(correct_frames)
The relative frequency in percent of pitch estimates that are outside a threshold around the true pitch. Only frames that are considered pitched by both the ground truth and the estimator (if applicable) are considered.
https://github.com/pytorch/fairseq/blob/fcca32258c8e8bcc9f9890bf4714fa2f96b6b3e1/examples/speech_synthesis/utils.py#L55-L66
import numpy as np import torch from scipy.interpolate import interp1d import torchaudio from fairseq.tasks.text_to_speech import ( batch_compute_distortion, compute_rms_dist ) def batch_mel_spectral_distortion( y1, y2, sr, normalize_type="path", mel_fn=None ): if mel_fn is None or mel_fn.sample_rate !=...
MIT License
cc1-cloud/cc1
src/cm/views/user/system_image.py
get_by_id
python
def get_by_id(caller_id, system_image_id, groups): return SystemImage.get(caller_id, system_image_id, groups).dict
@cmview_user @param_post{groups,list(int)} list of Groups ids, required for @val{group} access @param_post{system_image_id,int} id of the requested Image @response{dict} SystemImage.dict property of the requested SystemImage
https://github.com/cc1-cloud/cc1/blob/8113673fa13b6fe195cea99dedab9616aeca3ae8/src/cm/views/user/system_image.py#L121-L129
import os import urllib from cm.models.iso_image import IsoImage from cm.models.storage_image import StorageImage from cm.models.system_image import SystemImage from cm.models.system_image_group import SystemImageGroup from cm.models.user import User from cm.utils import log from cm.utils.decorators import user_log fro...
Apache License 2.0
mscroggs/symfem
symfem/functionals.py
InnerProductIntegralMoment.dot
python
def dot(self, function): tdim = len(self.inner_with_left) return vdot(self.inner_with_left, tuple(vdot(function[tdim * i: tdim * (i + 1)], self.inner_with_right) for i in range(0, tdim))) * self.f * self.reference.jacobian()
Take the inner product of a function with the moment direction.
https://github.com/mscroggs/symfem/blob/a08155837e49abe9123d2d8edf60fd36f7f1b8ee/symfem/functionals.py#L506-L511
import sympy import numpy from .symbolic import subs, x, t, PiecewiseFunction, sym_sum, to_sympy, to_float from .vectors import vdot from .calculus import derivative, jacobian_component, grad, diff, div from . import mappings class BaseFunctional: def __init__(self, entity=(None, None), mapping="identity"): ...
MIT License
openforcefield/openff-interchange
openff/interchange/components/interchange.py
Interchange.remove_handler
python
def remove_handler(self, handler_name: str): self._inner_data.handlers.pop(handler_name)
Remove a PotentialHandler in this Interchange object.
https://github.com/openforcefield/openff-interchange/blob/a080e348b62c36c3c6a6b04e8afde64556f3186e/openff/interchange/components/interchange.py#L92-L94
import warnings from copy import deepcopy from pathlib import Path from typing import TYPE_CHECKING, Dict, Optional, Tuple, Union import mdtraj as md import numpy as np from openff.toolkit.topology.topology import Topology from openff.toolkit.typing.engines.smirnoff import ForceField from openff.utilities.utilities imp...
MIT License
weblyzard/weblyzard_api
src/python/weblyzard_api/client/domain_specificity.py
DomainSpecificity.parse_documents
python
def parse_documents(self, matview_name, documents, is_case_sensitive=False, batch_size=None): found_tags = {} for document_batch in self.get_document_batch(documents=documents, batch_size=batch_size): result = self...
:param matview_name: a comma separated list of matview_names to check \ for domain specificity. :param documents: a list of dictionaries containing the document :param is_case_sensitive: case sensitive or not :returns: dict (profilename: (content_id, dom_spec))
https://github.com/weblyzard/weblyzard_api/blob/9dfc8d617e1fb0f78548a40162b0d3c2cff6d12b/src/python/weblyzard_api/client/domain_specificity.py#L64-L82
from __future__ import unicode_literals from eWRT.ws.rest import MultiRESTClient from weblyzard_api.client import ( WEBLYZARD_API_URL, WEBLYZARD_API_USER, WEBLYZARD_API_PASS) class DomainSpecificity(MultiRESTClient): URL_PATH = 'rest/domain_specificity' def __init__(self, url=WEBLYZARD_API_URL, usr=WEBLYZAR...
Apache License 2.0
nteract/scrapbook
scrapbook/models.py
Notebook.filename
python
def filename(self): return os.path.basename(self.path)
str: filename found a the specified path
https://github.com/nteract/scrapbook/blob/3c74e63f7df99cca3148182454797792aede4b9b/scrapbook/models.py#L93-L95
from __future__ import unicode_literals import os import copy import nbformat import collections import pandas as pd from six import string_types from collections import OrderedDict from papermill.iorw import papermill_io from .scraps import Scrap, Scraps, payload_to_scrap, scrap_to_payload from .schemas import GLUE_PA...
BSD 3-Clause New or Revised License
elastic/eland
eland/field_mappings.py
FieldMappings.field_name_pd_dtype
python
def field_name_pd_dtype(self, es_field_name: str) -> str: if es_field_name not in self._mappings_capabilities.es_field_name: raise KeyError(f"es_field_name {es_field_name} does not exist") pd_dtype = self._mappings_capabilities.loc[ self._mappings_capabilities.es_field_name == es...
Parameters ---------- es_field_name: str Returns ------- pd_dtype: str The pandas data type we map to Raises ------ KeyError If es_field_name does not exist in mapping
https://github.com/elastic/eland/blob/704c8982bcd5f89787c47c267b3d1572bb1cecdb/eland/field_mappings.py#L653-L675
import warnings from typing import ( TYPE_CHECKING, Any, Dict, List, Mapping, NamedTuple, Optional, Set, TextIO, Tuple, Union, ) import numpy as np import pandas as pd from pandas.core.dtypes.common import ( is_bool_dtype, is_datetime_or_timedelta_dtype, is_fl...
Apache License 2.0
pactools/pactools
pactools/dar_model/base_dar.py
BaseDAR.bic
python
def bic(self): return self._compute_criterion()['bic']
Bayesian information criterion (BIC) of the model
https://github.com/pactools/pactools/blob/1e95893bdfedf6e646749cf380c3815d4165bd9a/pactools/dar_model/base_dar.py#L446-L448
from abc import ABCMeta, abstractmethod import warnings import numpy as np import matplotlib.pyplot as plt from scipy import linalg from scipy.signal import fftconvolve from scipy import stats from ..utils.progress_bar import ProgressBar from ..utils.maths import squared_norm from ..utils.validation import check_array,...
BSD 3-Clause New or Revised License
lttm/gmnet
Deeplab/research/deeplab/core/resnet_v1_beta.py
root_block_fn_for_beta_variant
python
def root_block_fn_for_beta_variant(net, depth_multiplier=1.0): net = conv2d_ws.conv2d_same( net, int(64 * depth_multiplier), 3, stride=2, scope='conv1_1') net = conv2d_ws.conv2d_same( net, int(64 * depth_multiplier), 3, stride=1, scope='conv1_2') net = conv2d_ws.conv2d_same( net, int...
Gets root_block_fn for beta variant. ResNet-v1 beta variant modifies the first original 7x7 convolution to three 3x3 convolutions. Args: net: A tensor of size [batch, height, width, channels], input to the model. depth_multiplier: Controls the number of convolution output channels for each input c...
https://github.com/lttm/gmnet/blob/e17959eb219e1884e2be271c9244ba284c2f4ffa/Deeplab/research/deeplab/core/resnet_v1_beta.py#L153-L175
from __future__ import absolute_import from __future__ import division from __future__ import print_function import functools from six.moves import range import tensorflow as tf from tensorflow.contrib import slim as contrib_slim from research.deeplab.core import conv2d_ws from research.deeplab.core import utils from t...
Apache License 2.0
sally20921/all4depth
all4depth/loggers/wandb_logger.py
prep_image
python
def prep_image(prefix, key, image): if is_tensor(image): image = image.detach().permute(1, 2, 0).cpu().numpy() prefix_key = '{}-{}'.format(prefix, key) return {prefix_key: wandb.Image(image, caption=key)}
Prepare image for wandb logging Parameters ---------- prefix : str Prefix added to the key for logging key : str Key from data containing the inverse depth map image : torch.Tensor [3,H,W] Image to be logged Returns ------- output : dict Dictionary with ...
https://github.com/sally20921/all4depth/blob/ef058839e16b277b4ffa6a890d03cd90b6c36283/all4depth/loggers/wandb_logger.py#L252-L273
from argparse import Namespace from collections import OrderedDict import numpy as np import torch.nn as nn import wandb from wandb.wandb_run import Run from all4depth.utils.depth import viz_inv_depth from all4depth.utils.logging import prepare_dataset_prefix from all4depth.utils.types import is_dict, is_tensor class W...
MIT License
catalyst-cooperative/pudl
src/pudl/glue/ferc1_eia.py
get_lost_utils_eia
python
def get_lost_utils_eia(pudl_engine): db_utils_eia = get_db_utils_eia(pudl_engine) mapped_utils_eia = get_mapped_utils_eia() lost_utils_idx = mapped_utils_eia.index.difference(db_utils_eia.index) lost_utils_eia = mapped_utils_eia.loc[lost_utils_idx] return lost_utils_eia
Get a list of all mapped EIA Utilites not found in the PUDL DB.
https://github.com/catalyst-cooperative/pudl/blob/6a75069b90219a2da55262737b92fe0a024c4fb8/src/pudl/glue/ferc1_eia.py#L565-L571
import importlib import logging import pandas as pd import sqlalchemy as sa import pudl from pudl import constants as pc logger = logging.getLogger(__name__) def get_plant_map(): map_eia_ferc_file = importlib.resources.open_binary( 'pudl.package_data.glue', 'mapping_eia923_ferc1.xlsx') return pd.read_ex...
MIT License
tell-k/goolabs
goolabs/commands.py
morph
python
def morph(ctx, app_id, sentence_file, json_flag, sentence, info_filter, pos_filter, request_id): app_id = clean_app_id(app_id) sentence = clean_sentence(sentence, sentence_file) if info_filter: info_filter = info_filter.replace(',', '|') if pos_filter: pos_filter = pos_filter.r...
Morphological analysis for Japanese.
https://github.com/tell-k/goolabs/blob/3b87d0409e55c71290158ad6d5e2d8bb9a338c46/goolabs/commands.py#L107-L135
from __future__ import division, print_function, absolute_import import json import locale import click import six import goolabs from goolabs import GoolabsAPI if 0: from typing import Optional, IO, List, Dict, Any from click.core import Context def text(s): if isinstance(s, six.binary_type): ...
MIT License
machine-learning-exchange/mlx
api/client/swagger_client/models/api_pipeline_extended.py
ApiPipelineExtended.__init__
python
def __init__(self, id=None, created_at=None, name=None, description=None, parameters=None, status=None, default_version_id=None, namespace=None, annotations=None, featured=None, publish_approved=None): self._id = None self._created_at = None self._name = None self._description = None ...
ApiPipelineExtended - a model defined in Swagger
https://github.com/machine-learning-exchange/mlx/blob/be1503c45538dac1a8188560fbec4a07b2a367bf/api/client/swagger_client/models/api_pipeline_extended.py#L68-L105
import pprint import re import six from swagger_client.models.api_parameter import ApiParameter from swagger_client.models.api_pipeline import ApiPipeline from swagger_client.models.api_pipeline_extension import ApiPipelineExtension class ApiPipelineExtended(ApiPipeline, ApiPipelineExtension): """ Attri...
Apache License 2.0
osmr/imgclsmob
keras_/kerascv/models/igcv3.py
igcv3_w3d4
python
def igcv3_w3d4(**kwargs): return get_igcv3(width_scale=0.75, model_name="igcv3_w3d4", **kwargs)
IGCV3-D 0.75x model from 'IGCV3: Interleaved Low-Rank Group Convolutions for Efficient Deep Neural Networks,' https://arxiv.org/abs/1806.00178. Parameters: ---------- pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.keras/models' ...
https://github.com/osmr/imgclsmob/blob/ea5f784eea865ce830f3f97c5c1d1f6491d9cbb2/keras_/kerascv/models/igcv3.py#L230-L242
__all__ = ['igcv3', 'igcv3_w1', 'igcv3_w3d4', 'igcv3_wd2', 'igcv3_wd4'] import os from keras import layers as nn from keras.models import Model from .common import conv1x1_block, conv3x3_block, dwconv3x3_block, channel_shuffle_lambda, is_channels_first, flatten def inv_res_unit(x, in_channels, ...
MIT License
argoproj-labs/argo-client-python
argo/workflows/client/models/v1alpha1_hdfs_artifact.py
V1alpha1HDFSArtifact.krb_realm
python
def krb_realm(self, krb_realm): self._krb_realm = krb_realm
Sets the krb_realm of this V1alpha1HDFSArtifact. KrbRealm is the Kerberos realm used with Kerberos keytab It must be set if keytab is used. # noqa: E501 :param krb_realm: The krb_realm of this V1alpha1HDFSArtifact. # noqa: E501 :type: str
https://github.com/argoproj-labs/argo-client-python/blob/993d684cab39a834770b296e028519cec035c7b5/argo/workflows/client/models/v1alpha1_hdfs_artifact.py#L244-L253
import pprint import re import six from argo.workflows.client.configuration import Configuration class V1alpha1HDFSArtifact(object): """ Attributes: openapi_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The key is attribu...
Apache License 2.0
lightly-ai/lightly
lightly/openapi_generated/swagger_client/api/datasets_api.py
DatasetsApi.delete_dataset_by_id_with_http_info
python
def delete_dataset_by_id_with_http_info(self, dataset_id, **kwargs): all_params = ['dataset_id'] all_params.append('async_req') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() ...
delete_dataset_by_id # noqa: E501 Delete a specific dataset # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.delete_dataset_by_id_with_http_info(dataset_id, async_req=True) >...
https://github.com/lightly-ai/lightly/blob/00820e5a60522effb3685a8d792f15e99770ea50/lightly/openapi_generated/swagger_client/api/datasets_api.py#L157-L228
from __future__ import absolute_import import re import six from lightly.openapi_generated.swagger_client.api_client import ApiClient class DatasetsApi(object): def __init__(self, api_client=None): if api_client is None: api_client = ApiClient() self.api_client = api_client def cre...
MIT License
genomicsengland/gelreportmodels
protocols/migration/migration_reports_500_to_reports_400.py
MigrateReports500To400.migrate_interpretation_request_rd
python
def migrate_interpretation_request_rd(self, old_instance, old_ig): new_instance = self.convert_class(self.new_model.InterpretationRequestRD, old_instance) new_instance.versionControl = self.new_model.ReportVersionControl() new_instance.genomeAssemblyVersion = old_instance.genomeAssembly ...
Migrates a reports_5_0_0.InterpretationRequestRD into a reports_4_0_0.InterpretationRequestRD :type old_instance: reports_5_0_0.InterpretationRequestRD :type old_ig: reports_5_0_0.InterpretedGenomeRD :rtype: reports_4_0_0.InterpretationRequestRD
https://github.com/genomicsengland/gelreportmodels/blob/879bf5dd6d16efc274257e1c3f527d6b7459fa45/protocols/migration/migration_reports_500_to_reports_400.py#L58-L90
import logging import distutils.util from protocols import reports_4_0_0 as reports_4_0_0 from protocols import reports_5_0_0 as reports_5_0_0 from protocols.migration.base_migration import BaseMigrateReports400And500 from protocols.migration.base_migration import MigrationError from protocols.migration import MigrateP...
Apache License 2.0
joonaspu/video-game-behavioural-cloning
record_human_play.py
finish_recording
python
def finish_recording(recording_path, env_name, unique_id, data): trajectory_file = os.path.join( recording_path, "trajectories_pressed_buttons", "{}".format(env_name), "{}.json".format(unique_id) ) with open(trajectory_file, "w") as f: json.dump(data, f)
Store recorded data into a json file
https://github.com/joonaspu/video-game-behavioural-cloning/blob/828aaba3d8d275564f15f809611a3c253cea0298/record_human_play.py#L66-L75
import argparse import time import os import json from video_game_env.connection import Connection parser = argparse.ArgumentParser("""Record humans playing video games. Hotkeys: - Page Up + Q: Quit - Page Up + R: Start recording, or stop and start new recording - Page Up + S: Stop record...
MIT License
tomplus/kubernetes_asyncio
kubernetes_asyncio/client/models/admissionregistration_v1beta1_webhook_client_config.py
AdmissionregistrationV1beta1WebhookClientConfig.ca_bundle
python
def ca_bundle(self, ca_bundle): if (self.local_vars_configuration.client_side_validation and ca_bundle is not None and not re.search(r'^(?:[A-Za-z0-9+\/]{4})*(?:[A-Za-z0-9+\/]{2}==|[A-Za-z0-9+\/]{3}=)?$', ca_bundle)): raise ValueError(r"Invalid value for `ca_bundle`, must be a foll...
Sets the ca_bundle of this AdmissionregistrationV1beta1WebhookClientConfig. `caBundle` is a PEM encoded CA bundle which will be used to validate the webhook's server certificate. If unspecified, system trust roots on the apiserver are used. # noqa: E501 :param ca_bundle: The ca_bundle of this Admissi...
https://github.com/tomplus/kubernetes_asyncio/blob/22bf0f4ec775b920abc9cee86bb38abcfc57506d/kubernetes_asyncio/client/models/admissionregistration_v1beta1_webhook_client_config.py#L77-L89
import pprint import re import six from kubernetes_asyncio.client.configuration import Configuration class AdmissionregistrationV1beta1WebhookClientConfig(object): """ Attributes: openapi_types (dict): The key is attribute name and the value is attribute type. attribute...
Apache License 2.0
hbdmapi/huobi_futures_python
alpha/quant.py
Quant.initialize
python
def initialize(self, config_module=None): self._get_event_loop() self._load_settings(config_module) self._init_logger() self._init_db_instance() self._get_version() self._do_heartbeat()
Initialize. Args: config_module: config file path, normally it"s a json file.
https://github.com/hbdmapi/huobi_futures_python/blob/a505cfef0591d4adc610b7ef11bd06cb2d2ae2a5/alpha/quant.py#L29-L40
import signal import asyncio from alpha.utils import logger from alpha.config import config from alpha.const import VERSION class Quant: def __init__(self): self.loop = None
MIT License
hopshadoop/hdfscontents
hdfscontents/hdfsio.py
HDFSManagerMixin._hdfs_ensure_dir_exists
python
def _hdfs_ensure_dir_exists(self, hdfs_path): if not self.hdfs.exists(hdfs_path): try: self.hdfs.create_directory(hdfs_path) self.hdfs.chmod(hdfs_path, 0o0770) except OSError as e: if e.errno != errno.EEXIST: raise ...
ensure that a directory exists If it doesn't exist, try to create it and protect against a race condition if another process is doing the same.
https://github.com/hopshadoop/hdfscontents/blob/1eafd6260f2edca0ec9093196167d2233fdecfb2/hdfscontents/hdfsio.py#L174-L189
from contextlib import contextmanager import errno import os from tornado.web import HTTPError from notebook.utils import ( to_api_path, to_os_path, ) import nbformat from pydoop.hdfs.path import split from ipython_genutils.py3compat import str_to_unicode from traitlets.config import Configurable from traitlets...
Apache License 2.0
fusionauth/fusionauth-python-client
src/main/python/fusionauth/fusionauth_client.py
FusionAuthClient.create_user_consent
python
def create_user_consent(self, request, user_consent_id=None): return self.start().uri('/api/user/consent') .url_segment(user_consent_id) .body_handler(JSONBodyHandler(request)) .post() .go()
Creates a single User consent. Attributes: user_consent_id: (Optional) The Id for the User consent. If not provided a secure random UUID will be generated. request: The request that contains the user consent information.
https://github.com/fusionauth/fusionauth-python-client/blob/20bf313710eb0af6bfb9c07b7864b52fe5853eb0/src/main/python/fusionauth/fusionauth_client.py#L497-L509
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
stlehmann/pyads
pyads/constants.py
PLCTYPE_ARR_SHORT
python
def PLCTYPE_ARR_SHORT(n: int) -> Type[Array]: return c_int16 * n
Return an array with n short values.
https://github.com/stlehmann/pyads/blob/3c505092dafb2cd3f85c77ab6c700b99976cf5da/pyads/constants.py#L166-L168
from typing import Type, Dict, Callable, Union from ctypes import ( Array, c_bool, c_ubyte, c_int8, c_uint8, c_int16, c_uint16, c_int32, c_uint32, c_float, c_double, c_char, c_int64, c_uint64, ) STRING_BUFFER: int = 1024 PLC_DEFAULT_STRING_SIZE: int = 80 MAX_ADS_S...
MIT License
marqeta/marqeta-python
marqeta/resources/commando_modes.py
CommandoModesCollection.__call__
python
def __call__(self, token): return CommandoModesContext(token, self.client)
Special case call made with token :param token: commandomodes token :return: CommandoModesContext object
https://github.com/marqeta/marqeta-python/blob/66fa690eb910825c510a391720b0fe717fac0234/marqeta/resources/commando_modes.py#L24-L30
from marqeta.resources.collection import Collection from marqeta.response_models.commando_mode_response import CommandoModeResponse from marqeta.response_models.commando_mode_transition_response import CommandoModeTransitionResponse class CommandoModesCollection(object): _endpoint = 'commandomodes' def __init__...
MIT License
simplejwt/django-rest-framework-simplejwt
rest_framework_simplejwt/tokens.py
BlacklistMixin.blacklist
python
def blacklist(self): jti = self.payload[api_settings.JTI_CLAIM] exp = self.payload['exp'] token, _ = OutstandingToken.objects.get_or_create( jti=jti, defaults={ 'token': str(self), 'expires_at': datetime_from_epo...
Ensures this token is included in the outstanding token list and adds it to the blacklist.
https://github.com/simplejwt/django-rest-framework-simplejwt/blob/2003a24276f334c5e1d1b03c91d5343c0d3376bf/rest_framework_simplejwt/tokens.py#L218-L235
from datetime import timedelta from uuid import uuid4 from django.conf import settings from django.utils.translation import gettext_lazy as _ from django.utils.module_loading import import_string from .exceptions import TokenBackendError, TokenError from .settings import api_settings from .token_blacklist.models import...
MIT License
rbuffat/pyepw
pyepw/epw.py
DesignCondition.unkown_field
python
def unkown_field(self): return self._unkown_field
Get unkown_field. Returns: str: the value of `unkown_field` or None if not set
https://github.com/rbuffat/pyepw/blob/373d4d3c8386c8d35789f086ac5f6018c2711745/pyepw/epw.py#L945-L952
from collections import OrderedDict import re class Location(object): _internal_name = "LOCATION" field_count = 9 def __init__(self): self._city = None self._state_province_region = None self._country = None self._source = None self._wmo = None self._latitude ...
Apache License 2.0
vagrawal/deepsphinx
deepsphinx/attention.py
BahdanauAttentionCutoff.__init__
python
def __init__(self, num_units, memory, memory_sequence_length=None, normalize=False, score_mask_value=float('-inf'), name='BahdanauAttention'): def probability_fn_cutoff(scores, previous_alignments): ...
Construct the Attention mechanism. Args: num_units: The depth of the query mechanism. memory: The memory to query; usually the output of an RNN encoder. This tensor should be shaped `[batch_size, max_time, ...]`. memory_sequence_length (optional): Sequence lengths for ...
https://github.com/vagrawal/deepsphinx/blob/5fa7a2e3f22a69d956cc4866a40f73fcdecb14e2/deepsphinx/attention.py#L25-L94
import tensorflow as tf from tensorflow.python.layers.core import Dense from tensorflow.python.ops.rnn_cell_impl import _zero_state_tensors from deepsphinx.utils import FLAGS class BahdanauAttentionCutoff(tf.contrib.seq2seq.BahdanauAttention.__base__):
MIT License
santinic/pampy
pampy/pampy.py
match
python
def match(var, *args, default=NoDefault, strict=True): if len(args) % 2 != 0: raise MatchError("Every guard must have an action.") if default is NoDefault and strict is False: default = False pairs = list(pairwise(args)) patterns = [patt for (patt, action) in pairs] for patt, action ...
Match `var` against a number of potential patterns. Example usage: ``` match(x, 3, "this matches the number 3", int, "matches any integer", (str, int), lambda a, b: "a tuple (a, b) you can use in a function", [1, 2, _], "any list of 3 element...
https://github.com/santinic/pampy/blob/665c6b88bca00a0b1a9a744ebd0764dcdecafab4/pampy/pampy.py#L260-L305
from collections.abc import ( Iterable, Mapping, Callable as ACallable, ) from itertools import zip_longest from enum import Enum from typing import ( Any, Generic, TypeVar, Tuple, List, Pattern as RegexPattern, Callable, ) import inspect from pampy.helpers import ( Underscor...
MIT License
pegase745/sublime-flowtype
flowtype/commands/add_pragma.py
FlowtypeAddPragma.is_enabled
python
def is_enabled(self): content = self.get_content() no_pragma = "// @flow" not in content and "/* @flow */" not in content return is_js_source(self.view) and no_pragma
Enable the command only on Javascript files and has flow pragma.
https://github.com/pegase745/sublime-flowtype/blob/d1f95f22fb698029d09771dfe0959eb2d7f0c722/flowtype/commands/add_pragma.py#L11-L16
from ..logger import Logger from .base import BaseCommand from ..helpers import is_js_source logger = Logger() class FlowtypeAddPragma(BaseCommand):
MIT License
openstack/tempest-lib
tempest_lib/services/compute/aggregates_client.py
AggregatesClient.show_aggregate
python
def show_aggregate(self, aggregate_id): resp, body = self.get("os-aggregates/%s" % aggregate_id) body = json.loads(body) self.validate_response(schema.get_aggregate, resp, body) return rest_client.ResponseBody(resp, body)
Get details of the given aggregate.
https://github.com/openstack/tempest-lib/blob/023426894a4f72d906ed6f79c55ed7152a732b44/tempest_lib/services/compute/aggregates_client.py#L32-L37
from oslo_serialization import jsonutils as json from tempest_lib.api_schema.response.compute.v2_1 import aggregates as schema from tempest_lib.common import rest_client from tempest_lib import exceptions as lib_exc class AggregatesClient(rest_client.RestClient): def list_aggregates(self): resp, body = self...
Apache License 2.0
airesearch-in-th/kora
kora/kaggle.py
ls
python
def ls(dataset): cmd = 'kaggle datasets files -v '+dataset return _show_csv(getoutput(cmd))
List all files for this dataset name
https://github.com/airesearch-in-th/kora/blob/dcf3cc4dec0caa91ffbee7e8942a57a433ab099f/kora/kaggle.py#L33-L36
import os import pandas as pd from io import StringIO from subprocess import getoutput from IPython import get_ipython import kora.data_table assert os.path.exists('/content/drive'), "You need to mount the drive first" assert os.path.exists('/content/drive/My Drive/kaggle.json'), "You need to create API token and...
MIT License
pyviz-dev/nbsite
examples/sites/holoviews/holoviews/streams.py
Stream.add_subscriber
python
def add_subscriber(self, subscriber, precedence=0): if not callable(subscriber): raise TypeError('Subscriber must be a callable.') self._subscribers.append((precedence, subscriber))
Register a callable subscriber to this stream which will be invoked either when event is called or when this stream is passed to the trigger classmethod. Precedence allows the subscriber ordering to be controlled. Users should only add subscribers with precedence between zero an...
https://github.com/pyviz-dev/nbsite/blob/7a4752e6ed6a3b0c3698473a6dd3a71ff9ba2acb/examples/sites/holoviews/holoviews/streams.py#L232-L246
import uuid import math import param import numpy as np from numbers import Number from collections import defaultdict from .core import util from contextlib import contextmanager @contextmanager def triggering_streams(streams): for stream in streams: stream._triggering = True try: yield exc...
BSD 3-Clause New or Revised License
salesforce/pomgen
crawl/workspace.py
Workspace.filter_artifact_producing_packages
python
def filter_artifact_producing_packages(self, packages): art_defs = [self.parse_maven_artifact_def(p) for p in packages] return [art_def.bazel_package for art_def in art_defs if art_def.pom_generation_mode.produces_artifact]
Given a list of packages, returns those that are actually producing a Maven artifact. This is based on the pom_generation_mode specified in the BUILD.pom file.
https://github.com/salesforce/pomgen/blob/4fb427c95c9dc35bfcf47f921e85d6be3876ef6c/crawl/workspace.py#L108-L117
from common import logger from crawl import artifactprocessor from crawl import bazel from crawl import buildpom from crawl import dependency from crawl import dependencymd class Workspace: def __init__(self, repo_root_path, excluded_dependency_paths, source_exclusions, maven_ins...
BSD 3-Clause New or Revised License
lithium876/controll_remote_access_trojan
pyinstaller/PyInstaller/depend/dylib.py
mac_set_relative_dylib_deps
python
def mac_set_relative_dylib_deps(libname, distname): from PyInstaller.lib.macholib import util from PyInstaller.lib.macholib.MachO import MachO if os.path.basename(libname) in _BOOTLOADER_FNAMES: return parent_dir = '' if os.path.dirname(distname): parent_level = len(os.path.dirname(d...
On Mac OS X set relative paths to dynamic library dependencies of `libname`. Relative paths allow to avoid using environment variable DYLD_LIBRARY_PATH. There are known some issues with DYLD_LIBRARY_PATH. Relative paths is more flexible mechanism. Current location of dependend libraries is derived...
https://github.com/lithium876/controll_remote_access_trojan/blob/7ba48b51d98723e0dd0bca7d0e2586d422f78419/pyinstaller/PyInstaller/depend/dylib.py#L177-L242
__all__ = ['exclude_list', 'include_list', 'include_library'] import os import re from PyInstaller import is_win, is_unix, is_aix, is_darwin from PyInstaller.compat import set import PyInstaller.log as logging logger = logging.getLogger('PyInstaller.build.dylib') _BOOTLOADER_FNAMES = set(['run', 'run_d', 'runw', 'runw_...
Apache License 2.0
weasyl/weasyl
libweasyl/libweasyl/cache.py
ThreadCacheProxy.get_multi
python
def get_multi(self, keys): d = self._dict to_fetch = [] ret = [] for key in keys: ret.append(d.get(key, NO_VALUE)) if ret[-1] is NO_VALUE: to_fetch.append((key, len(ret) - 1)) if not to_fetch: return ret keys_to_fetch, i...
Proxy a ``get_multi`` call. This works like :py:meth:`.get`, except *keys* is a list of keys, and the result is a list of values. Parameters: keys: A list of :term:`native string` objects. Returns: list: The values corresponding to the *keys*.
https://github.com/weasyl/weasyl/blob/80c86942c6f20a815086e2895fdad51d3aa77eed/libweasyl/libweasyl/cache.py#L89-L116
import json import threading import dogpile.cache import dogpile.cache.backends.memcached import pylibmc from dogpile.cache.api import CachedValue, NO_VALUE from dogpile.cache.proxy import ProxyBackend from dogpile.cache import make_region region = make_region() class ThreadCacheProxy(ProxyBackend): _local = thread...
Apache License 2.0
dapr/python-sdk
dapr/clients/grpc/client.py
DaprGrpcClient.wait
python
def wait(self, timeout_s: float): host_port_str = self._address.split(":") host_port = (host_port_str[0], int(host_port_str[1])) start = time.time() while True: with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: s.settimeout(timeout_s) ...
Waits for sidecar to be available within the timeout. It checks if sidecar socket is available within the given timeout. The example gets a secret from secret store: from dapr.clients import DaprClient with DaprClient() as d: d.wait(1000) # waits for 1 second....
https://github.com/dapr/python-sdk/blob/3ac8416559338dffb04b900d4ebdd201a2672960/dapr/clients/grpc/client.py#L791-L821
import time import socket import grpc from grpc import ( UnaryUnaryClientInterceptor, UnaryStreamClientInterceptor, StreamUnaryClientInterceptor, StreamStreamClientInterceptor ) from dapr.clients.grpc._state import StateOptions, StateItem from typing import Dict, Optional, Union, Sequence, List from...
MIT License
google/deluca
deluca/lung/envs/_generalized_stitched_sim_open_loop.py
loop_over_loader
python
def loop_over_loader(model_optimState_lrMult_loss, X_Y, optim, rollout, scheduler): X_batch, y_batch = X_Y model, optim_state, lr_mult, loss = model_optimState_lrMult_loss loss, grad = jax.value_and_grad(map_rollout_over_batch)(model, (X_batch, y_batch), ...
rollout has signature (model, data) -> loss where data.shape = (2, N) X_batch.shape = Y_batch.shape = (num_batches, batch_size, N=29) lrMult is the multiplier for the scheduler
https://github.com/google/deluca/blob/9fdcb9b382cae2ff9d8c7600469d2c6f1a128d1c/deluca/lung/envs/_generalized_stitched_sim_open_loop.py#L295-L310
from functools import partial from absl import logging from typing import Dict, Any import time import os import jax import jax.numpy as jnp import flax.linen as nn import optax import copy from flax.metrics import tensorboard import deluca.core from deluca.lung.core import LungEnv from deluca.lung.utils.data.transform...
Apache License 2.0
pyansys/pyaedt
pyaedt/siwave.py
Siwave.project_path
python
def project_path(self): return os.path.normpath(self.oSiwave.GetProjectDirectory())
Project path. Returns ------- str Full absolute path for the project.
https://github.com/pyansys/pyaedt/blob/817c7d706a2d10942470ccac959645e16e9ea971/pyaedt/siwave.py#L159-L168
from __future__ import absolute_import from .generic.general_methods import aedt_exception_handler import os import sys import pkgutil import time from .misc import list_installed_ansysem from pyaedt import is_ironpython, _pythonver if is_ironpython: import clr _com = "pythonnet" import System elif os.nam...
MIT License
iterative/dvc
dvc/fs/base.py
BaseFileSystem.walk_files
python
def walk_files(self, path_info, **kwargs): raise NotImplementedError
Return a generator with `PathInfo`s to all the files. Optional kwargs: prefix (bool): If true `path_info` will be treated as a prefix rather than directory path.
https://github.com/iterative/dvc/blob/3a100382bc5d50a4f1243b1c5d894bb5d7058dbf/dvc/fs/base.py#L169-L176
import contextlib import logging import os from concurrent.futures import ThreadPoolExecutor, as_completed from functools import partialmethod from multiprocessing import cpu_count from typing import Any, ClassVar, Dict, FrozenSet, Optional from tqdm.utils import CallbackIOWrapper from dvc.exceptions import DvcExceptio...
Apache License 2.0
riotgames/cloud-inquisitor
backend/cloud_inquisitor/utils.py
to_camelcase
python
def to_camelcase(inStr): return re.sub('_([a-z])', lambda x: x.group(1).upper(), inStr)
Converts a string from snake_case to camelCase >>> to_camelcase('convert_to_camel_case') 'convertToCamelCase' Args: inStr (str): String to convert Returns: String formatted as camelCase
https://github.com/riotgames/cloud-inquisitor/blob/29a26c705381fdba3538b4efedb25b9e09b387ed/backend/cloud_inquisitor/utils.py#L380-L392
import binascii import hashlib import json import logging import os import random import re import string import time import zlib from base64 import b64decode from collections import namedtuple from copy import deepcopy from datetime import datetime from difflib import Differ from functools import wraps import boto3.se...
Apache License 2.0
harpribot/deep-summarization
models/simple.py
Simple._train_batch
python
def _train_batch(self, review, summary): feed_dict = {self.enc_inp[t]: review[t] for t in range(self.seq_length)} feed_dict.update({self.labels[t]: summary[t] for t in range(self.seq_length)}) _, loss_t = self.sess.run([self.train_op, self.loss], feed_dict) return loss_t
Train a batch of the data :param review: The input review data (X) shape[seq_length x batch_length] :param summary: The target tip data (Y) shape[seq_length x batch_length] :return: None
https://github.com/harpribot/deep-summarization/blob/9b3bb1daae11a1db2386dbe4a71848714e6127f8/models/simple.py#L225-L239
import tensorflow as tf from models.sequenceNet import NeuralNet from abc import abstractmethod, ABCMeta import cPickle as Pickle import numpy as np import random from helpers.data2tensor import Mapper class Simple(NeuralNet): __metaclass__ = ABCMeta def __init__(self, review_summary_file, checkpointer, attenti...
MIT License
cartus/dcgcn
sockeye/config.py
Config.__add_frozen
python
def __add_frozen(self): setattr(self, "_frozen", False) for attr, val in self.__dict__.items(): if isinstance(val, Config): val.__add_frozen()
Adds _frozen attribute to this instance and all its child configurations.
https://github.com/cartus/dcgcn/blob/af91fc787e0aed3ef20e143c2deba70c3c5f309a/sockeye/config.py#L90-L97
import copy import inspect import yaml class TaggedYamlObjectMetaclass(yaml.YAMLObjectMetaclass): def __init__(cls, name, bases, kwds): cls.yaml_tag = "!" + name new_kwds = {} new_kwds.update(kwds) new_kwds['yaml_tag'] = "!" + name super().__init__(name, bases, new_kwds) clas...
MIT License
tcalmant/ipopo
pelix/http/basic.py
_RequestHandler.log_request
python
def log_request(self, code="-", size="-"): self._service.log(logging.DEBUG, '"%s" %s', self.requestline, code)
Logs a request to the server
https://github.com/tcalmant/ipopo/blob/1d4b81207e67890dfccc8f562336c7104f194c17/pelix/http/basic.py#L322-L326
import logging import socket import threading import traceback try: from http.server import HTTPServer from http.server import BaseHTTPRequestHandler from socketserver import ThreadingMixIn, TCPServer except ImportError: from BaseHTTPServer import HTTPServer from BaseHTTPServer import BaseHTTPReques...
Apache License 2.0
mrod5/pyturb
src/pyturb/combustion/combustion_thermodynamics.py
Combustion.reactants_dictionary
python
def reactants_dictionary(self): return self._reactants_dictionary
Reactants dictionary [gas_species]: moles
https://github.com/mrod5/pyturb/blob/08b4016528fc50733fff58d967d1000bf1e634c9/src/pyturb/combustion/combustion_thermodynamics.py#L90-L94
from pyturb.gas_models.thermo_properties import ThermoProperties from pyturb.gas_models.perfect_ideal_gas import PerfectIdealGas from pyturb.gas_models.semiperfect_ideal_gas import SemiperfectIdealGas import numpy as np import warnings oxidizers = ['Air', 'O', 'O2', 'O3', 'O2(L)', 'O3(L)'] fuels = ['hydrocarbon', 'C8H1...
MIT License