content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def embed_tiles_in_json_sprite(tile_list, as_bytes=True, out_file=None): """Make a big rectangle containing the images for a brainsprite. Parameters: ----------- tile_list : list List of 2d square numpy arrays to stick in a mosaic Returns: -------- mosaic : np.ndarray ...
2eca9eb999d69537fac60dfefd0d482576994868
7,915
import re def removeUnicode(text): """ Removes unicode strings like "\u002c" and "x96" """ text = re.sub(r'(\\u[0-9A-Fa-f]+)',r'', text) text = re.sub(r'[^\x00-\x7f]',r'',text) return text
f5c8090329ede82ce51601efa463537bba68b63a
7,916
import scipy def mfcc(tf, n_mfcc, fs, fmin=0.0, fmax=None): """ Extract MFCC vectors Args: tf : single-channel time-frequency domain signal, indexed by 'tf' n_mfcc : number of coefficients fs : sample rate fmin : (default 0) minimal frequency in Hz ...
58769db11aa0633dd846b9d427e6d35a0fff435e
7,917
import logging def transform(fname, metadata=False): """ This function reads a Mission Analysis Orbit file and performs a matrix transformation on it. Currently only from the Mercury Equatorial frame to the Earth Equatorial frame. :param fname: The path to the orbit file. :type fname: str. ...
ce389f74ba35d3c92a94031563b187a7285ccb5b
7,918
import requests import json def query_repository(repo_name, index_uuid, token, display_results=False): """ Display the ids ('subjects') of all items indexed in a repository. :param repo_name: Textual name of repository to query, corresponds to 'name' field in conf file. :param index_name: Name of ind...
8a6b4f90374b90504a375c5d44a6dce6f32fb936
7,919
def power(x1, x2, out=None, where=True, dtype=None): """ First array elements raised to powers from second array, element-wise. Raises each base in `x1` to the positionally-corresponding power in `x2`. Note: Numpy arguments `casting`, `order`, `dtype`, `subok`, `signature`, and `extobj` are ...
ecc265e96c36c47177aa96797d355a55f35114d6
7,920
def _str2bool(s): """文字列からboolへの変換""" return s.lower() in ["true", "t", "yes", "1"]
877340b7926541a5b8f56cb7f1acd5a54e08a987
7,921
import random def _generate_nonce(length=42): """ Generate an alpha numeric string that is unique for each request. Twitter used a 42 character alpha-numeric (case-sensitive) string in the API documentation. However, they note "any approach which produces a relatively random alphanumeric string s...
034c4fee363d47e9af98c0135159f53179d27fdd
7,922
def int_(value): """Validate that the config option is an integer. Automatically also converts strings to ints. """ check_not_templatable(value) if isinstance(value, int): return value if isinstance(value, float): if int(value) == value: return int(value) rai...
f5d5f729a1bbec418f3b270b4e28be2cf9cc7cd6
7,924
def explode(screen): """Convert a string representing a screen display into a list of lists.""" return [list(row) for row in screen.split('\n')]
a43a9d8c830c4a784bb9c3505c62aaf2077bb732
7,925
def basic_info(user, keys): """Prints a table of basic user information""" table = formatting.KeyValueTable(['Title', 'Basic Information']) table.align['Title'] = 'r' table.align['Basic Information'] = 'l' table.add_row(['Id', user.get('id', '-')]) table.add_row(['Username', user.get('username...
805b8e12f531b1c6b31aeca847568cbc1b2e929c
7,927
def iobes_iob(tags): """ IOBES -> IOB """ new_tags = [] for i, tag in enumerate(tags): if tag == 'rel': new_tags.append(tag) elif tag.split('-')[0] == 'B': new_tags.append(tag) elif tag.split('-')[0] == 'I': new_tags.append(tag) eli...
1a2f715edfc37b387944f84c4f149f21a0e86e74
7,928
def draw_handler(canvas): """ Event handler that is responsible for all drawing. It receives "canvas" object and draws the "Pong" table, the "moving" ball and the scores of each "Player". It is also responsible for testing whether the ball touches/collides with the "gutters" or the "paddles". ...
ad9d5be8bbc1eb1b1612c6bfd35cc774bcacbd7a
7,929
def tf_idf(df, vocab): """[summary] https://towardsdatascience.com/natural-language-processing-feature-engineering-using-tf-idf-e8b9d00e7e76 Args: docs ([type]): [description] """ docs = [] for text in df['text'].tolist(): docs += [text] vectorizer = TfidfVectorizer(tokeniz...
ef75e51f1d4b69dcf6a5ab908f56eff8a25852f7
7,930
def get_activation_func(activation): """Turns a string activation function name into a function. """ if isinstance(activation, string_types): # Get the activation function. activation = activation.lower() if activation == "tanh": activation_func = tanh elif activa...
6cb6fccdacf44c3fc3fac242d69a2494459c1318
7,932
def create_schema(hostname='localhost', username=None, password=None, dbname=None, port=None, schema_name=None): """Create test schema.""" cn = create_cn(hostname, password, username, dbname, port) with cn.cursor() as cr: cr.execute('DROP SCHEMA IF EXISTS %s CASCADE' % dbname) ...
ef1b8b77ca1cd88804f0afec9efc24caad3a601d
7,934
def set_color_in_session(intent, session): """ Sets the color in the session and prepares the speech to reply to the user. """ card_title = intent['name'] session_attributes = {} should_end_session = False if 'Color' in intent['slots']: favorite_color = intent['slots']['Color']['va...
4783aa36b18fb723441d99a8ffcdfe4b587d2a45
7,935
def fpath_to_pgn(fpath): """Slices the pgn string from file path. """ return fpath.split('/')[-1].split('.jpeg')[0]
1cc6cad60c5356b6c731947a59998117bf15035a
7,936
def convert_to_constant(num): """ Convert one float argument to Constant, returning the converted object. :param float num: Float number to be converted to Constant :return: Float number converted to a Constant object :rtype: object """ return Constant(name=str(num), units...
111ae55c1446228b23638465c75bd9fa6d3d7043
7,937
def data_zip(data): """ 输入数据,返回一个拼接了子项的列表,如([1,2,3], [4,5,6]) -> [[1,4], [2,5], [3,6]] {"a":[1,2],"b":[3,4]} -> [{"a":1,"b":3}, {"a":2,"b":4}] :param data: 数组 data 元组 (x, y,...) 字典 {"a":data1, "b":data2,...} :return: 列表或数组 """ if isinstance(data, tuple): ...
31dcaa3905a7d062cfe994543df31f293fdc962a
7,938
def _days_in_leap_and_common_years(i_date, f_date): """Return the a tuple with number of days in common and leap years (respectively) between initial and final dates. """ iy = i_date.year fy = f_date.year days_in_leap = 0 days_in_common = 0 if iy == fy: # same year ...
f96b6c26fd8e87a543ffa6b6e7ed66144248d752
7,939
def make_space_kernel(data, background_kernel, trigger_kernel, time, time_cutoff=None, space_cutoff=None): """Produce a kernel object which evaluates the background kernel, and the trigger kernel based on the space locations in the data, always using the fixed time as passed in. :param data: An...
5c84dfb89340e52e57fb0b28464b18b0487601ea
7,940
import torch def get_dim_act_curv(args): """ Helper function to get dimension and activation at every layer. :param args: :return: """ if not args.act: act = lambda x: x else: act = getattr(F, args.act) acts = [act] * (args.num_layers - 1) dims = [args.feat_dim] ...
072a54a3a2060598cbbe0fc89efe0be4b7cdc63f
7,941
def write_charset_executable(mysql_charset_script_name, here): """Write to disk as an executable the file that will be used to issue the MySQL statements that change the character set to UTF-8 -- return the absolute path. """ mysql_charset_script = os.path.join(here, mysql_charset_script_name) if no...
b92ea0e48ccebd267856ababcb714e736fea812c
7,943
import time def readTemperature(file): """ Returns the temperature of the one wire sensor. Pass in the file containing the one wire data (ds18b20+) """ lines = read_temp_raw(file) while lines[0].strip()[-3:] != "YES": time.sleep(0.2) lines = read_temp_raw(file) equals_pos =...
3398f287ae98df4b72ff212cdcad1764a9bbe31b
7,944
def energyAct( grid, deltaE, xA, yA, zA, xB, yB, zB, temp, eList, i, dimensions): """Perform swap or not, based on deltaE value""" kB = 8.617332e-5 # boltzmann constant, w/ ~eV units kTemp = kB * temp if deltaE <= 0: # Swap lowers energy, therefore is favourable, # so perform swap in grid grid = performSwap(...
2380991200c2b3c196b1fea4c4108e82f20a979b
7,946
def lambda_handler(event, context): """ Lambda function that transforms input data and stores inital DB entry Parameters ---------- event: dict, required context: object, required Lambda Context runtime methods and attributes Context doc: https://docs.aws.amazon.com/lambda/latest/dg/python-...
83bba41d28a7b37da6579dfc2641380839f9d785
7,947
def getModCase(s, mod): """Checks the state of the shift and caps lock keys, and switches the case of the s string if needed.""" if bool(mod & KMOD_RSHIFT or mod & KMOD_LSHIFT) ^ bool(mod & KMOD_CAPS): return s.swapcase() else: return s
4faa2963e96786c5495443382585188b3a6ff119
7,948
from pathlib import Path def try_provider(package, provider, domain): """Try using a provider.""" downloaded_file = None data = None apk_name = f'{package}.apk' temp_file = Path(gettempdir()) / apk_name link = find_apk_link(provider, domain) if link: downloaded_file = download_file...
e43a6b18a5783722c148a537f21e501a1f4e5928
7,950
def _get_list(sline): """Takes a list of strings and converts them to floats.""" try: sline2 = convert_to_float(sline) except ValueError: print("sline = %s" % sline) raise SyntaxError('cannot parse %s' % sline) return sline2
2b315b12508638fe603378fdd3127bd814f4313d
7,951
def add_number(partitions, number): """ Adds to the partition provided `number` in all its combinations """ # Add to each list in partitions add 1 prods = partitions.values() nKeys = [(1,) + x for x in partitions.keys()] # apply sum_ones on each partition, and add results to partitions ...
cade1ddbd4002b76fc2652c59fe4f0a9bcdcc9b9
7,952
import colorsys def _color_to_rgb(color, input): """Add some more flexibility to color choices.""" if input == "hls": color = colorsys.hls_to_rgb(*color) elif input == "husl": color = husl.husl_to_rgb(*color) color = tuple(np.clip(color, 0, 1)) elif input == "xkcd": col...
7b3a502eba4a48dbd9b1e44d278aee58eb1ea22c
7,953
def in_days(range_in_days): """ Generate time range strings between start and end date where each range is range_in_days days long :param range_in_days: number of days :return: list of strings with time ranges in the required format """ delta = observation_period_end - observation_period_star...
f9e77eac3fd151923cb14d05d291a0e362bd11b5
7,954
from pathlib import Path from typing import List import re def tags_in_file(path: Path) -> List[str]: """Return all tags in a file.""" matches = re.findall(r'@([a-zA-Z1-9\-]+)', path.read_text()) return matches
1071c22ac79f51697b2ed18896aa1d17568ecb2c
7,955
import torch def pad_to_longest_in_one_batch(batch): """According to the longest item to pad dataset in one batch. Notes: usage of pad_sequence: seq_list = [(L_1, dims), (L_2, dims), ...] item.size() must be (L, dims) return (longest_len, len(seq_list), dims) ...
3892b6002ae0f0cb0b6ce4c29128120a8f63237a
7,956
def create_instance(c_instance): """ Creates and returns the Twister script """ return Twister(c_instance)
acceb844eae8a3c9a8c734e55c4c618f990f1ae0
7,957
from typing import Type from typing import Callable def command_handler(command_type: Type[CommandAPI], *, name: str = None) -> Callable[[CommandHandlerFn], Type[CommandHandler]]: """ Decorator that can be used to construct a CommandHandler from a simple function. ...
1c6634691e366b61043b2c745d43cc2371090200
7,958
def check_ip_in_lists(ip, db_connection, penalties): """ Does an optimized ip lookup with the db_connection. Applies only the maximum penalty. Args: ip (str): ip string db_connection (DBconnector obj) penalties (dict): Contains tor_penalty, vpn_penalty, blacklist_penalty keys with i...
2d6e3615d4b0d9b0fb05e7a0d03708856ffcbfef
7,959
import numpy def scan(fn, sequences=None, outputs_info=None, non_sequences=None, n_steps=None, truncate_gradient=-1, go_backwards=False, mode=None, name=None, options=None, profile=False): """ This function constructs an...
7ac0b7d106bc2e1642827a2e9f79552eb418a918
7,960
def stock_analyst(stock_list): """This function accepts a list of data P and outputs the best day to buy(B) and sell(S) stock. Args: stock_list: expects a list of stocks as a parameter Returns: a string promting to buy stock if one has not bought stock i.e the value of stock is...
bbb3cd664ba0ea366e8ad6fa369ae3259cf52a02
7,961
def is_sync_available(admin_id): """Method to check the synchronization's availability about networks connection. Args: admin_id (str): Admin privileges flag. """ return r_synchronizer.is_sync_available()
712becdc6c9903d41e3d29602bb7dc07987c6867
7,962
import collections def on_second_thought(divider): """sort the characters according to number of times they appears in given text, returns the remaining word as a string """ unsorted_list = list(unsorted_string) # characters occurence determines the order occurence = collections.Counter(un...
1295a67cf1ebce0f79e49566306eba6add1f2e35
7,963
def aiohttp_unused_port(loop, aiohttp_unused_port, socket_enabled): """Return aiohttp_unused_port and allow opening sockets.""" return aiohttp_unused_port
9c5d0c1125a7758be2e07a8f8aca6676429a841a
7,964
def font_variant(name, tokens): """Expand the ``font-variant`` shorthand property. https://www.w3.org/TR/css-fonts-3/#font-variant-prop """ return expand_font_variant(tokens)
8bac3f0610c7951686504fd843c845d124f34ed6
7,966
def with_part_names(*part_names): """Add part names for garage.parts.assemble. Call this when you want to assemble these parts but do not want them to be passed to main. """ return lambda main: ensure_app(main).with_part_names(*part_names)
c62d495c2259139b1a9079697bcf784d12e6f9c2
7,967
def library_view(request): """View for image library.""" if request.user.is_authenticated: the_user = request.user albums = Album.objects.filter(user=the_user) context = {'the_user': the_user, 'albums': albums} return render(request, 'imager_profile/library.html',...
948d239decfacabf5b3bba05e10739c7856db609
7,968
def combine_html_json_pbp(json_df, html_df, game_id, date): """ Join both data sources. First try merging on event id (which is the DataFrame index) if both DataFrames have the same number of rows. If they don't have the same number of rows, merge on: Period', Event, Seconds_Elapsed, p1_ID. :param json...
4f2aa3948fea4f64ac996f4052101daa556d1038
7,969
import json def read_json_file(path): """ Given a line-by-line JSON file, this function converts it to a Python dict and returns all such lines as a list. :param path: the path to the JSON file :returns items: a list of dictionaries read from a JSON file """ items = list() with open(...
15f898faca0dff0ca4b6c73ff31e037d822cf273
7,970
def get_boss_wage2(employee): """ Monadic version. """ return bind3(bind3(unit3(employee), Employee.get_boss), Employee.get_wage)
60524cc219a1c4438d310382aff519ee8ef5a66b
7,971
def keypoint_angle(kp1, kp2): """求两个keypoint的夹角 """ k = [ (kp1.angle - 180) if kp1.angle >= 180 else kp1.angle, (kp2.angle - 180) if kp2.angle >= 180 else kp2.angle ] if k[0] == k[1]: return 0 else: return abs(k[0] - k[1])
3feee667bcf767656da6334727b8d502be41d909
7,972
def get_args_static_distribute_cells(): """ Distribute ranges of cells across workers. :return: list of lists """ pop_names_list = [] gid_lists = [] for pop_name in context.pop_names: count = 0 gids = context.spike_trains[pop_name].keys() while count < len(gids): ...
42862d47533a8662b26c9875e5f62ceebb91ccec
7,973
import torch def le(input, other, *args, **kwargs): """ In ``treetensor``, you can get less-than-or-equal situation of the two tree tensors with :func:`le`. Examples:: >>> import torch >>> import treetensor.torch as ttorch >>> ttorch.le( ... torch.tensor([[1, 2], [3, ...
fa96a544f7f449daf008c6cf9b68f3760de67487
7,974
import numpy def linear_to_srgb(data): """Convert linear color data to sRGB. Acessed from https://entropymine.com/imageworsener/srgbformula Parameters ---------- data: :class:`numpy.ndarray`, required Array of any shape containing linear data to be converted to sRGB. Returns ---...
01eae0f9a34204498aad86e3a0a38337c7ced919
7,975
def circuit_to_dagdependency(circuit): """Build a ``DAGDependency`` object from a ``QuantumCircuit``. Args: circuit (QuantumCircuit): the input circuits. Return: DAGDependency: the DAG representing the input circuit as a dag dependency. """ dagdependency = DAGDependency() dagde...
7356da47f3af1088226af765f83cd43413de0a1f
7,976
def tweets_factory(fixtures_factory): """Factory for tweets from YAML file""" def _tweets_factory(yaml_file): all_fixtures = fixtures_factory(yaml_file) return [t for t in all_fixtures if isinstance(t, TweetBase)] return _tweets_factory
19d6e7ffe57ec071d324d535458c2263496c109d
7,977
def monte_carlo(ds,duration,n,pval,timevar): """ pval: two-tailed pval """ x=0 mc = np.empty([ds.shape[1],ds.shape[2],n]) while x<n: dummy = np.random.randint(0, len(ds[timevar])-duration, size=1) # have to adjust size so total number of points is always the same mc[:,:,x] = ds[i...
040aaf1a6a6813095079262446a2226fec8948ee
7,978
def num_crl(wf_n): """Function computes the autocorrelation function from given vectors\ and the Discrete Fourier transform Args: wf_n(numpy array, complex): Wave function over time Returns: numpy array, complex: The wave function complex over time. numpy array, complex: The au...
fc84cd7184fb04f2725b50439d9b5cfe223e2020
7,979
def resample_time_series(series, period="MS"): """ Resample and interpolate a time series dataframe so we have one row per time period (useful for FFT) Parameters ---------- df: DataFrame Dataframe with date as index col_name: string, Identifying the column we will pull out ...
2e3d2b1cbe4a8a0cc13c33c19fe217364819e31d
7,980
def check_user(user, pw, DB): """ Check if user exists and if password is valid. Return the user's data as a dict or a string with an error message. """ userdata = DB.get(user) if not userdata: log.error("Unknown user: %s", user) return "Unknown user: %s" % user elif userdat...
21e8c56c0f747bd105cec31e1cb5aea348b4af44
7,983
def get_single_response_value(dom_response_list: list, agg_function): """ Get value of a single scenario's response. :param dom_response_list: Single response provided as a list of one term. :param agg_function: Function to aggregate multiple responses. :return: Value of such observation. """ ...
7a7ef4f24a720a4611c48123061886b6bdb9f2f5
7,984
def sharpe_ratio(returns, periods=252): """ Create the Sharpe ratio for the strategy, based on a benchmark of zero (i.e. no risk-free rate information). Args: returns (list, Series) - A pandas Series representing period percentage returns. periods (int....
b06ef19c5512370ff98217f7fb565c25846b697e
7,985
def is_validated(user): """Is this user record validated?""" # An account is "validated" if it has the `validated` field set to True, or # no `validated` field at all (for accounts created before the "account # validation option" was enabled). return user.get("validated", True)
c1ddfc52a62e71a68798dc07e7576a4ae42aa17f
7,986
def current_chart_provider_monthly(): """ API for monthly provider chart """ mytime = dubwebdb.CTimes("%Y-%m", request.args.get('time_start'), request.args.get('time_end')) myids = dubwebdb.Ids(prv_id=sanitize_list(request.args.get('prvid')), team_id=san...
36f67b0323be8fc136175fa4f9fb4819b40ebb94
7,987
def create_round_meander(radius, theta=0, offset=Point()): """ Returns a single period of a meandering path based on radius and angle theta """ deg_to_rad = 2 * pi / 360 r = radius t = theta * deg_to_rad # The calculation to obtain the 'k' coefficient can be found here: # ...
c4379ef8f16486e9cdbd3353c5458a6c9523bb2d
7,988
import pickle def load_config(path): """Loads the config dict from a file at path; returns dict.""" with open(path, "rb") as f: config = pickle.load(f) return config
eb12aed2ebdeebacf3041f3e4880c714f99c052c
7,990
from datetime import datetime def _check_year(clinicaldf: pd.DataFrame, year_col: int, filename: str, allowed_string_values: list = []) -> str: """Check year columns Args: clinicaldf: Clinical dataframe year_col: YEAR column filename: Name of file allowed_strin...
c1630b4196733baa6ef12db2990243b1052d01d5
7,991
def lower_strings(string_list): """ Helper function to return lowercase version of a list of strings. """ return [str(x).lower() for x in string_list]
58dcaccbc0f4ce8f22d80922a3ac5da26d7f42b1
7,992
def AAprime(): """ >> AAprime() aaprime and aprimea """ aprimeA = dot(transpose(ATable), ATable) # Aaprime = dot(ATable1, ATable) return aprimeA
f47d4df43ebcb8348e4a6fd4234b38bd18e92199
7,993
import _pickle import _io def _load_dataset(data_filename_or_set, comm, verbosity): """Loads a DataSet from the data_filename_or_set argument of functions in this module.""" printer = _baseobjs.VerbosityPrinter.create_printer(verbosity, comm) if isinstance(data_filename_or_set, str): if comm is No...
9c3a26a36202b4e8f35c795b7817d3fde8900a0b
7,995
import re def parse_contact_name(row, name_cols, strict=False, type='person'): """Parses a person's name with probablepeople library Concatenates all the contact name columns into a single string and then attempts to parse it into standardized name components and return a subset of the name parts that ar...
315b971344df60d2cbb4f0c4e1d820b37b07ddaf
7,996
def get_peer_addr(ifname): """Return the peer address of given peer interface. None if address not exist or not a peer-to-peer interface. """ for addr in IP.get_addr(label=ifname): attrs = dict(addr.get('attrs', [])) if 'IFA_ADDRESS' in attrs: return attrs['IFA_ADDRESS']
e92906c0c705eb42ec3bedae2959dabcad72f0d2
7,999
def eiffel_artifact_created_event(): """Eiffel artifact created event.""" return { "meta": { "id": "7c2b6c13-8dea-4c99-a337-0490269c374d", "time": 1575981274307, "type": "EiffelArtifactCreatedEvent", "version": "3.0.0", }, "links": [], ...
0ef2e5adadb58b92c94bac42c9880728573b159e
8,000
def _hash(input_data, initVal=0): """ hash() -- hash a variable-length key into a 32-bit value k : the key (the unaligned variable-length array of bytes) len : the length of the key, counting by bytes level : can be any 4-byte value Returns a 32-bit value. Every bit of the key affec...
c4f1b0ee22ca940d360090b965125e71c272ad4c
8,001
import logging def read_config_option(key, expected_type=None, default_value=None): """Read the specified value from the configuration file. Args: key: the name of the key to read from the config file. expected_type: read the config option as the specified type (if specified) default_...
effc94b89dd8b1e0765c71bd4c0c03760715db1d
8,002
from typing import Any import logging def removeKeys(array: dict = None, remove: Any = None) -> dict: """ Removes keys from array by given remove value. :param array: dict[Any: Any] :param remove: Any :return: - sorted_dict - dict[Any: Any] """ if remove is None: remove = [...
1b98821000642c79fbb71a9c0dc7163c4a95fa26
8,004
from trimesh.path.creation import box_outline from trimesh.path.util import concatenate def affine2boxmesh(affines): """ :param affines: (n_parts, 6), range (0, 1) :return: """ n_parts = len(affines) colors = [[0, 0, 255, 255], # blue [0, 255, 0, 255], # green ...
3d6568e6e533bdb31cdceb244666f376d73dad1e
8,005
def _select_index_code(code): """ 1 - sh 0 - sz """ code = str(code) if code[0] == '3': return 0 return 1
697d8e5ca1744c897b7eebbb7b9b0a3b45faec3d
8,006
def get_install_agent_cmd(): """Get OS specific command to install Telegraf agent.""" agent_pkg_deb = "https://packagecloud.io/install/repositories/" \ "wavefront/telegraf/script.deb.sh" agent_pkg_rpm = "https://packagecloud.io/install/repositories/" \ "wavefront/tele...
14373024b3b6046badcedf686a38423f126f02a2
8,007
from typing import Tuple from typing import DefaultDict import collections def unpack(manifests: LocalManifestLists) -> Tuple[ServerManifests, bool]: """Convert `manifests` to `ServerManifests` for internal processing. Returns `False` unless all resources in `manifests` are unique. For instance, returns ...
b7f3c3f1388b9d3791a18f2da97dd40cf131ecaa
8,008
async def async_setup_platform(hass, config, async_add_entities, discovery_info=None): """Set up the switch from config.""" if DATA_KEY not in hass.data: hass.data[DATA_KEY] = {} host = config[CONF_HOST] token = config[CONF_TOKEN] name = config[CONF_NAME] model = config.get(CONF_MODEL) ...
0ef4f94c2b69bb2674ffcace56a85927c2c6d1d1
8,009
def process_generate_metric_alarms_event(event): """Handles a new event request Placeholder copied from alert_controller implementation """ LOG.info(str(event)) return create_response(200, body="Response to HealthCheck")
45f3ac5fa73048ec1f76bb5188a4e1de0eaca62d
8,010
def get_query_segment_info(collection_name, timeout=None, using="default"): """ Notifies Proxy to return segments information from query nodes. :param collection_name: A string representing the collection to get segments info. :param timeout: An optional duration of time in seconds to allow for the RPC...
521119f98a43d1abc303028f9bfa150dbfba098b
8,011
def IoU(pred, gt, n_classes, all_iou=False): """Computes the IoU by class and returns mean-IoU""" # print("IoU") iou = [] for i in range(n_classes): if np.sum(gt == i) == 0: iou.append(np.NaN) continue TP = np.sum(np.logical_and(pred == i, gt == i)) FP = n...
9635472121b13c9ce04e38fdfaee8bf29774a17a
8,012
def from_torchvision(vision_transform, p=1): """Takes in an arbitary torchvision tranform and wrap it such that it can be applied to a list of images of shape HxWxC Returns a callable class that takes in list of images and target as input NOTE: Due to implementation difficuities, in order ...
b2af1a672d24171d9b80cd4eeb6d53fc80d09f53
8,013
def get_ports(context, project_id=None): """Returns all ports of VMs in EOS-compatible format. :param project_id: globally unique neutron tenant identifier """ session = context.session model = db_models.AristaProvisionedVms if project_id: all_ports = (session.query(model). ...
17d8dadde3dde78286f746435454b454d5589bd2
8,015
import hashlib import hmac def _HMAC(K, C, Mode=hashlib.sha1): """ Generate an HMAC value. The default mode is to generate an HMAC-SHA-1 value w/ the SHA-1 algorithm. :param K: shared secret between client and server. Each HOTP generator has a different and unique secret K. :type K: ...
db9bf26c52427acc259f3cb1590c7c13b0d0dd9e
8,016
def get_reference(planet_name): """ Return reference for a given planet's orbit fit Args: planet_name (str): name of planet. no space Returns: reference (str): Reference of orbit fit """ planet_name = planet_name.lower() if planet_name not in post_dict: raise Value...
b700509300bdb2f6595e2a7c44a0d84e04d795f8
8,017
def DefaultPortIfAvailable(): """Returns default port if available. Raises: EmulatorArgumentsError: if port is not available. Returns: int, default port """ if portpicker.is_port_free(_DEFAULT_PORT): return _DEFAULT_PORT else: raise EmulatorArgumentsError( 'Default emulator port [{...
40c065946d8f9ee6c50f7df40f2be6644a472414
8,018
def mock_hub(hass): """Mock hub.""" mock_integration(hass, MockModule(DOMAIN)) hub = mock.MagicMock() hub.name = "hub" hass.data[DOMAIN] = {DEFAULT_HUB: hub} return hub
b4495ca6fbb7638aedf86406f94c00566e376b1b
8,019
def deferred_setting(name, default): """ Returns a function that calls settings with (name, default) """ return lambda: setting(name, default)
286acec75f7a5a1e0217dc4cee7b7b5d1ba8e742
8,020
def extends_dict(target, source): """ Will copy every key and value of source in target if key is not present in target """ for key, value in source.items(): if key not in target: target[key] = value elif type(target[key]) is dict: extends_dict(target[key], value) ...
5a68dde5e3bb7dbb81ad61c3698614f56dd5efd7
8,021
def get_maps_interface_class(zep_inp): """ Takes the input of zephyrus and return the maps of interfaces to classes and viceversa """ interface_to_classes = {} class_to_interfaces = {} for i in zep_inp["components"].keys(): class_name = i.split(settings.SEPARATOR)[-1] interfaces = zep_inp["compone...
9a14de30677abe0fa8cf0bb3907cd1f32a8f33de
8,022
def plextv_resources_base_fixture(): """Load base payload for plex.tv resources and return it.""" return load_fixture("plex/plextv_resources_base.xml")
f252099bd6457af208c4d96b8024d3ce28d84cd9
8,023
from netrc import netrc from requests.auth import HTTPDigestAuth def _auth(machine='desi.lbl.gov'): """Get authentication credentials. """ n = netrc() try: u,foo,p = n.authenticators(machine) except: raise ValueError('Unable to get user/pass from $HOME/.netrc for {}'.format(machine...
4ef27e589416f54dd76522b3312a2aa24441e200
8,024
import re def relative_date_add(date_rule: str, strict: bool = False) -> float: """Change the string in date rule format to the number of days. E.g 1d to 1, 1y to 365, 1m to 30, -1w to -7""" days = '' if re.search(DateRuleReg, date_rule) is not None: res = re.search(DateRuleReg, date_rule) ...
9180ed2ec99302679f7d0e2ee9ca57c4e2e6c48c
8,025
def to_frames_using_nptricks(src: np.ndarray, window_size: int, stride: int) -> np.ndarray: """ np.ndarray をフレーム分けするプリミティブな実装で,分割に`np.lib.stride_tricks.as_strided`関数を使用しており,indexingを使用する`to_frames_using_index`より高速である. Parameters ---------- src: np.ndarray splited source. window_size: i...
b10b077cf0fbf2b0e491e7f1cba9033cfadf10c5
8,026
def global_fit( model_constructor, pdf_transform=False, default_rtol=1e-10, default_atol=1e-10, default_max_iter=int(1e7), learning_rate=1e-6, ): """ Wraps a series of functions that perform maximum likelihood fitting in the `two_phase_solver` method found in the `fax` python module....
46917c0a4e6469759184a4aaa8199c57573360b0
8,027
from typing import Optional from typing import List def reorder_task( token: 'auth.JWT', task_id: 'typevars.ObjectID', before_id: 'Optional[typevars.ObjectID]' = None, after_id: 'Optional[typevars.ObjectID]' = None ) -> 'List[models.Task]': """Change the position of the task in the list.""" if...
b9e30b6d5929614d8385bd478e0e0a1f2663723f
8,029
def get_ldpc_code_params(ldpc_design_filename): """ Extract parameters from LDPC code design file. Parameters ---------- ldpc_design_filename : string Filename of the LDPC code design file. Returns ------- ldpc_code_params : dictionary Parameters of the LDPC code. "...
a2702a3fb5faf67d56fa08ae7ab627e3142fb006
8,030
def find_collection(*, collection, name): """ Looks through the pages of a collection for a resource with the specified name. Returns it, or if not found, returns None """ if isinstance(collection, ProjectCollection): try: # try to use search if it is available # cal...
a6532f2f63b682822f96e51d7ab86e7bc240d922
8,031