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 |
|---|---|---|---|---|---|---|---|---|
mcs07/chemdataextractor | chemdataextractor/reader/markup.py | LxmlReader._make_tree | python | def _make_tree(self, fstring):
pass | Read a string into an lxml elementtree. | https://github.com/mcs07/chemdataextractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/reader/markup.py#L200-L202 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import logging
from abc import abstractmethod, ABCMeta
from collections import defaultdict
from lxml import etree
from lxml.etree import XMLParser
from lxml.html import HT... | MIT License |
thehappydinoa/ashssdk | lambda/awscli/customizations/s3/subcommands.py | CommandArchitecture.create_instructions | python | def create_instructions(self):
if self.needs_filegenerator():
self.instructions.append('file_generator')
if self.parameters.get('filters'):
self.instructions.append('filters')
if self.cmd == 'sync':
self.instructions.append('comparator')
... | This function creates the instructions based on the command name and
extra parameters. Note that all commands must have an s3_handler
instruction in the instructions and must be at the end of the
instruction list because it sends the request to S3 and does not
yield anything. | https://github.com/thehappydinoa/ashssdk/blob/d251a08ba6c35d81cf41b3267db666b08e875515/lambda/awscli/customizations/s3/subcommands.py#L882-L897 | import os
import logging
import sys
from botocore.client import Config
from dateutil.parser import parse
from dateutil.tz import tzlocal
from awscli.compat import six
from awscli.compat import queue
from awscli.customizations.commands import BasicCommand
from awscli.customizations.s3.comparator import Comparator
from a... | MIT License |
aspose-words-cloud/aspose-words-cloud-python | asposewordscloud/models/document_entry.py | DocumentEntry.import_format_mode | python | def import_format_mode(self, import_format_mode):
self._import_format_mode = import_format_mode | Sets the import_format_mode of this DocumentEntry.
Gets or sets the option that controls formatting will be used: appended or destination document. Can be KeepSourceFormatting or UseDestinationStyles. # noqa: E501
:param import_format_mode: The import_format_mode of this DocumentEntry. # noqa: E501
... | https://github.com/aspose-words-cloud/aspose-words-cloud-python/blob/abf8fccfed40aa2b09c6cdcaf3f2723e1f412d85/asposewordscloud/models/document_entry.py#L101-L109 | import pprint
import re
import datetime
import six
import json
class DocumentEntry(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 t... | MIT License |
pegasystems/building-bridges | bridges/database/mongo.py | create_survey | python | def create_survey(title: str,
hide_votes: bool,
is_anonymous: bool,
question_author_name_field_visible: bool,
limit_question_characters_enabled: bool,
limit_question_characters: int,
results_secret: str, admin_se... | Create new survey in db | https://github.com/pegasystems/building-bridges/blob/1e972290e95d2dd3078401ee2193df47d90f3d6e/bridges/database/mongo.py#L77-L106 | from urllib.parse import quote_plus
import logging
from typing import List
from dacite import from_dict
from dacite.exceptions import (
DaciteFieldError,
ForwardReferenceError,
MissingValueError,
UnexpectedDataError,
WrongTypeError,
)
from pymongo import MongoClient
from pymongo.errors import Connec... | MIT License |
ivannz/cplxmodule | cplxmodule/cplx.py | convnd_quick | python | def convnd_quick(conv, input, weight, stride=1,
padding=0, dilation=1):
n_out = int(weight.shape[0])
ww = torch.cat([weight.real, weight.imag], dim=0)
wr = conv(input.real, ww, None, stride, padding, dilation, 1)
wi = conv(input.imag, ww, None, stride, padding, dilation, 1)
rwr, iwr... | r"""Applies a complex convolution transformation to the complex data
:math:`y = x \ast W + b` using two calls to `conv` at the cost of extra
concatenation and slicing. | https://github.com/ivannz/cplxmodule/blob/d5fc89496ca4ea1f0a589a6d36c7ea2d4a8c9ef6/cplxmodule/cplx.py#L697-L711 | import warnings
from copy import deepcopy
import torch
import torch.nn.functional as F
from math import sqrt
from .utils import complex_view, fix_dim
class Cplx(object):
__slots__ = ("__real", "__imag")
def __new__(cls, real, imag=None):
if isinstance(real, cls):
return real
if isins... | MIT License |
y-chan/atomicswap-qt | atomicswap/address.py | base_decode | python | def base_decode(v: Union[bytes, str], length: Optional[int], base: int) -> Optional[bytes]:
v = to_bytes(v, "ascii")
if base not in (58, 43):
raise ValueError("not supported base: {}".format(base))
chars = __b58chars
if base == 43:
chars = __b43chars
long_value = 0
for (i, c) in ... | decode v into a string of len bytes. | https://github.com/y-chan/atomicswap-qt/blob/5bab6d301177aaf7487236597f75efb1172e6450/atomicswap/address.py#L85-L116 | from typing import Union, Tuple, Optional
import hashlib
from .coind import Coind
__b58chars = b"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"
assert len(__b58chars) == 58
__b43chars = b"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ$*+-./:"
assert len(__b43chars) == 43
class PrivkeyDecodeError(Exception):
pass... | MIT License |
jessamynsmith/twitterbot | twitter_bot/twitter_bot.py | TwitterBot.tokenize | python | def tokenize(self, message, max_length, mentions=None):
mention_text = ''
mention_length = 0
if mentions:
formatted_mentions = ['@{0}'.format(mention) for mention in mentions]
mention_text = " ".join(formatted_mentions)
message = '{0} {1}'.format(mention_text,... | Tokenize a message into a list of messages of no more than max_length, including mentions
in each message
:param message: Message to be sent
:param max_length: Maximum allowed length for each resulting message
:param mentions: List of usernames to mention in each message
:return: | https://github.com/jessamynsmith/twitterbot/blob/124308a38d8ad31db0dae0e1ec7a367b5df0a6d6/twitter_bot/twitter_bot.py#L76-L121 | from __future__ import absolute_import
import logging
from twitter import Twitter, TwitterHTTPError
from twitter.oauth import OAuth
from .settings import SettingsError
logging.basicConfig(filename='logs/twitter_bot.log',
filemode='a',
format='%(asctime)s %(name)s %(levelname)s %(... | MIT License |
darkdarkfruit/python-weed | weed/util.py | WeedAssignKeyExtended.update_full_urls | python | def update_full_urls(self):
self['full_url'] = 'http://' + self['url']
self['full_publicUrl'] = 'http://' + self['publicUrl']
self['fid_full_url'] = urllib.parse.urljoin(self['full_url'], self['fid'])
self['fid_full_publicUrl'] = urllib.parse.urljoin(self['full_publicUrl'], self['fid'])
... | update "full_url" and "full_publicUrl" | https://github.com/darkdarkfruit/python-weed/blob/32722b9aa3143116970a993dad690835c9cd415b/weed/util.py#L82-L93 | import json
import urllib.parse
from dataclasses import dataclass
from enum import Enum
import requests
from weed.conf import g_logger
class WeedAssignKey(dict):
def __init__(self, json_of_weed_response=None):
self['fid'] = ''
self['count'] = 0
self['url'] = ''
self['publicUrl'] = ''... | MIT License |
gretelai/gretel-python-client | src/gretel_client/config.py | _get_config_path | python | def _get_config_path() -> Path:
from_env = os.getenv(GRETEL_CONFIG_FILE)
if from_env:
return Path(from_env)
return Path().home() / f".{GRETEL}" / "config.json" | Returns the path to the system's Gretel config | https://github.com/gretelai/gretel-python-client/blob/ccae575bbd9014a6364382270a93fbf0911048d5/src/gretel_client/config.py#L164-L169 | from __future__ import annotations
import json
import logging
import os
from enum import Enum
from pathlib import Path
from typing import Optional, Type, TypeVar, Union
from urllib3.util import Retry
from gretel_client.rest.api.projects_api import ProjectsApi
from gretel_client.rest.api_client import ApiClient
from gre... | Apache License 2.0 |
ninthdevilhaunster/arknightsautohelper | vendor/penguin_client/penguin_client/models/zone.py | Zone.zone_id | python | def zone_id(self, zone_id):
self._zone_id = zone_id | Sets the zone_id of this Zone.
:param zone_id: The zone_id of this Zone. # noqa: E501
:type: str | https://github.com/ninthdevilhaunster/arknightsautohelper/blob/d24b4e22a73b333c1acc152556566efad4e94c04/vendor/penguin_client/penguin_client/models/zone.py#L206-L214 | import pprint
import re
import six
class Zone(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.
... | MIT License |
pydata/sparse | sparse/_coo/common.py | nanprod | python | def nanprod(x, axis=None, keepdims=False, dtype=None, out=None):
assert out is None
x = asCOO(x)
return nanreduce(x, np.multiply, axis=axis, keepdims=keepdims, dtype=dtype) | Performs a product operation along the given axes, skipping ``NaN`` values.
Uses all axes by default.
Parameters
----------
x : SparseArray
The array to perform the reduction on.
axis : Union[int, Iterable[int]], optional
The axes along which to multiply. Uses all axes by default.
... | https://github.com/pydata/sparse/blob/0b7dfeb35cc5894fe36ed1742704acbb37c0c54e/sparse/_coo/common.py#L498-L526 | from functools import reduce
import operator
import warnings
from collections.abc import Iterable
import numpy as np
import scipy.sparse
import numba
from .._sparse_array import SparseArray
from .._utils import (
isscalar,
is_unsigned_dtype,
normalize_axis,
check_zero_fill_value,
check_consistent_fi... | BSD 3-Clause New or Revised License |
peterdsharpe/aerosandbox | aerosandbox/library/aerodynamics/unsteady.py | pitching_through_transverse_gust | python | def pitching_through_transverse_gust(
reduced_time: np.ndarray,
gust_velocity_profile: Callable[[float], float],
plate_velocity: float,
angle_of_attack: Union[Callable[[float], float], float],
chord: float = 1
):
gust_lift = calculate_lift_due_to_transverse_gust(reduced_tim... | This function calculates the lift as a function of time of a flat plate pitching
about its midchord through an arbitrary transverse gust. It combines Kussner's gust response with
wagners pitch response as well as added mass.
The following physics are accounted for
1) Vorticity shed from the traili... | https://github.com/peterdsharpe/aerosandbox/blob/8fbf9449cba2f02e14424690ba2e34b438f21c69/aerosandbox/library/aerodynamics/unsteady.py#L289-L326 | import matplotlib.pyplot as plt
import aerosandbox.numpy as np
from typing import Union, Callable
from scipy.integrate import quad
def main():
time = np.linspace(0, 10, 100)
wing_velocity = 2
chord = 2
reduced_time = calculate_reduced_time(time, wing_velocity, chord)
fig, ax1 = plt.subplots(dp... | MIT License |
chaffelson/whoville | whoville/cloudbreak/models/aws_encryption.py | AwsEncryption.type | python | def type(self, type):
self._type = type | Sets the type of this AwsEncryption.
encryption type for vm (DEFAULT|CUSTOM|NONE)
:param type: The type of this AwsEncryption.
:type: str | https://github.com/chaffelson/whoville/blob/f71fda629c9fd50d0a482120165ea5abcc754522/whoville/cloudbreak/models/aws_encryption.py#L68-L77 | from pprint import pformat
from six import iteritems
import re
class AwsEncryption(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... | Apache License 2.0 |
ionelmc/python-hunter | src/hunter/event.py | Event.detach | python | def detach(self, value_filter=None):
event = Event.__new__(Event)
event.__dict__['code'] = self.code
event.__dict__['filename'] = self.filename
event.__dict__['fullsource'] = self.fullsource
event.__dict__['function'] = self.function
event.__dict__['lineno'] = self.lineno... | Return a copy of the event with references to live objects (like the frame) removed. You should use this if you
want to store or use the event outside the handler.
You should use this if you want to avoid memory leaks or side-effects when storing the events.
Args:
value_filter:
... | https://github.com/ionelmc/python-hunter/blob/e14bbfe28a11bfe8e65a91fd65831c72b2269cef/src/hunter/event.py#L125-L177 | from __future__ import absolute_import
import linecache
import tokenize
from functools import partial
from os.path import basename
from os.path import exists
from os.path import splitext
from threading import current_thread
from .const import SITE_PACKAGES_PATHS
from .const import SYS_PREFIX_PATHS
from .util import CYT... | BSD 2-Clause Simplified License |
frank-qlu/recruit | 招聘爬虫/zlzpView/static/zlzpView/venv/Lib/site-packages/numpy/core/defchararray.py | encode | python | def encode(a, encoding=None, errors=None):
return _to_string_or_unicode_array(
_vec_string(a, object_, 'encode', _clean_args(encoding, errors))) | Calls `str.encode` element-wise.
The set of available codecs comes from the Python standard library,
and may be extended at runtime. For more information, see the codecs
module.
Parameters
----------
a : array_like of str or unicode
encoding : str, optional
The name of an encoding
... | https://github.com/frank-qlu/recruit/blob/0875fb1d2cfb581aaa8abc7a97880c0ce5bf6147/招聘爬虫/zlzpView/static/zlzpView/venv/Lib/site-packages/numpy/core/defchararray.py#L568-L600 | from __future__ import division, absolute_import, print_function
import functools
import sys
from .numerictypes import string_, unicode_, integer, object_, bool_, character
from .numeric import ndarray, compare_chararrays
from .numeric import array as narray
from numpy.core.multiarray import _vec_string
from numpy.core... | Apache License 2.0 |
didix21/mdutils | mdutils/fileutils/fileutils.py | MarkDownFile.rewrite_all_file | python | def rewrite_all_file(self, data):
with open(self.file_name, 'w', encoding='utf-8') as self.file:
self.file.write(data) | Rewrite all the data of a Markdown file by ``data``.
:param str data: is a string containing all the data that is written in the markdown file. | https://github.com/didix21/mdutils/blob/09e531b486563e01f4890a0c68633bb246d44b4c/mdutils/fileutils/fileutils.py#L26-L31 | class MarkDownFile(object):
def __init__(self, name=''):
if name:
self.file_name = name if name.endswith('.md') else name + '.md'
self.file = open(self.file_name, 'w+', encoding='UTF-8')
self.file.close() | MIT License |
gandalf15/hx711 | HX711_Python3/hx711.py | HX711.set_data_filter | python | def set_data_filter(self, data_filter):
if callable(data_filter):
self._data_filter = data_filter
else:
raise TypeError('Parameter "data_filter" must be a function. '
'Received: {}'.format(data_filter)) | set_data_filter method sets data filter that is passed as an argument.
Args:
data_filter(data_filter): Data filter that takes list of int numbers and
returns a list of filtered int numbers.
Raises:
TypeError: if filter is not a function. | https://github.com/gandalf15/hx711/blob/4faae5525ced1d08e51c95728f47ac0b8864c56f/HX711_Python3/hx711.py#L243-L258 | import statistics as stat
import time
import RPi.GPIO as GPIO
class HX711:
def __init__(self,
dout_pin,
pd_sck_pin,
gain_channel_A=128,
select_channel='A'):
if (isinstance(dout_pin, int)):
if (isinstance(pd_sck_pin, int)):
... | BSD 3-Clause New or Revised License |
jamescurtin/demo-cookiecutter-flask | my_flask_app/public/views.py | register | python | def register():
form = RegisterForm(request.form)
if form.validate_on_submit():
User.create(
username=form.username.data,
email=form.email.data,
password=form.password.data,
active=True,
)
flash("Thank you for registering. You can now log i... | Register new user. | https://github.com/jamescurtin/demo-cookiecutter-flask/blob/11decb79ea62c8d10d3141ba7333db85390d4ebf/my_flask_app/public/views.py#L56-L70 | from flask import (
Blueprint,
current_app,
flash,
redirect,
render_template,
request,
url_for,
)
from flask_login import login_required, login_user, logout_user
from my_flask_app.extensions import login_manager
from my_flask_app.public.forms import LoginForm
from my_flask_app.user.forms imp... | MIT License |
andrewtavis/causeinfer | src/causeinfer/data/download_utils.py | get_download_paths | python | def get_download_paths(file_path, file_directory="files", file_name="file"):
if file_path is None:
directory_path = os.path.join(os.getcwd() + "/" + file_directory)
file_path = os.path.join(directory_path + "/" + file_name)
else:
directory_path = file_path.split("/")[0]
file_path... | Derives paths for a file folder and a file.
Parameters
----------
path : str
A user specified path that the data should go to
file_directory : str (default=files)
A user specified directory.
file_name : str (default=file)
The name to call the file. | https://github.com/andrewtavis/causeinfer/blob/19cb098e162f4b711f2681bad21f303e8dc65db7/src/causeinfer/data/download_utils.py#L67-L89 | import os
import urllib
import zipfile
import requests
def download_file(url: str, output_path: str, zip_file=False):
print("Attempting to download file to '{}'...".format(output_path))
headers = {
"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_5) AppleWebKit/537.36 (KHTML, like Gecko) Chro... | BSD 3-Clause New or Revised License |
vector-ai/vectorhub | vectorhub/encoders/text/sentence_transformers/sentence_auto_transformers.py | SentenceTransformer2Vec.get_list_of_urls | python | def get_list_of_urls(self):
return self.urls | Return list of URLS. | https://github.com/vector-ai/vectorhub/blob/17c2f342cef2ff7bcc02c8f3914e79ad92071a9e/vectorhub/encoders/text/sentence_transformers/sentence_auto_transformers.py#L73-L77 | import warnings
from typing import List
from datetime import date
from ....base import catch_vector_errors
from ....doc_utils import ModelDefinition
from ....import_utils import *
from ....models_dict import MODEL_REQUIREMENTS
from ..base import BaseText2Vec
is_all_dependency_installed(MODEL_REQUIREMENTS['encoders-text... | Apache License 2.0 |
benvanwerkhoven/kernel_tuner | kernel_tuner/opencl.py | OpenCLFunctions.run_kernel | python | def run_kernel(self, func, gpu_args, threads, grid):
global_size = (grid[0]*threads[0], grid[1]*threads[1], grid[2]*threads[2])
local_size = threads
event = func(self.queue, global_size, local_size, *gpu_args)
event.wait() | runs the OpenCL kernel passed as 'func'
:param func: An OpenCL Kernel
:type func: pyopencl.Kernel
:param gpu_args: A list of arguments to the kernel, order should match the
order in the code. Allowed values are either variables in global memory
or single values passed b... | https://github.com/benvanwerkhoven/kernel_tuner/blob/1fb183b7719ddb4e211428231e7936c3194f1433/kernel_tuner/opencl.py#L171-L193 | from __future__ import print_function
import time
import numpy as np
from kernel_tuner.observers import BenchmarkObserver
try:
import pyopencl as cl
except ImportError:
cl = None
class OpenCLObserver(BenchmarkObserver):
def __init__(self, dev):
self.dev = dev
self.times = []
def after_fi... | Apache License 2.0 |
opendilab/di-star | ctools/pysc2/lib/actions.py | raw_cmd_pt | python | def raw_cmd_pt(action, ability_id, queued, unit_tags, world):
action_cmd = action.action_raw.unit_command
action_cmd.ability_id = ability_id
action_cmd.queue_command = queued
if not isinstance(unit_tags, (tuple, list)):
unit_tags = [unit_tags]
action_cmd.unit_tags.extend(unit_tags)
world.assign_to(actio... | Do a raw command to another unit towards a point. | https://github.com/opendilab/di-star/blob/f12d79403488e7df0498d7b116fc23a67506112b/ctools/pysc2/lib/actions.py#L171-L179 | import collections
import numbers
import enum
import numpy
import six
from ctools.pysc2.lib import point
from s2clientprotocol import spatial_pb2 as sc_spatial
from s2clientprotocol import ui_pb2 as sc_ui
class ActionSpace(enum.Enum):
FEATURES = 1
RGB = 2
RAW = 3
def spatial(action, action_space):... | Apache License 2.0 |
google-research/pyreach | pyreach/internal.py | Timer.calls | python | def calls(self) -> int:
with self._lock:
return self._calls | Return the number of timer calls. | https://github.com/google-research/pyreach/blob/83cac8e235ba1392dcdc6b8d19202c3eff3ad9a6/pyreach/internal.py#L91-L94 | import os
import threading
import time
from typing import Any, Callable, Dict, FrozenSet, List, Optional, Set, TextIO, Tuple
import numpy as np
from pyreach import core
from pyreach.common.python import types_gen
class Timer(object):
def __init__(self,
name: str,
get_time: Callable[[],... | Apache License 2.0 |
packtpublishing/hands-on-deep-learning-architectures-with-python | Chapter03/rbm.py | RBM._gibbs_sampling | python | def _gibbs_sampling(self, v):
v0 = v
prob_h_v0 = self._prob_h_given_v(v0)
vk = v
prob_h_vk = prob_h_v0
for _ in range(self.k):
hk = self._bernoulli_sampling(prob_h_vk)
prob_v_hk = self._prob_v_given_h(hk)
vk = self._bernoulli_sampling(prob_v_hk... | Gibbs sampling
@param v: visible layer
@return: visible vector before Gibbs sampling, conditional probability P(h|v) before Gibbs sampling,
visible vector after Gibbs sampling, conditional probability P(h|v) after Gibbs sampling | https://github.com/packtpublishing/hands-on-deep-learning-architectures-with-python/blob/61ae6aea8618093c7abf44c2fe00b3d1e6e2d3c8/Chapter03/rbm.py#L67-L85 | import numpy as np
import tensorflow as tf
class RBM(object):
def __init__(self, num_v, num_h, batch_size, learning_rate, num_epoch, k=2):
self.num_v = num_v
self.num_h = num_h
self.batch_size = batch_size
self.learning_rate = learning_rate
self.num_epoch = num_epoch
... | MIT License |
dingmyu/hr-nas | utils/optim.py | get_lr_scheduler | python | def get_lr_scheduler(optimizer, FLAGS, last_epoch=-1):
stepwise = FLAGS.get('lr_stepwise', True)
steps_per_epoch = FLAGS._steps_per_epoch
warmup_iterations = FLAGS.get('epoch_warmup', 5) * steps_per_epoch
use_warmup = FLAGS.lr > FLAGS.base_lr
def warmup_wrap(lr_lambda, i):
if use_warmup and ... | Get learning rate scheduler. | https://github.com/dingmyu/hr-nas/blob/003c3b6bd0168751c884b6999ffc8c13b36a39e2/utils/optim.py#L264-L327 | from __future__ import division
import copy
from collections import OrderedDict
import logging
import functools
import importlib
import warnings
import torch
from torch import nn
from utils.rmsprop import RMSprop
from utils.adamw import AdamW
from utils.adam import Adam
def poly_learning_rate(optimizer, base_lr, curr_i... | MIT License |
vertexproject/synapse | synapse/lib/cell.py | CellApi.iterBackupArchive | python | async def iterBackupArchive(self, name):
await self.cell.iterBackupArchive(name, user=self.user)
if False:
yield | Retrieve a backup by name as a compressed stream of bytes.
Note: Compression and streaming will occur from a separate process.
Args:
name (str): The name of the backup to retrieve. | https://github.com/vertexproject/synapse/blob/a9d62ffacd9cc236ac52f92a734deef55c66ecf3/synapse/lib/cell.py#L675-L688 | import os
import ssl
import time
import shutil
import socket
import asyncio
import logging
import tarfile
import argparse
import datetime
import platform
import functools
import contextlib
import multiprocessing
import tornado.web as t_web
import synapse.exc as s_exc
import synapse.common as s_common
import synapse.dae... | Apache License 2.0 |
ourownstory/neural_prophet | neuralprophet/df_utils.py | split_df | python | def split_df(df, n_lags, n_forecasts, valid_p=0.2, inputs_overbleed=True, local_modeling=False):
if isinstance(df, list):
df_list = df.copy()
df_train_list = list()
df_val_list = list()
if local_modeling:
for df in df_list:
df_train, df_val = _split_df(df,... | Splits timeseries df into train and validation sets.
Prevents overbleed of targets. Overbleed of inputs can be configured. In case of global modeling the split could be either local or global.
Args:
df (pd.DataFrame or list of pd.Dataframe): data
n_lags (int): identical to NeuralProhet
... | https://github.com/ourownstory/neural_prophet/blob/8535b8ce7e1e1c9827f20dfb9c47d3550c24f73f/neuralprophet/df_utils.py#L506-L539 | from dataclasses import dataclass
from collections import OrderedDict
import pandas as pd
import numpy as np
import logging
import math
log = logging.getLogger("NP.df_utils")
@dataclass
class ShiftScale:
shift: float = 0.0
scale: float = 1.0
def create_df_list(df):
if isinstance(df, list):
df_list =... | MIT License |
szymonmaszke/torchfunc | torchfunc/performance/layers.py | Inplace.modules | python | def modules(self, module: torch.nn.Module):
yield from self._analyse(module, "modules") | r"""**Look for inplace operation using** `modules()` **method (recursive scanning).**
Yields
------
int
Indices where module is probably `inplace`. | https://github.com/szymonmaszke/torchfunc/blob/92511c9beb2b62bb4e195deb0fa87b450daee61c/torchfunc/performance/layers.py#L193-L201 | import abc
import collections
import sys
import typing
import torch
from .._base import Base
class Depthwise(Base):
def __init__(
self, checkers: typing.Tuple[typing.Callable[[torch.nn.Module], bool]] = None
):
self.checkers: typing.Tuple[typing.Callable] = (
Depthwise.default_checke... | MIT License |
adn-devtech/3dsmax-python-howtos | src/packages/reloadmod/reloadmod/reload.py | non_builtin | python | def non_builtin():
skip = set(
list(sys.builtin_module_names) +
list(filter(lambda k: k.find("importlib") >= 0, sys.modules.keys())) +
FORCE_SKIP)
return set(filter(lambda k: not (k in skip) and not is_builtin(k), sys.modules.keys())) | Return a set of all modules names that are not builtins and not
importlib related. | https://github.com/adn-devtech/3dsmax-python-howtos/blob/b86ef45ef4d8dff373bd1cbfe5c4d5b805687339/src/packages/reloadmod/reloadmod/reload.py#L11-L20 | import sys
import importlib
import inspect
import pymxs
FORCE_SKIP = [] | MIT License |
jjdabr/forecastnet | Pytorch/denseForecastNet.py | ForecastNetDenseModel2.forward | python | def forward(self, input, target, is_training=False):
outputs = torch.zeros((self.out_seq_length, input.shape[0], self.output_dim)).to(self.device)
next_cell_input = input
for i in range(self.out_seq_length):
hidden = F.relu(self.hidden_layer1[i](next_cell_input))
hidden =... | Forward propagation of the dense ForecastNet model
:param input: Input data in the form [input_seq_length, batch_size, input_dim]
:param target: Target data in the form [output_seq_length, batch_size, output_dim]
:param is_training: If true, use target data for training, else use the previous ou... | https://github.com/jjdabr/forecastnet/blob/dc76b95f5136dae95fe868dca76d8d8cd9d43cf4/Pytorch/denseForecastNet.py#L115-L139 | import torch
import torch.nn as nn
import torch.nn.functional as F
class ForecastNetDenseModel(nn.Module):
def __init__(self, input_dim, hidden_dim, output_dim, in_seq_length, out_seq_length, device):
super(ForecastNetDenseModel, self).__init__()
self.input_dim = input_dim
self.hidden_dim = ... | MIT License |
bendangnuksung/mrcnn_serving_ready | inferencing/saved_model_utils.py | resize_image | python | def resize_image(image, min_dim=None, max_dim=None, min_scale=None, mode="square"):
image_dtype = image.dtype
h, w = image.shape[:2]
window = (0, 0, h, w)
scale = 1
padding = [(0, 0), (0, 0), (0, 0)]
crop = None
if mode == "none":
return image, window, scale, padding, crop
if min... | Resizes an image keeping the aspect ratio unchanged.
min_dim: if provided, resizes the image such that it's smaller
dimension == min_dim
max_dim: if provided, ensures that the image longest side doesn't
exceed this value.
min_scale: if provided, ensure that the image is scaled up by at leas... | https://github.com/bendangnuksung/mrcnn_serving_ready/blob/de9cd824e6e3a108dcd6af50a4a377afc3f24d08/inferencing/saved_model_utils.py#L385-L491 | import random
import cv2
import numpy as np
import tensorflow as tf
import scipy
import skimage.color
import skimage.transform
import urllib.request
import shutil
import warnings
COCO_MODEL_URL = "https://github.com/matterport/Mask_RCNN/releases/download/v2.0/mask_rcnn_coco.h5"
def extract_bboxes(mask):
boxes = np.... | MIT License |
chriso/gauged | gauged/bridge.py | SharedLibrary.prototype | python | def prototype(self, name, argtypes, restype=None):
function = self.function(name)
function.argtypes = argtypes
if restype:
function.restype = restype | Define argument / return types for the specified C function | https://github.com/chriso/gauged/blob/cda3bba2f3e92ce2fb4aa92132dcc0e689bf7976/gauged/bridge.py#L31-L36 | import glob
import os
import sys
from ctypes import (POINTER, Structure, cdll, c_int, c_size_t, c_uint32,
c_char_p, c_bool, c_float)
class SharedLibrary(object):
def __init__(self, name, prefix):
self.prefix = prefix
path = os.path.dirname(os.path.realpath(os.path.join(__file__, ... | MIT License |
okpy/ok-client | client/api/assignment.py | Assignment._encrypt_file | python | def _encrypt_file(self, path, key, padding):
def encrypt(data):
if encryption.is_encrypted(data):
try:
data = encryption.decrypt(data, key)
except encryption.InvalidKeyException:
raise ValueError("Attempt to re-encrypt file with... | Encrypt the given file in place with the given key.
This is idempotent but if you try to encrypt the same file with multiple keys it errors. | https://github.com/okpy/ok-client/blob/3c5eca17100eed808023a815654cfe1c95179080/client/api/assignment.py#L194-L207 | import uuid
from datetime import timedelta
import requests
from client import exceptions as ex
from client.sources.common import core
from client.utils import auth, format, encryption
from client.protocols.grading import grade
from client.cli.common import messages
import client
import collections
import glob
import im... | Apache License 2.0 |
hexrd/hexrd | hexrd/crystallography.py | PlaneData.getLatticeOperators | python | def getLatticeOperators(self):
return copy.deepcopy(self.__latVecOps) | gets lattice vector operators as a new (deepcopy) | https://github.com/hexrd/hexrd/blob/90e9b26e5e5091dd5ecf460b3227072e6d90bcd5/hexrd/crystallography.py#L929-L933 | import re
import copy
from math import pi
import numpy as np
import csv
import os
from hexrd import constants
from hexrd.matrixutil import unitVector
from hexrd.rotations import rotMatOfExpMap, mapAngle, applySym, ltypeOfLaueGroup, quatOfLaueGroup
from hexrd.transforms import xfcapi
from hexrd import valunits
fro... | BSD 3-Clause New or Revised License |
waliens/sldc | sldc/logging.py | Logger.info | python | def info(self, msg):
self._log(Logger.INFO, msg) | Logs a information message if the level of verbosity is above or equal INFO
Parameters
----------
msg: string
The message to log | https://github.com/waliens/sldc/blob/b16d28ca223ac686b711ca988f5e76f7cdedbaca/sldc/logging.py#L70-L77 | import os
import threading
from abc import abstractmethod, ABCMeta
__author__ = "Romain Mormont <romainmormont@hotmail.com>"
__version__ = "0.1"
class Logger(object):
SILENT = 0
ERROR = 1
WARNING = 2
INFO = 3
DEBUG = 4
def __init__(self, level, prefix=True, pid=True):
self._level = level... | MIT License |
clericpy/torequests | torequests/main.py | NewExecutorPoolMixin._get_cpu_count | python | def _get_cpu_count(self):
try:
from multiprocessing import cpu_count
return cpu_count()
except Exception as e:
logger.error("_get_cpu_count failed for %s" % e) | Get the cpu count. | https://github.com/clericpy/torequests/blob/e57ce331aa850db45c198dc90b9d01e437384b61/torequests/main.py#L74-L81 | import atexit
from concurrent.futures import (ProcessPoolExecutor, ThreadPoolExecutor,
as_completed)
from concurrent.futures._base import (CANCELLED, CANCELLED_AND_NOTIFIED,
FINISHED, PENDING, RUNNING,
CancelledE... | MIT License |
sfanous/pyecobee | pyecobee/objects/thermostat.py | Thermostat.program | python | def program(self, program):
self._program = program | Sets the program attribute of this Thermostat instance.
:param program: The program value to set for the program
attribute of this Thermostat instance.
:type: Program | https://github.com/sfanous/pyecobee/blob/3d6b4aec3c6bc9b796aa3d3fd6626909ffdbac13/pyecobee/objects/thermostat.py#L603-L612 | from pyecobee.ecobee_object import EcobeeObject
class Thermostat(EcobeeObject):
__slots__ = [
'_identifier',
'_name',
'_thermostat_rev',
'_is_registered',
'_model_number',
'_brand',
'_features',
'_last_modified',
'_thermostat_time',
'_u... | MIT License |
trusted-ai/adversarial-robustness-toolbox | art/estimators/classification/mxnet.py | MXClassifier.save | python | def save(self, filename: str, path: Optional[str] = None) -> None:
if path is None:
full_path = os.path.join(config.ART_DATA_PATH, filename)
else:
full_path = os.path.join(path, filename)
folder = os.path.split(full_path)[0]
if not os.path.exists(folder):
... | Save a model to file in the format specific to the backend framework. For Gluon, only parameters are saved in
file with name `<filename>.params` at the specified path. To load the saved model, the original model code needs
to be run before calling `load_parameters` on the generated Gluon model.
... | https://github.com/trusted-ai/adversarial-robustness-toolbox/blob/564f46f99b3cb0406fe3570919b8e71a4c5bba9d/art/estimators/classification/mxnet.py#L499-L518 | from __future__ import absolute_import, division, print_function, unicode_literals
import logging
import os
from typing import List, Optional, Tuple, Union, TYPE_CHECKING
import numpy as np
import six
from art import config
from art.estimators.mxnet import MXEstimator
from art.estimators.classification.classifier impor... | MIT License |
rlouf/mcx | mcx/distributions/distribution.py | Distribution.sample | python | def sample(
self, rng_key: jnp.ndarray, sample_shape: Union[Tuple[()], Tuple[int]]
) -> jax.numpy.DeviceArray:
pass | Obtain samples from the distribution.
Parameters
----------
rng_key: jnp.ndarray
The pseudo random number generator key to use to draw samples.
sample_shape: Tuple[int]
The number of independant, identically distributed samples to draw
from the distri... | https://github.com/rlouf/mcx/blob/26c316f2911dac86fbc585b66a8652872187f64e/mcx/distributions/distribution.py#L65-L83 | from abc import ABC, abstractmethod
from typing import Dict, Tuple, Union
import jax
from jax import numpy as jnp
from .constraints import Constraint
class Distribution(ABC):
parameters: Dict[str, Constraint]
support: Constraint
@abstractmethod
def __init__(self, *args) -> None:
pass
@abstra... | Apache License 2.0 |
google/fedjax | fedjax/core/models.py | ModelEvaluator.evaluate_per_client_params | python | def evaluate_per_client_params(
self, clients: Iterable[Tuple[federated_data.ClientId,
Iterable[BatchExample], Params]]
) -> Iterator[Tuple[federated_data.ClientId, Dict[str, jnp.ndarray]]]:
yield from self._evaluate_each_client(shared_input=None, clients=clients) | Evaluates batches from each client using per client params.
Args:
clients: Client batches and the per client params.
Yields:
Pairs of the client id and a dictionary of evaluation `Metric` results for
each client. | https://github.com/google/fedjax/blob/24f768c9aa2959f76d91c3e5aa0e513721c903d7/fedjax/core/models.py#L337-L350 | import functools
from typing import Any, Callable, Dict, Iterable, Iterator, Optional, Mapping, Tuple
from fedjax.core import client_datasets
from fedjax.core import dataclasses
from fedjax.core import federated_data
from fedjax.core import for_each_client
from fedjax.core import metrics
from fedjax.core import util
fr... | Apache License 2.0 |
ialbert/bio | biorun/utils.py | gz_write | python | def gz_write(fname, flag='wt'):
stream = gzip.open(fname, flag, compresslevel=3) if fname.endswith(".gz") else open(fname, flag)
return stream | Shortcut to opening gzipped or regular files | https://github.com/ialbert/bio/blob/564a77c8ee92a1791beea56eedf16b722a0c3932/biorun/utils.py#L387-L392 | import gzip
import json
import logging
import os
import shutil
import sys
import tempfile
from io import StringIO
from itertools import *
from os.path import expanduser
import requests
from biorun.libs.sqlitedict import SqliteDict
from tqdm import tqdm
__CURR_DIR = os.path.dirname(__file__)
__TMPL_DIR = os.path.join(__... | MIT License |
aws-solutions/aws-mlops-framework | source/lib/blueprints/byom/lambdas/create_baseline_job/baselines_helper.py | exception_handler | python | def exception_handler(func: Callable[..., Any]) -> Any:
def wrapper_function(*args, **kwargs):
try:
return func(*args, **kwargs)
except Exception as e:
logger.error(f"Error in {func.__name__}: {str(e)}")
raise e
return wrapper_function | Docorator function to handle exceptions
Args:
func (object): function to be decorated
Returns:
func's return value
Raises:
Exception thrown by the decorated function | https://github.com/aws-solutions/aws-mlops-framework/blob/c2315eed90496371ebc6f2c8d259b95bdcfb41f7/source/lib/blueprints/byom/lambdas/create_baseline_job/baselines_helper.py#L23-L45 | from typing import Callable, Any, Dict, List, Optional
import logging
import sagemaker
from sagemaker.model_monitor import DefaultModelMonitor
from sagemaker.model_monitor import ModelQualityMonitor
from sagemaker.model_monitor.dataset_format import DatasetFormat
logger = logging.getLogger(__name__) | Apache License 2.0 |
mitjafelicijan/redis-marshal | redis/connection.py | Connection.pack_command | python | def pack_command(self, *args):
output = []
command = args[0]
if ' ' in command:
args = tuple([Token.get_token(s)
for s in command.split()]) + args[1:]
else:
args = (Token.get_token(command),) + args[1:]
buff = SYM_EMPTY.join(
... | Pack a series of arguments into the Redis protocol | https://github.com/mitjafelicijan/redis-marshal/blob/57c730529e86f803fc489e4d52973fd37fa12d53/redis/connection.py#L633-L664 | from __future__ import with_statement
from distutils.version import StrictVersion
from itertools import chain
import os
import socket
import sys
import threading
import warnings
try:
import ssl
ssl_available = True
except ImportError:
ssl_available = False
from redis._compat import (b, xrange, imap, byte_to... | MIT License |
aotuai/brainframe-qt | brainframe_qt/ui/resources/ui_elements/applications/messaging_application.py | MessagingServer._handle_connection | python | def _handle_connection(self) -> None:
if not self.hasPendingConnections():
return
if self.current_connection is not None:
logging.debug(
f"Received new connection, but we're already handling another: "
f"0x{id(self.current_connection):x}"
... | Called when a new connection is made to the server.
Connects handler functions to the different events that can occur with a socket | https://github.com/aotuai/brainframe-qt/blob/23b47af6b6da448439288624f6b15515e79ee8d0/brainframe_qt/ui/resources/ui_elements/applications/messaging_application.py#L177-L219 | import logging
import typing
from typing import NewType, Dict, Optional
try:
from PyQt5 import sip
except ImportError:
import sip
from PyQt5.QtCore import pyqtSignal, QObject
from PyQt5.QtNetwork import QLocalServer, QLocalSocket, QAbstractSocket
from PyQt5.QtWidgets import QApplication
IntraInstanceMessage = N... | BSD 3-Clause New or Revised License |
diefenbach/django-lfs | lfs/manage/manufacturers/views.py | manufacturer_view | python | def manufacturer_view(request, manufacturer_id, template_name="manage/manufacturers/view.html"):
manufacturer = lfs_get_object_or_404(Manufacturer, pk=manufacturer_id)
if request.method == "POST":
form = ViewForm(instance=manufacturer, data=request.POST)
if form.is_valid():
form.save... | Displays the view data for the manufacturer with passed manufacturer id.
This is used as a part of the whole category form. | https://github.com/diefenbach/django-lfs/blob/3bbcb3453d324c181ec68d11d5d35115a60a2fd5/lfs/manage/manufacturers/views.py#L82-L111 | import json
from django.contrib.auth.decorators import permission_required
from django.urls import reverse
from django.http import HttpResponse
from django.http import HttpResponseRedirect
from django.shortcuts import render
from django.template.loader import render_to_string
from django.utils.translation import ugette... | BSD 3-Clause New or Revised License |
keon/algorithms | algorithms/maths/rsa.py | generate_key | python | def generate_key(k, seed=None):
def modinv(a, m):
b = 1
while not (a * b) % m == 1:
b += 1
return b
def gen_prime(k, seed=None):
def is_prime(num):
if num == 2:
return True
for i in range(2, int(num ** 0.5) + 1):
... | the RSA key generating algorithm
k is the number of bits in n | https://github.com/keon/algorithms/blob/a9e57d459557f0bcd2bad1e8fac302ab72d34fe8/algorithms/maths/rsa.py#L27-L78 | import random | MIT License |
facebookresearch/mtrl | mtrl/agent/components/critic.py | QFunction._make_trunk | python | def _make_trunk(
self,
obs_dim: int,
action_dim: int,
hidden_dim: int,
output_dim: int,
num_layers: int,
multitask_cfg: ConfigType,
) -> ModelType:
if (
"critic_cfg" in multitask_cfg
and multitask_cfg.critic_cfg
and ... | Make the tunk for the Q-function.
Args:
obs_dim (int): size of the observation.
action_dim (int): size of the action vector.
hidden_dim (int): size of the hidden layer of the trunk.
output_dim (int): size of the output.
num_layers (int): number of lay... | https://github.com/facebookresearch/mtrl/blob/184c7d39db21acc505cf7094ed87cd28a1735105/mtrl/agent/components/critic.py#L98-L149 | from typing import List, Tuple
import torch
from torch import nn
from mtrl.agent import utils as agent_utils
from mtrl.agent.components import base as base_component
from mtrl.agent.components import encoder, moe_layer
from mtrl.agent.components.actor import (
check_if_should_use_multi_head_policy,
check_if_sho... | MIT License |
nestauk/nesta | nesta/core/batchables/nih/nih_dedupe/run.py | extract_yearly_funds | python | def extract_yearly_funds(src):
year = get_value(src, 'year_fiscal_funding')
cost_ref = get_value(src, 'cost_total_project')
start_date = get_value(src, 'date_start_project')
end_date = get_value(src, 'date_end_project')
yearly_funds = []
if year is not None:
yearly_funds = [{'year':year,... | Extract yearly funds | https://github.com/nestauk/nesta/blob/f0abf0b19a4b0c6c9799b3afe0bd67310122b705/nesta/core/batchables/nih/nih_dedupe/run.py#L31-L42 | import logging
from nesta.core.luigihacks.elasticsearchplus import ElasticsearchPlus
from nesta.core.orms.orm_utils import load_json_from_pathstub
from collections import Counter
import json
import boto3
import os
import numpy as np
import time
def get_value(obj, key):
try:
return obj[key]
except KeyErr... | MIT License |
jason-ash/pyesg | pyesg/stochastic_process.py | StochasticProcess.standard_deviation | python | def standard_deviation(self, x0: Array, dt: float) -> np.ndarray:
return self.diffusion(x0=x0) * dt ** 0.5 | Returns the standard deviation of the stochastic process using the Euler
Discretization method | https://github.com/jason-ash/pyesg/blob/95183b3f8e6d37797653bb672a69a1af8a01c1f4/pyesg/stochastic_process.py#L92-L97 | from abc import ABC, abstractmethod
from typing import Dict, Tuple
import numpy as np
from scipy import stats
from scipy.stats._distn_infrastructure import rv_continuous
from pyesg.utils import check_random_state, to_array, Array, RandomState
class StochasticProcess(ABC):
def __init__(self, dim: int = 1, dW: rv_con... | MIT License |
googleads/google-ads-python | google/ads/googleads/v7/services/services/customer_client_service/client.py | CustomerClientServiceClient.get_customer_client | python | def get_customer_client(
self,
request: customer_client_service.GetCustomerClientRequest = None,
*,
resource_name: str = None,
retry: retries.Retry = gapic_v1.method.DEFAULT,
timeout: float = None,
metadata: Sequence[Tuple[str, str]] = (),
) -> customer_client... | r"""Returns the requested client in full detail.
List of thrown errors: `AuthenticationError <>`__
`AuthorizationError <>`__ `HeaderError <>`__
`InternalError <>`__ `QuotaError <>`__ `RequestError <>`__
Args:
request (:class:`google.ads.googleads.v7.services.types.GetCustom... | https://github.com/googleads/google-ads-python/blob/6794993e146abcfe21292677144c66cb546446bc/google/ads/googleads/v7/services/services/customer_client_service/client.py#L363-L447 | from collections import OrderedDict
from distutils import util
import os
import re
from typing import Dict, Optional, Sequence, Tuple, Type, Union
from google.api_core import client_options as client_options_lib
from google.api_core import exceptions
from google.api_core import gapic_v1
from google.api_core impor... | Apache License 2.0 |
geophysics-ubonn/reda | lib/reda/utils/filter_config_types.py | _sort_dd_skips | python | def _sort_dd_skips(configs, dd_indices_all):
config_current_skips = np.abs(configs[:, 1] - configs[:, 0])
if np.all(np.isnan(config_current_skips)):
return {0: []}
available_skips_raw = np.unique(config_current_skips)
available_skips = available_skips_raw[
~np.isnan(available_skips_raw)
... | Given a set of dipole-dipole configurations, sort them according to
their current skip.
Parameters
----------
configs: Nx4 numpy.ndarray
Dipole-Dipole configurations
Returns
-------
dd_configs_sorted: dict
dictionary with the skip as keys, and arrays/lists with indices to
... | https://github.com/geophysics-ubonn/reda/blob/5be52ecb184f45f0eabb23451f039fec3d9537c5/lib/reda/utils/filter_config_types.py#L158-L189 | import numpy as np
import pandas as pd
def _filter_schlumberger(configs):
configs_sorted = np.hstack((
np.sort(configs[:, 0:2], axis=1),
np.sort(configs[:, 2:4], axis=1),
)).astype(int)
MN = configs_sorted[:, 2:4].copy()
MN_unique = np.unique(
MN.view(
MN.dtype.descr ... | MIT License |
dropbox/dropboxbusinessscripts | Sharing/ListSharedFolderMembers.py | SharedFolderLoader.__init__ | python | def __init__(self, context):
self.context = context | :type context: AsMemberContext | https://github.com/dropbox/dropboxbusinessscripts/blob/4f4c32ddd488b29e7fd16a40966761e70a758239/Sharing/ListSharedFolderMembers.py#L343-L347 | import sys
import argparse
from dropbox import Dropbox
from dropbox import DropboxTeam
from dropbox.sharing import GroupMembershipInfo
from dropbox.sharing import InviteeMembershipInfo
from dropbox.sharing import SharedFolderMetadata
from dropbox.sharing import SharedFolderMembers
from dropbox.sharing import UserMember... | Apache License 2.0 |
ebellocchia/py_crypto_hd_wallet | py_crypto_hd_wallet/monero/hd_wallet_monero_keys.py | HdWalletMoneroKeys.__FromMoneroObj | python | def __FromMoneroObj(self,
monero_obj: Monero) -> None:
self.__SetKeyData(HdWalletMoneroKeyTypes.PUB_SPEND, monero_obj.PublicSpendKey().RawCompressed().ToHex())
self.__SetKeyData(HdWalletMoneroKeyTypes.PUB_VIEW, monero_obj.PublicViewKey().RawCompressed().ToHex())
self.__Se... | Create keys from the specified Monero object.
Args:
monero_obj (Monero object): Monero object | https://github.com/ebellocchia/py_crypto_hd_wallet/blob/a48aeb1e7fae9c6cdad781079c39aaae12668a6e/py_crypto_hd_wallet/monero/hd_wallet_monero_keys.py#L124-L143 | from __future__ import annotations
import json
from typing import Dict, Optional
from bip_utils import Monero
from py_crypto_hd_wallet.monero.hd_wallet_monero_enum import HdWalletMoneroKeyTypes
class HdWalletMoneroKeysConst:
KEY_TYPE_TO_DICT_KEY: Dict[HdWalletMoneroKeyTypes, str] = {
HdWalletMoneroKeyTypes.... | MIT License |
man-group/mdf | mdf/builders/basic.py | _get_labels | python | def _get_labels(node, label=None, value=None):
if value is not None:
if label is None:
label = _get_labels(node)[0]
if isinstance(value, (tuple, list, np.ndarray, pa.core.generic.NDFrame, pa.Index)):
if isinstance(label, (tuple, list, np.ndarray, pa.core.generic.NDFrame, pa.I... | returns a list of lables the same length as value, if value is
a list (or of length 1 if value is not a list)
If label is supplied that will be used as the base (eg x.0...x.N)
or if it's a list it will be padded to the correct length and returned. | https://github.com/man-group/mdf/blob/4b2c78084467791ad883c0b4c53832ad70fc96ef/mdf/builders/basic.py#L18-L59 | import numpy as np
import pandas as pa
from ..nodes import MDFNode, MDFEvalNode
from collections import deque, defaultdict
import datetime
import operator
import csv
import matplotlib.pyplot as pp
import sys
import types
if sys.version_info[0] > 2:
basestring = str | MIT License |
erenbalatkan/depthvisualizer | DepthVisualizer/DepthVisualizer.py | Utils.read_kitti_3d_object | python | def read_kitti_3d_object(path, convert_format=True):
objects = []
with open(path, "r") as f:
for line in f:
object_label = line.split(" ")[0]
if not (object_label == "DontCare"):
object_data = [x.rstrip() for x in line.split(" ")]
... | Reads kitti 3d Object Labels
:param path: Path of the label.txt file
:param convert_format: If True, object format will be converted to the DepthVisualizer format which is on
the following form
[Type, Truncation, Occlusion, Observing Angle, 2D Left, 2D Top, 2D Right, 2D Bottom, 3D X, 3D... | https://github.com/erenbalatkan/depthvisualizer/blob/f34ea92bf5ee037520ef16371bca5d055b778238/DepthVisualizer/DepthVisualizer.py#L289-L310 | import glfw
import OpenGL.GL as GL
from OpenGL.GL import shaders
from OpenGL.arrays import vbo
import math
import glm
import ctypes
import time
import numpy as np
from PIL import Image
vertex_shader_source = "#version 330 core\n" + "uniform mat4 view;\n" + "uniform mat4 projection;\n" + "layout (location = ... | MIT License |
edgedb/edgedb | edb/ir/scopetree.py | ScopeTreeNode.mark_as_optional | python | def mark_as_optional(self) -> None:
self.optional_count = 0 | Indicate that this scope is used as an OPTIONAL argument. | https://github.com/edgedb/edgedb/blob/ab26440d9ff775a55f22e3b93e6f345eefc10f61/edb/ir/scopetree.py#L708-L710 | from __future__ import annotations
from typing import *
if TYPE_CHECKING:
from typing_extensions import TypeGuard
import textwrap
import weakref
from edb import errors
from edb.common import context as pctx
from . import pathid
class FenceInfo(NamedTuple):
unnest_fence: bool
factoring_fence: bool
def __... | Apache License 2.0 |
jnez71/lqrrt | lqrrt/planner.py | Planner.kill_update | python | def kill_update(self):
self.killed = True | Raises a flag that will cause an abrupt termination of the update_plan routine. | https://github.com/jnez71/lqrrt/blob/4796ee3fa8d1e658dc23c143f576b38d22642e45/lqrrt/planner.py#L596-L601 | from __future__ import division
import time
import numpy as np
import numpy.linalg as npl
from tree import Tree
from constraints import Constraints
import scipy.interpolate
if int(scipy.__version__.split('.')[1]) < 16:
def interp1d(*args, **kwargs):
kwargs.pop('assume_sorted', None)
return scipy.int... | MIT License |
chirpradio/chirpradio-machine | chirp/stream/looper.py | Looper._trap_exceptions | python | def _trap_exceptions(self, callable_to_wrap):
try:
callable_to_wrap()
except Exception, err:
logging.exception("Swallowed Exception in %s" % self)
self.trapped_exceptions.append((time.time(), err))
if len(self.trapped_exceptions) > self.MAX_TRAPPED_EXCEPTI... | Execute a callable, trapping any raised exceptions.
A list of the last MAX_TRAPPED_EXCEPTIONS exceptions is
maintained. | https://github.com/chirpradio/chirpradio-machine/blob/5977203ca3f561cabb05b5070d0d1227d82b10dc/chirp/stream/looper.py#L38-L52 | import logging
import threading
import time
class Looper(object):
MAX_TRAPPED_EXCEPTIONS = 100
def __init__(self):
self._finished = threading.Event()
self._looped_once = threading.Event()
self._looping = False
self.trapped_exceptions = []
def _begin_looping(self):
pas... | Apache License 2.0 |
uwbmrb/pynmrstar | pynmrstar/entry.py | Entry.from_template | python | def from_template(cls, entry_id, all_tags=False, default_values=False, schema=None) -> 'Entry':
schema = utils.get_schema(schema)
entry = cls(entry_id=entry_id, all_tags=all_tags, default_values=default_values, schema=schema)
entry.source = f"from_template({schema.version})"
return entry | Create an entry that has all of the saveframes and loops from the
schema present. No values will be assigned. Specify the entry
ID when calling this method.
The optional argument 'all_tags' forces all tags to be included
rather than just the mandatory tags.
The optional argumen... | https://github.com/uwbmrb/pynmrstar/blob/c6e3cdccb4aa44dfbc3b4e984837a6bcde3cf171/pynmrstar/entry.py#L371-L387 | import hashlib
import json
import logging
import warnings
from io import StringIO
from typing import TextIO, BinaryIO, Union, List, Optional, Dict, Any, Tuple
from pynmrstar import definitions, utils, loop as loop_mod, parser as parser_mod, saveframe as saveframe_mod
from pynmrstar._internal import _json_serialize, _in... | MIT License |
hazyresearch/fonduer | src/fonduer/candidates/mentions.py | MentionExtractor.apply | python | def apply(
self,
docs: Collection[Document],
clear: bool = True,
parallelism: Optional[int] = None,
progress_bar: bool = True,
) -> None:
super().apply(
docs, clear=clear, parallelism=parallelism, progress_bar=progress_bar
) | Run the MentionExtractor.
:Example: To extract mentions from a set of training documents using
4 cores::
mention_extractor.apply(train_docs, parallelism=4)
:param docs: Set of documents to extract from.
:param clear: Whether or not to clear the existing Mentions
... | https://github.com/hazyresearch/fonduer/blob/c9fd6b91998cd708ab95aeee3dfaf47b9e549ffd/src/fonduer/candidates/mentions.py#L426-L451 | import logging
import re
from builtins import map, range
from typing import Any, Collection, Dict, Iterable, Iterator, List, Optional, Set, Union
from sqlalchemy.orm import Session
from fonduer.candidates.matchers import _Matcher
from fonduer.candidates.models import Candidate, Mention
from fonduer.candidates.models.ca... | MIT License |
mrknow/filmkodi | plugin.video.fanfilm/resources/lib/libraries/f4mproxy/F4mProxy.py | Server.get_request | python | def get_request(self):
self.socket.settimeout(5.0)
result = None
while result is None:
try:
result = self.socket.accept()
except socket.timeout:
pass
result[0].settimeout(1000)
return result | Get the request and client address from the socket. | https://github.com/mrknow/filmkodi/blob/0162cde9ae25ddbf4a69330948714833ff2f78c9/plugin.video.fanfilm/resources/lib/libraries/f4mproxy/F4mProxy.py#L298-L308 | import base64
import re
import time
import urllib
import urllib2
import sys
import traceback
import socket
from SocketServer import ThreadingMixIn
from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler
from urllib import *
import urlparse
from f4mDownloader import F4MDownloader
from interalSimpleDownloader impor... | Apache License 2.0 |
ryanc414/pytest_commander | pytest_commander/result_tree.py | _ensure_branch | python | def _ensure_branch(
root_branch: BranchNode,
nodeid_fragments: List[nodeid.NodeidFragment],
nodeid_prefix: nodeid.Nodeid,
root_dir: str,
) -> BranchNode:
next_fragment, rest_fragments = nodeid_fragments[0], nodeid_fragments[1:]
if not rest_fragments:
return root_branch
child_nodeid =... | Retrieve the branch node under the given root node that corresponds to the given
chain of collectors. If any branch nodes do not yet exist, they will be
automatically created. | https://github.com/ryanc414/pytest_commander/blob/11681fea458de1761e808684f578e183bddc40ef/pytest_commander/result_tree.py#L285-L310 | import abc
import enum
import logging
import os
import textwrap
from typing import List, Tuple, Dict, Generator, Iterator, Optional, Any, cast, Union
import marshmallow
from marshmallow import fields
import marshmallow_enum
from _pytest import nodes
from pytest_commander import environment
from pytest_commander imp... | MIT License |
zaproxy/zap-api-python | src/zapv2/graphql.py | graphql.import_file | python | def import_file(self, endurl, file, apikey=''):
return six.next(six.itervalues(self.zap._request(self.zap.base + 'graphql/action/importFile/', {'endurl': endurl, 'file': file, 'apikey': apikey}))) | Imports a GraphQL Schema from a File.
This component is optional and therefore the API will only work if it is installed | https://github.com/zaproxy/zap-api-python/blob/5166b67ebd5e2d89b285aa7b9d9d7cfd83b88d31/src/zapv2/graphql.py#L94-L99 | import six
class graphql(object):
def __init__(self, zap):
self.zap = zap
@property
def option_args_type(self):
return six.next(six.itervalues(self.zap._request(self.zap.base + 'graphql/view/optionArgsType/')))
@property
def option_lenient_max_query_depth_enabled(self):
retur... | Apache License 2.0 |
mschulth/rhc | env/Environment.py | Environment.var_plt | python | def var_plt(self, x, y=None, label=None, var=None):
if y is not None:
line = plt.plot(x, y, label=label)
else:
line = plt.plot(x, label=label)
if var is not None:
var = np.log(var + 1e-5)[:, 0]/2
col = line[0]._color
plt.fill_between(np... | Creates a line plot with variances
:param x: the x values for plotting
:param y: the y values for plotting
:param label: the label for the lines
:param var: the variances to plot
:return: the line of the plot | https://github.com/mschulth/rhc/blob/0e9adf74267ad6c2aa8712f46c54791f30d532ab/env/Environment.py#L265-L286 | import numpy as np
import matplotlib.pyplot as plt
from abc import ABC, abstractmethod
import casadi as cas
from gym.spaces import Box
class Environment(ABC):
def __init__(self):
self.a_dim = None
self.s_dim = None
self.o_dim = None
self.a_lim = None
self.s_lim = N... | MIT License |
maniacallabs/bibliopixelanimations | BiblioPixelAnimations/matrix/TicTacToe.py | Tic.available_combos | python | def available_combos(self, player):
return self.available_moves() + self.get_squares(player) | what combos are available? | https://github.com/maniacallabs/bibliopixelanimations/blob/fba81f6b94f5265272a53f462ef013df1ccdb426/BiblioPixelAnimations/matrix/TicTacToe.py#L28-L30 | import random
from bibliopixel.animation.matrix import Matrix
from bibliopixel.colors import COLORS
class Tic:
winning_combos = (
[0, 1, 2], [3, 4, 5], [6, 7, 8],
[0, 3, 6], [1, 4, 7], [2, 5, 8],
[0, 4, 8], [2, 4, 6])
winners = ('X-win', 'Draw', 'O-win')
def __init__(self, squares=[]... | MIT License |
okta/okta-sdk-python | okta/cache/cache.py | Cache.create_key | python | def create_key(self, request):
url_object = urlparse(request)
return url_object.geturl() | A method used to create a unique key for an entry in the cache.
Used with URLs that requests fire at.
Arguments:
request {str} -- The key to use to produce a unique key
Returns:
str -- Unique key based on the input | https://github.com/okta/okta-sdk-python/blob/c86b8fdc4525e84199143c27213c0aebc6b2af8f/okta/cache/cache.py#L75-L88 | from urllib.parse import urlparse
class Cache():
def __init__(self):
pass
def get(self, key):
raise NotImplementedError
def contains(self, key):
raise NotImplementedError
def add(self, key, value):
raise NotImplementedError
def delete(self, key):
raise NotImpl... | Apache License 2.0 |
hyperledger/avalon | sdk/avalon_sdk/work_order/work_order_params.py | WorkOrderParams.set_requester_id | python | def set_requester_id(self, requester_id):
self.params_obj["requesterId"] = requester_id | Set requesterId work order parameter. | https://github.com/hyperledger/avalon/blob/cf762fd08b34cc3ba01aaec0143168c60c35d929/sdk/avalon_sdk/work_order/work_order_params.py#L130-L132 | import json
import logging
import schema_validation.validate as WOcheck
import avalon_crypto_utils.crypto_utility as crypto_utility
import avalon_crypto_utils.worker_encryption as worker_encryption
import avalon_crypto_utils.worker_signing as worker_signing
import avalon_crypto_utils.worker_hash as worker_hash
from err... | Apache License 2.0 |
demisto/demisto-py | demisto_client/demisto_api/models/task_loop.py | TaskLoop.script_id | python | def script_id(self, script_id):
self._script_id = script_id | Sets the script_id of this TaskLoop.
:param script_id: The script_id of this TaskLoop. # noqa: E501
:type: str | https://github.com/demisto/demisto-py/blob/95d29e07693d27c133f7fe6ef9da13e4b6dbf542/demisto_client/demisto_api/models/task_loop.py#L225-L233 | import pprint
import re
import six
from demisto_client.demisto_api.models.advance_arg import AdvanceArg
from demisto_client.demisto_api.models.arg_filter import ArgFilter
class TaskLoop(object):
"""
Attributes:
swagger_types (dict): The key is attribute name
and the value... | Apache License 2.0 |
ericssonresearch/calvin-base | calvin/utilities/confsort.py | Options.dict | python | def dict(self):
optionsdict = {}
for option in self.options:
optionsdict[option.key] = option.value
return optionsdict | Return unstructured dictionary with key, value of options. | https://github.com/ericssonresearch/calvin-base/blob/bc4645c2061c30ca305a660e48dc86e3317f5b6f/calvin/utilities/confsort.py#L40-L47 | from operator import itemgetter, attrgetter, methodcaller
class Options:
def __init__(self):
self.options = []
def insert(self, option):
self.options.append(option)
def __repr__(self):
return repr(self.options) | Apache License 2.0 |
woudt/bunq2ifttt | app/bunq.py | session_request | python | def session_request(method, endpoint, config, data=None, extra_headers=None):
result = request(method, endpoint, config, data, extra_headers)
if isinstance(result, dict) and "Error" in result and result["Error"][0]["error_description"] in ["Insufficient authorisation.", "Insufficient authe... | Send a request, refreshing session keys if needed | https://github.com/woudt/bunq2ifttt/blob/de53ca03743b705c4f5149c756e0fd90d55231ee/app/bunq.py#L312-L320 | import base64
import json
import re
import secrets
import traceback
import requests
from cryptography.exceptions import InvalidSignature
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import hashes, hmac, serialization
from cryptography.hazmat.primitives.asymmetric import p... | MIT License |
psiq/gdsfactory | pp/components/rectangle.py | rectangle | python | def rectangle(
size: Tuple[float, float] = (4.0, 2.0),
layer: Tuple[int, int] = pp.LAYER.WG,
centered: bool = False,
ports_parameters: Dict[str, List[Tuple[float, float]]] = {},
**port_settings
) -> Component:
c = pp.Component()
w, h = size
if centered:
points = [
[-w... | rectangle
Args:
size: (tuple) Width and height of rectangle.
layer: (int, array-like[2], or set) Specific layer(s) to put polygon geometry on.
ports: {direction: [(x_or_y, width), ...]} direction: 'W', 'E', 'N' or 'S'
.. plot::
:include-source:
import pp
c = pp.c.re... | https://github.com/psiq/gdsfactory/blob/34c8ecbed465e8eda0d5116687fd02e95e530f35/pp/components/rectangle.py#L9-L73 | import pp
from pp.component import Component
from typing import Dict, List, Tuple
DIRECTION_TO_ANGLE = {"W": 180, "E": 0, "N": 90, "S": 270}
@pp.autoname | MIT License |
pypa/twine | twine/utils.py | get_userpass_value | python | def get_userpass_value(
cli_value: Optional[str],
config: RepositoryConfig,
key: str,
prompt_strategy: Optional[Callable[[], str]] = None,
) -> Optional[str]:
if cli_value is not None:
logger.info(f"{key} set by command options")
return cli_value
elif config.get(key) is not None:... | Get a credential (e.g. a username or password) from the configuration.
Uses the following rules:
1. If ``cli_value`` is specified, use that.
2. If ``config[key]`` is specified, use that.
3. If ``prompt_strategy`` is specified, use its return value.
4. Otherwise return ``None``
:param cli_valu... | https://github.com/pypa/twine/blob/658037f05898b4dc96113628153aa2691b0dbfa3/twine/utils.py#L213-L270 | import argparse
import collections
import configparser
import functools
import logging
import os
import os.path
import unicodedata
from typing import Any, Callable, DefaultDict, Dict, Optional, Sequence, Union
from urllib.parse import urlparse
from urllib.parse import urlunparse
import requests
import rfc3986
from twin... | Apache License 2.0 |
googleapis/python-bigtable | google/cloud/bigtable/backup.py | Backup.update_expire_time | python | def update_expire_time(self, new_expire_time):
backup_update = table.Backup(
name=self.name, expire_time=_datetime_to_pb_timestamp(new_expire_time),
)
update_mask = field_mask_pb2.FieldMask(paths=["expire_time"])
api = self._instance._client.table_admin_client
api.upd... | Update the expire time of this Backup.
:type new_expire_time: :class:`datetime.datetime`
:param new_expire_time: the new expiration time timestamp | https://github.com/googleapis/python-bigtable/blob/a99bf88417d6aec03923447c70c2752f6bb5c459/google/cloud/bigtable/backup.py#L378-L390 | import re
from google.cloud._helpers import _datetime_to_pb_timestamp
from google.cloud.bigtable_admin_v2 import BigtableTableAdminClient
from google.cloud.bigtable_admin_v2.types import table
from google.cloud.bigtable.encryption_info import EncryptionInfo
from google.cloud.bigtable.policy import Policy
from google.... | Apache License 2.0 |
derkarnold/pylifx | pylifx/networking.py | LifxSocket.recv | python | def recv(self):
while True:
raw_data, addr = self._socket.recvfrom(_RECV_BUFFER_SIZE)
if raw_data == None or len(raw_data) == 0:
raise IOError('disconnected')
try:
return decode(raw_data), addr
except Exception as e:
... | Returns a tuple of ((method, args), addr) | https://github.com/derkarnold/pylifx/blob/ae69511728f5316872d0441608b84d4484c73244/pylifx/networking.py#L101-L112 | from __future__ import absolute_import
from socket import socket, AF_INET, SOCK_DGRAM, SOCK_STREAM, SOL_SOCKET, SO_REUSEADDR, SO_BROADCAST, error
from .packet import encode, decode
from re import match
from thread import start_new_thread
from netifaces import ifaddresses, interfaces
_RECV_BUFFER_SIZE = 1024
_LIFX_PROTO... | BSD 2-Clause Simplified License |
autodesk/aomi | aomi/model/context.py | ensure_backend | python | def ensure_backend(resource, backend, backends, opt, managed=True):
existing_mount = find_backend(resource.mount, backends)
if not existing_mount:
new_mount = backend(resource, opt, managed=managed)
backends.append(new_mount)
return new_mount
return existing_mount | Ensure the backend for a resource is properly in context | https://github.com/autodesk/aomi/blob/84da2dfb0424837adf9c4ddc1aa352e942bb7a4a/aomi/model/context.py#L59-L67 | import sys
import inspect
import logging
from future.utils import iteritems
from aomi.helpers import normalize_vault_path
import aomi.exceptions as aomi_excep
from aomi.model.resource import Resource, Mount, Secret, Auth, AuditLog
from aomi.model.aws import AWS
from aomi.model.auth import Policy, UserPass, LDAP
fr... | MIT License |
ayoolaolafenwa/pixellib | pixellib/torchbackend/instance/modeling/backbone/regnet.py | gap2d | python | def gap2d():
return nn.AdaptiveAvgPool2d((1, 1)) | Helper for building a global average pooling layer. | https://github.com/ayoolaolafenwa/pixellib/blob/ae56003c416a98780141a1170c9d888fe9a31317/pixellib/torchbackend/instance/modeling/backbone/regnet.py#L38-L40 | import numpy as np
from torch import nn
from pixellib.torchbackend.instance.layers.blocks import CNNBlockBase
from pixellib.torchbackend.instance.layers.batch_norm import get_norm
from pixellib.torchbackend.instance.layers.shape_spec import ShapeSpec
from .backbone import Backbone
__all__ = [
"AnyNet",
"RegNet"... | MIT License |
bitmovin/bitmovin-api-sdk-python | bitmovin_api_sdk/models/analytics_error_detail.py | AnalyticsErrorDetail.message | python | def message(self):
return self._message | Gets the message of this AnalyticsErrorDetail.
Error message
:return: The message of this AnalyticsErrorDetail.
:rtype: string_types | https://github.com/bitmovin/bitmovin-api-sdk-python/blob/79dd938804197151af7cbe5501c7ec1d97872c15/bitmovin_api_sdk/models/analytics_error_detail.py#L192-L201 | from enum import Enum
from datetime import datetime
from six import string_types, iteritems
from bitmovin_api_sdk.common.poscheck import poscheck_model
from bitmovin_api_sdk.models.analytics_error_data import AnalyticsErrorData
import pprint
import six
class AnalyticsErrorDetail(object):
@poscheck_model
def __i... | MIT License |
skelsec/pydesfire | pyDESFire/pydesfire.py | Desfire.ChangeKeySettings | python | def ChangeKeySettings(self, newKeySettings):
self.logger.debug('Changing key settings to %s' %('|'.join(a.name for a in newKeySettings),))
params = int2hex(calc_key_settings(newKeySettings))
cmd = DESFireCommand.DF_INS_CHANGE_KEY_SETTINGS.value
raw_data = self.communicate(cmd) | Changes key settings for the key that was used to authenticate with in the current session.
Authentication is ALWAYS needed to call this function.
Args:
newKeySettings (list) : A list with DESFireKeySettings enum value
Returns:
None | https://github.com/skelsec/pydesfire/blob/59b67eef5d3170a295eccc20cd01de5ecf3bcf52/pyDESFire/pydesfire.py#L853-L866 | from enum import Enum
import logging
import struct
from .readers import PCSCReader, DummyReader
from .cards import SmartCardTypes, SmartCard
from .utils import *
from Crypto.Cipher import DES, DES3, AES
from Crypto import Random
_logger = logging.getLogger(__name__)
class DESFireCommand(Enum):
DF_INS_AUTHENTICATE_LEGA... | MIT License |
epswartz/block_distortion | block_distortion/effects.py | animate_image | python | def animate_image(
image: np.ndarray,
frames: int=100,
splits: int=2000,
progress: bool=False
):
X_SIZE, Y_SIZE, CHANNELS = image.shape
init_box = Box(0, 0, X_SIZE, Y_SIZE)
images = []
r = range(frames)
if progress:
r = track(r, "Rendering Frames")
for i in r:
gri... | Produce a gif with distortion effects. This function returns a list of frames, which you can write with write_frames_to_gif().
Args:
image: (W,H,3) or (W,H,4) np.ndarray
frames: Number of frames in output gif
splits: Number of times to split the image (higher makes a "smoother" looking imag... | https://github.com/epswartz/block_distortion/blob/22cefc3bb9e1be32278d74957e7798b13db2258b/block_distortion/effects.py#L14-L46 | import numpy as np
from .splitting import *
from .utils import *
from .Box import Box
from .coloring import *
from rich.progress import track
from rich.console import Console
ORIENTATION = "alternating" | MIT License |
tlc-pack/tenset | python/tvm/topi/generic/search.py | schedule_argwhere | python | def schedule_argwhere(outs):
return _default_schedule(outs, False) | Schedule for argwhere operator.
Parameters
----------
outs: Array of Tensor
The computation graph description of argwhere.
Returns
-------
s: Schedule
The computation schedule for the op. | https://github.com/tlc-pack/tenset/blob/3f7ed0291df47331d43f43a064fffacdc2914b47/python/tvm/topi/generic/search.py#L23-L36 | from __future__ import absolute_import as _abs
from .default import default_schedule as _default_schedule | Apache License 2.0 |
dell/ansible-isilon | dellemc_ansible/isilon/library/dellemc_isilon_nfs.py | IsilonNfsExport._check_remove_clients | python | def _check_remove_clients(self, nfs_export):
playbook_client_dict = self._create_current_client_dict_from_playbook()
current_client_dict = self._create_current_client_dict()
mod_flag = False
mod_flag1 = False
if playbook_client_dict['clients']:
for client in playbook_... | Check if clients are to be removed from NFS export | https://github.com/dell/ansible-isilon/blob/9e98faf2344083e0c74467cb2de39f9b8a3145f9/dellemc_ansible/isilon/library/dellemc_isilon_nfs.py#L517-L566 | from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'
}
DOCUMENTATION = r'''
---
module: dellemc_isilon_nfs
version_added: '2.7'
s... | Apache License 2.0 |
appliedgeometry/poissongeometry | poisson/utils.py | validate_dimension | python | def validate_dimension(dim):
if not isinstance(dim, int):
raise DimensionError(F"{dim} is not int")
if dim < 2:
raise DimensionError(F"{dim} < 2")
else:
return dim | This method check if the dimension variable is valid for the this class | https://github.com/appliedgeometry/poissongeometry/blob/98bea08d9127f1bda45bc04b88d73b05dd480c65/poisson/utils.py#L30-L38 | from __future__ import unicode_literals
from poisson.errors import DimensionError | MIT License |
mwaskom/seaborn | seaborn/rcmod.py | set_theme | python | def set_theme(context="notebook", style="darkgrid", palette="deep",
font="sans-serif", font_scale=1, color_codes=True, rc=None):
set_context(context, font_scale)
set_style(style, rc={"font.family": font})
set_palette(palette, color_codes=color_codes)
if rc is not None:
mpl.rcParams... | Set aspects of the visual theme for all matplotlib and seaborn plots.
This function changes the global defaults for all plots using the
:ref:`matplotlib rcParams system <matplotlib:matplotlib-rcparams>`.
The themeing is decomposed into several distinct sets of parameter values.
The options are illustr... | https://github.com/mwaskom/seaborn/blob/59e61256a704e709007685c9840595b53221e367/seaborn/rcmod.py#L83-L124 | import warnings
import functools
import matplotlib as mpl
from cycler import cycler
from . import palettes
__all__ = ["set_theme", "set", "reset_defaults", "reset_orig",
"axes_style", "set_style", "plotting_context", "set_context",
"set_palette"]
_style_keys = [
"axes.facecolor",
"axes.edg... | BSD 3-Clause New or Revised License |
sanderslab/magellanmapper | magmap/cv/stack_detect.py | StackDetector.detect_sub_roi_from_data | python | def detect_sub_roi_from_data(cls, coord, sub_roi_slices, offset):
return cls.detect_sub_roi(
coord, offset, cls.last_coord,
cls.denoise_max_shape, cls.exclude_border, cls.img[sub_roi_slices],
cls.channel, coloc=cls.coloc) | Perform 3D blob detection within a sub-ROI using data stored
as class attributes for forked multiprocessing.
Args:
coord (Tuple[int]): Coordinate of the sub-ROI in the order z,y,x.
sub_roi_slices (Tuple[slice]): Sequence of slices within
:attr:``img`` defining th... | https://github.com/sanderslab/magellanmapper/blob/35e910035217edab799d4fbaa61e39931527a354/magmap/cv/stack_detect.py#L55-L74 | from enum import Enum
import os
from time import time
import numpy as np
import pandas as pd
from magmap.cv import chunking, colocalizer, detector, verifier
from magmap.io import cli, df_io, importer, libmag, naming
from magmap.plot import plot_3d
from magmap.settings import config, roi_prof
_logger = config.logger.get... | BSD 3-Clause New or Revised License |
osmr/imgclsmob | tensorflow_/tensorflowcv/models/mnasnet.py | mnas_init_block | python | def mnas_init_block(x,
in_channels,
out_channels,
mid_channels,
use_skip,
training,
data_format,
name="mnas_init_block"):
x = conv3x3_block(
x=x,
in_channels=in... | MnasNet specific initial block.
Parameters:
----------
x : Tensor
Input tensor.
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
mid_channels : int
Number of middle channels.
use_skip : bool
Whether to use skip... | https://github.com/osmr/imgclsmob/blob/ea5f784eea865ce830f3f97c5c1d1f6491d9cbb2/tensorflow_/tensorflowcv/models/mnasnet.py#L114-L165 | __all__ = ['MnasNet', 'mnasnet_b1', 'mnasnet_a1', 'mnasnet_small']
import os
import tensorflow as tf
from .common import is_channels_first, flatten, conv1x1_block, conv3x3_block, dwconv3x3_block, dwconv5x5_block, se_block, round_channels
def dws_exp_se_res_unit(x,
in_channels,
... | MIT License |
tomplus/kubernetes_asyncio | kubernetes_asyncio/client/models/v1_deployment_condition.py | V1DeploymentCondition.last_transition_time | python | def last_transition_time(self, last_transition_time):
self._last_transition_time = last_transition_time | Sets the last_transition_time of this V1DeploymentCondition.
Last time the condition transitioned from one status to another. # noqa: E501
:param last_transition_time: The last_transition_time of this V1DeploymentCondition. # noqa: E501
:type: datetime | https://github.com/tomplus/kubernetes_asyncio/blob/22bf0f4ec775b920abc9cee86bb38abcfc57506d/kubernetes_asyncio/client/models/v1_deployment_condition.py#L90-L99 | import pprint
import re
import six
from kubernetes_asyncio.client.configuration import Configuration
class V1DeploymentCondition(object):
"""
Attributes:
openapi_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is at... | Apache License 2.0 |
laserkelvin/pyspectools | pyspectools/mmw/mmw_analysis.py | sec_deriv_peak_detection | python | def sec_deriv_peak_detection(df_group, threshold=5, window_size=25, magnet_thres=0.5, **kwargs):
signal = df_group["Field OFF"].to_numpy()
frequency = df_group["Frequency"].to_numpy()
corr_signal = cross_correlate_lorentzian(signal, window_size)
indices = peakutils.indexes(corr_signal, thres=threshold, ... | Function designed to take advantage of split-combine-apply techniques to analyze
concatenated spectra, or a single spectrum. The spectrum is cross-correlated with
a window corresponding to a second-derivative Lorentzian line shape, with the parameters
corresponding to the actual downward facing peak such th... | https://github.com/laserkelvin/pyspectools/blob/f8f38136d362c061cefc71fede56848829467666/pyspectools/mmw/mmw_analysis.py#L172-L223 | from typing import List
from pathlib import Path
import numpy as np
import lmfit
import pandas as pd
import os
import peakutils
from matplotlib import pyplot as plt
from . import fft_routines
from . import interpolation
from ..lineshapes import sec_deriv_lorentzian
def parse_data(filepath):
settings = dict()
in... | MIT License |
rspivak/slimit | src/slimit/parser.py | Parser.p_array_literal_2 | python | def p_array_literal_2(self, p):
items = p[2]
if len(p) == 6:
items.extend(p[4])
p[0] = ast.Array(items=items) | array_literal : LBRACKET element_list RBRACKET
| LBRACKET element_list COMMA elision_opt RBRACKET | https://github.com/rspivak/slimit/blob/3533eba9ad5b39f3a015ae6269670022ab310847/src/slimit/parser.py#L250-L257 | __author__ = 'Ruslan Spivak <ruslan.spivak@gmail.com>'
import ply.yacc
from slimit import ast
from slimit.lexer import Lexer
try:
from slimit import lextab, yacctab
except ImportError:
lextab, yacctab = 'lextab', 'yacctab'
class Parser(object):
def __init__(self, lex_optimize=True, lextab=lextab,
... | MIT License |
luna-klatzer/openhiven.py | openhivenpy/gateway/messagebroker.py | EventConsumer._cleanup | python | def _cleanup(self) -> None:
del self.workers
self.workers = {}
del self._tasks
self._tasks = {} | Removes all workers and removes the data that still exists | https://github.com/luna-klatzer/openhiven.py/blob/9184d6a77bde0ee3847dcb9ea7d399217a36c95d/openhivenpy/gateway/messagebroker.py#L442-L448 | from __future__ import annotations
import asyncio
import logging
from typing import Optional, List, Coroutine, Tuple, Dict
from typing import TYPE_CHECKING
from .. import utils
from ..base_types import HivenObject
if TYPE_CHECKING:
from .. import HivenClient
from ..exceptions import EventConsumerLoopError, Work... | MIT License |
longcw/faster_rcnn_pytorch | faster_rcnn/datasets/nthu.py | nthu._get_default_path | python | def _get_default_path(self):
return os.path.join(ROOT_DIR, 'data', 'NTHU') | Return the default path where nthu is expected to be installed. | https://github.com/longcw/faster_rcnn_pytorch/blob/d8f842dfa51e067105e6949999277a08daa3d743/faster_rcnn/datasets/nthu.py#L92-L96 | import os
import PIL
import numpy as np
import scipy.sparse
import subprocess
import cPickle
import math
import glob
from .imdb import imdb
from .imdb import ROOT_DIR
from ..fast_rcnn.config import cfg
class nthu(imdb):
def __init__(self, image_set, nthu_path=None):
imdb.__init__(self, 'nthu_' + image_set)
... | MIT License |
alexa/alexa-apis-for-python | ask-smapi-model/ask_smapi_model/v1/skill/simulations/input.py | Input.__init__ | python | def __init__(self, content=None):
self.__discriminator_value = None
self.content = content | :param content: A string corresponding to the utterance text of what a customer would say to Alexa.
:type content: (optional) str | https://github.com/alexa/alexa-apis-for-python/blob/bfe5e694daaca71bfb1a4199ca8d2514f1cac6c9/ask-smapi-model/ask_smapi_model/v1/skill/simulations/input.py#L44-L53 | import pprint
import re
import six
import typing
from enum import Enum
if typing.TYPE_CHECKING:
from typing import Dict, List, Optional, Union, Any
from datetime import datetime
class Input(object):
deserialized_types = {
'content': 'str'
}
attribute_map = {
'content': 'content'
... | Apache License 2.0 |
boxed/mutmut | mutmut/__init__.py | guess_paths_to_mutate | python | def guess_paths_to_mutate():
this_dir = os.getcwd().split(os.sep)[-1]
if isdir('lib'):
return 'lib'
elif isdir('src'):
return 'src'
elif isdir(this_dir):
return this_dir
elif isdir(this_dir.replace('-', '_')):
return this_dir.replace('-', '_')
elif isdir(this_dir.... | Guess the path to source code to mutate
:rtype: str | https://github.com/boxed/mutmut/blob/cce78241aa116d14c4ae38ecd1b2c84e659126d7/mutmut/__init__.py#L896-L919 | import fnmatch
import itertools
import multiprocessing
import os
import re
import shlex
import subprocess
import sys
from configparser import (
ConfigParser,
NoOptionError,
NoSectionError,
)
from copy import copy as copy_obj
from functools import wraps
from io import (
open,
TextIOBase,
)
from os.pa... | BSD 3-Clause New or Revised License |
deepmind/bsuite | bsuite/experiments/summary_analysis.py | bsuite_radar_plot | python | def bsuite_radar_plot(summary_data: pd.DataFrame,
sweep_vars: Optional[Sequence[str]] = None):
fig = plt.figure(figsize=(8, 8), facecolor='white')
ax = fig.add_subplot(111, polar=True)
try:
ax.set_axis_bgcolor('white')
except AttributeError:
ax.set_facecolor('white')
all_tags = s... | Output a radar plot of bsuite data from bsuite_summary by tag. | https://github.com/deepmind/bsuite/blob/afdeae850b08108d2247a1802567bb7f404d9833/bsuite/experiments/summary_analysis.py#L342-L421 | from typing import Callable, Mapping, NamedTuple, Optional, Sequence, Union
from bsuite.experiments.bandit import analysis as bandit_analysis
from bsuite.experiments.bandit_noise import analysis as bandit_noise_analysis
from bsuite.experiments.bandit_scale import analysis as bandit_scale_analysis
from bsuite.experiment... | Apache License 2.0 |
cfedermann/appraise | appraise/wmt15/models.py | RankingResult.export_to_csv | python | def export_to_csv(self, expand_multi_systems=True):
item = self.item
hit = self.item.hit
values = []
iso639_3_to_name_mapping = {'ces': 'Czech', 'cze': 'Czech',
'deu': 'German', 'ger': 'German', 'eng': 'English',
'spa': 'Spanish', 'fra': 'French', 'fre': 'French',
... | Exports this RankingResult in CSV format. | https://github.com/cfedermann/appraise/blob/2cce477efd5594699d6e0fa58f6312df60e05394/appraise/wmt15/models.py#L604-L709 |
import logging
import uuid
from datetime import datetime
from xml.etree.ElementTree import fromstring, ParseError, tostring
from django.dispatch import receiver
from django.contrib.auth.models import User, Group
from django.core.urlresolvers import reverse
from django.db import models
from django.template import Cont... | BSD 3-Clause New or Revised License |
oarriaga/paz | paz/models/segmentation/unet.py | build_UNET | python | def build_UNET(num_classes, backbone, branch_tensors,
decoder, decoder_filters, activation, name):
inputs, x = backbone.input, backbone.output
if isinstance(backbone.layers[-1], MaxPooling2D):
x = convolution_block(x, 512)
x = convolution_block(x, 512)
for branch, filters in z... | Build UNET with a given ``backbone`` model.
# Arguments
num_classes: Integer used for output number of channels.
backbone: Instantiated backbone model.
branch_tensors: List of tensors from ``backbone`` model
decoder: Function used for upsampling and decoding the output.
deco... | https://github.com/oarriaga/paz/blob/5fcfa78768c3e5b2ee3f58aaf928709f05d750f4/paz/models/segmentation/unet.py#L127-L155 | from tensorflow.keras.layers import Conv2DTranspose, Concatenate, UpSampling2D
from tensorflow.keras.layers import Conv2D, BatchNormalization, Activation
from tensorflow.keras.layers import MaxPooling2D, Input
from tensorflow.keras import Model
from tensorflow.keras.applications import VGG16, VGG19
from tensorflow.kera... | MIT License |
openstack/swift | swift/common/daemon.py | DaemonStrategy.run | python | def run(self, once=False, **kwargs):
self.setup(**kwargs)
try:
self._run(once=once, **kwargs)
except KeyboardInterrupt:
self.logger.notice('User quit')
finally:
self.cleanup()
self.running = False | Daemonize and execute our strategy | https://github.com/openstack/swift/blob/dbd0960aeebedc0487699d3ca2a4d6f21e7ed524/swift/common/daemon.py#L154-L163 | import errno
import os
import sys
import time
import signal
from re import sub
import eventlet.debug
from eventlet.hubs import use_hub
from swift.common import utils
class Daemon(object):
WORKERS_HEALTHCHECK_INTERVAL = 5.0
def __init__(self, conf):
self.conf = conf
self.logger = utils.get_logger... | Apache License 2.0 |
coin3d/pivy | scons/scons-local-1.2.0.d20090919/SCons/Util.py | splitext | python | def splitext(path):
sep = rightmost_separator(path, os.sep)
dot = string.rfind(path, '.')
if dot > sep and not containsOnly(path[dot:], "0123456789."):
return path[:dot],path[dot:]
else:
return path,"" | Same as os.path.splitext() but faster. | https://github.com/coin3d/pivy/blob/a88a54e594977d573747f762823d9a24b10e3b23/scons/scons-local-1.2.0.d20090919/SCons/Util.py#L89-L97 | from __future__ import print_function
__revision__ = "src/engine/SCons/Util.py 4369 2009/09/19 15:58:29 scons"
import copy
import os
import os.path
import re
import string
import sys
import types
from UserDict import UserDict
from UserList import UserList
from UserString import UserString
DictType = dict
Instanc... | ISC License |
eric3911/mini_ssd | object_detection/utils/vrd_evaluation.py | _VRDDetectionEvaluation.add_single_ground_truth_image_info | python | def add_single_ground_truth_image_info(
self, image_key, groundtruth_box_tuples, groundtruth_class_tuples):
if image_key in self._groundtruth_box_tuples:
logging.warn(
'image %s has already been added to the ground truth database.',
image_key)
return
self._groundtruth_box_t... | Adds groundtruth for a single image to be used for evaluation.
Args:
image_key: A unique string/integer identifier for the image.
groundtruth_box_tuples: A numpy array of structures with the shape
[M, 1], representing M tuples, each tuple containing the same number
of named bounding... | https://github.com/eric3911/mini_ssd/blob/6fb6e1bce3ab6e4adb832b37e78325803c7424b6/object_detection/utils/vrd_evaluation.py#L447-L470 | from abc import abstractmethod
import collections
import logging
import numpy as np
from object_detection.core import standard_fields
from object_detection.utils import metrics
from object_detection.utils import object_detection_evaluation
from object_detection.utils import per_image_vrd_evaluation
vrd_box_data_type = ... | MIT License |
dingmyu/hr-nas | common.py | reduce_and_flush_meters | python | def reduce_and_flush_meters(meters, method='avg'):
if not FLAGS.use_distributed:
results = flush_scalar_meters(meters)
else:
results = {}
assert isinstance(meters, dict), "meters should be a dict."
for name in sorted(meters.keys()):
meter = meters[name]
if... | Sync and flush meters. | https://github.com/dingmyu/hr-nas/blob/003c3b6bd0168751c884b6999ffc8c13b36a39e2/common.py#L124-L155 | import copy
import importlib
import logging
import math
import os
import torch
import torch.distributed as dist
from torch.utils.tensorboard import SummaryWriter
from utils import distributed as udist
from utils.model_profiling import model_profiling
from utils.config import FLAGS
from utils.meters import ScalarMeter
f... | MIT License |
srstevenson/nb-clean | noxfile.py | list_source_files | python | def list_source_files() -> List[str]:
paths = [path for path in SOURCES if pathlib.Path(path).is_file()]
paths.extend(
[
os.fspath(path)
for source in SOURCES
for path in pathlib.Path(source).rglob("*.py")
if pathlib.Path(source).is_dir()
]
)
... | Expand directories in SOURCES to constituent files. | https://github.com/srstevenson/nb-clean/blob/58dfdd2d0ed175b3ff80dec73bc1a37c84a9e070/noxfile.py#L12-L23 | import os
import pathlib
from typing import List
import nox
SOURCES = ["noxfile.py", "src", "tests"] | ISC License |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.