content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import json def handle_response(command, frame, args, quiet=False): """ Handle a response frame from the device. Return a dictionary of interesting information. """ ret_dict = {} resp_command = frame.get_frame()[0] if resp_command & protocol.CMD_RESPONSE: resp_command ^= protocol.C...
47b8eb435db997ec57581f100e9f72bc2bb8591c
3,617,000
def trace(f): """ helps debug recursive calls """ indent = ' ' def _f(*args): signature = '%s(%s)' % (f.__name__, ', '.join(map(repr, args))) print '%s--> %s' % (trace.level * indent, signature) trace.level += 1 try: result = f(*args) print ...
718a70489887e47e0c3708b840dfffde7d0193fb
3,617,001
import sqlite3 from typing import Any def generate_table(rows: list[sqlite3.Row], target: tuple[int, Any] = None) -> list[str]: """Generate a Markdown-like table out of the given rows. The optional `target` parameter expects a tuple of the form ``(col#, value)``. If the given column nu...
650e31efe92774749c306cf94dfeb91ad68ad502
3,617,002
def getPrivateKeyObject(filename = None, data = '', passphrase = ''): """ Return a C{Crypto.PublicKey.pubkey.pubkey} object corresponding to the private key file/data. If the private key is encrypted, passphrase B{must} be specified, other wise a L{BadKeyError} will be raised. @type filename: ...
07a5c5b302726b2db4eab3e451765ebbe592e374
3,617,003
import statistics def get_two_movies_average_rating(movie1_id, movie2_id, threshold=50): """return the average rating for two movies, based on the users who have watched both of the movies""" users = get_user_watched_two_movies(movie1_id, movie2_id) if users and len(users) > threshold: ratings1 = ...
8a2080624357cd112d8789317984d0e01d1cf2da
3,617,004
import torch def test_extraction(): """End-to-end test of a model extraction attack""" # Create a query function for a target PyTorch Lightning model model = train_four_layer_mnist_victim(gpus=torch.cuda.device_count()) def query_mnist(input_data): # PrivacyRaven provides built-in query func...
72ce6c053a9bca2cfaf965193b9cf5aa9f889df6
3,617,005
def read_parquet(filename, column, **kwargs): """read_parquet""" memory = kwargs.get("memory", "") start = kwargs.get("start", 0) stop = kwargs.get("stop", None) if stop is None and column.shape[0] is not None: stop = column.shape[0] - start if stop is None: stop = -1 return parquet_ops.io_read_pa...
785f0a6f16679b0f60ee37bcdadc9fba409b8099
3,617,006
from pathlib import Path import os import subprocess def decompress(full_bzip_filename: Path, temp_pth: Path) -> str: """ Decompresses .bz2 file and returns the non-compressed filename Args: full_bzip_filename: Full compressed filename temp_pth: Temporary path to save the native file ...
4fdacd7340a75de056f08557c87509b0b899b1a8
3,617,007
def to_int(value): """Converts the given string value into an integer. Returns 0 if the conversion fails.""" try: return int(value) except (TypeError, ValueError): return 0
f219844de96d1d2236e94c4427c0ad27cc4b587b
3,617,008
def create_two_transforms_curve(transform1, transform2, name = ''): """ Create a curve between two transforms. """ if not name: name = '%s_to_%s_curve' % (transform1, transform2) pos1 = cmds.xform(transform1, q = True, ws = True, t = True) pos2 = cmds.xform(transform2, q = True, ws ...
e894c77d647afdbe7676360ed73640193f03fe2e
3,617,009
def vms_ajax_assign_disk(request, vm_id, template_name='vms/ajax/assign_disk.html', form_class=AssignDiskForm): """ Ajax view for assigning Disk to a virtual machine. """ rest_data = prep_data({'disks': 'user/storage_image/get_list/', 'disk_controllers': 'user/storage_image/ge...
c0fd472d9a9fbbd8a1e27a1b5bb86c313776cbdf
3,617,010
def _default_function(l, default, i): """ EXAMPLES:: sage: from sage.combinat.integer_vector import _default_function sage: import functools sage: f = functools.partial(_default_function, [1,2,3], 99) sage: f(-1) 99 sage: f(0) 1 sage: f(1) ...
05da74d0c4ecee914928e8760d75730efc3434e5
3,617,011
import base64 import json def parse_id_token(token: str) -> GoogleUserInfo: """Parse the base64 encoded id token.""" parts = token.split(".") if len(parts) != 3: raise RuntimeError("Received Invalid ID Token") payload = parts[1] padded = payload + ("=" * (4 - len(payload) % 4)) decode...
8a7ea6c8d959c35df8f623f892b4df7e4b8af3b0
3,617,012
def _parse_apple(data): """Parse an AppleSingle or AppleDouble file.""" header = _APPLE_HEADER.from_bytes(data) if header.magic == _APPLESINGLE_MAGIC: container = 'AppleSingle' elif header.magic == _APPLEDOUBLE_MAGIC: container = 'AppleDouble' else: raise ValueError('Not an A...
8cade17b36fcafdfde6ebd81a9918d77e114586c
3,617,013
def convert_headers_str(_str): """ convert headers str to dict """ _list = [i.strip() for i in _str.split('\n')] headers_dict = dict() for i in _list: k, v = i.split(':', 1) headers_dict[k.strip()] = v.strip() return headers_dict
cc80c1c2f5fc128243e59529808685335f7cead4
3,617,014
def make_expand_dims_tests(options): """Make a set of tests to do expand_dims.""" test_parameters = [{ "input_type": [tf.float32, tf.int32], "input_shape": [[5, 4], [1, 5, 4]], "axis_value": [0, 1, 2, -1, -2, -3], "constant_axis": [True, False], "fully_quantize": [False], }, { ...
238d4a6ba427357c4e02223c01d5245610016492
3,617,015
def eliminate_from_neighbors(csp, var) : """Eliminates incompatible values from var's neighbors' domains, modifying the original csp. Returns an alphabetically sorted list of the neighboring variables whose domains were reduced, with each variable appearing at most once. If no domains were reduced, re...
66062fce99f7f596239c27b27265bdec20cd55ae
3,617,016
def cross(a, b): """Cross Product function Given vectors a and b, calculate the cross product. Parameters ---------- a : list First 3D vector. b : list Second 3D vector. Returns ------- c : list The cross product of vector a and vector b. ...
d71244391e28af7b42eff45af62cc936b8651cd2
3,617,017
from operator import add def add_multiply(x, y, z): """Add two numbers and multiply it with a third.""" addition = add(x, y) product = multiply(addition, z) return product
430e5c17106faab4a123123c42c10064727e654c
3,617,018
async def async_setup(hass: HomeAssistant, config: dict): """Set up the media_source component.""" hass.data[DOMAIN] = {} hass.components.websocket_api.async_register_command(websocket_browse_media) hass.components.websocket_api.async_register_command(websocket_resolve_media) hass.components.fronten...
4de2588406b96b0a9eb8f9ad6ac959c79ad601ee
3,617,019
import random def rand_sampling(ratio, stop, start=1) : """ random sampling from close interval [start, stop] Args : ratio (float): percentage of sampling stop (int): upper bound of sampling interval start (int): lower bound of sampling interval Returns : A random...
9b54c6b364e71a97d7cd9fa392790c4afde2bae0
3,617,020
import urllib def open_webpage(url): """some webpages block the user agent 'python'""" hdr = {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11'} req = urllib.request.Request(url, headers=hdr) return urllib.request.urlopen(req)
1b7fd7d6edd652818f6c454e9e27a4c5bd11c298
3,617,021
def compare_from_file(filename, disable_tokenizers=None, verbose=True, additional_tokenizers=None): """ Method to compare the tokenizers from an input text. This function outputs information about the execution environment and data and comparison results. Parameters -----...
77863249c1ee2940bb5c3fa770ae3bd2ec934858
3,617,022
def humanbool(name, value): """ Determine human boolean value :Parameters: `name` : ``str`` The config key (used for error message) `value` : ``str`` The config value :Return: The boolean value :Rtype: ``bool`` :Exceptions: - `ValueError` : The value could n...
422d45167c26f422e1f0a2fc5aa1c5e2eb752276
3,617,023
import os def xlsx_to_array(url, sheetname='Data', skiprows=1, **kwds): """ Convert xlsx to numpy 2D array of objects Parameters --------- url: string or io Can either be a path or and io object sheetname: str The sheet name for the sheet in the xlsx file wanted Defa...
eab8e50b2970efc6b9d785022c175d68ef4e5ee0
3,617,024
async def filter_record(record_a, record_b, filter_fields=None): """ Filters a record for unique information. Args: record_a (``dictionary``): New airtable record. record_b (``dictionary``): Old airtable record (This will be dictate the ``id``) Kwargs: filter_fields (``list``, o...
79e42ff50bf8e43fb7c4df218b0de58f61ea778d
3,617,025
def mask_tokens_evenly(tokens, gap, min_token_lengths, mask_token, gap_mask=1): """Produce several maskings for the given tokens where each masking is created by masking every "gap" tokens, as long as the token is large enough according to min_token_lengths. Args: tokens (List[str]): a sequence of ...
76cb6d402b73a5d5af0e1e87835485962e9b2353
3,617,026
async def async_setup(hass, config): """Set up the Polar component.""" conf = config.get(DOMAIN) hass.data[DOMAIN] = conf or {} if conf is not None: _LOGGER.debug('Setting up Polar config flow from configuration data') hass.async_create_task( hass.config_entries.flow.async...
699136d6751311b25c433e5944e8a8f0363637ab
3,617,027
from .hosts import Host def valid_host(host: Host) -> Host: """ Validation test for valid Host class Parameters: host (Host): Host class object Returns: Host: Valid Host object """ if not isinstance(host, Host): raise ex.InvalidHostError( f'Must be Host class ...
bc8b25f3be0df5ed82b15d9e59f0453f70848be5
3,617,028
def build_graph(input_file): """Build the graph data structure from the input csv file.""" # Open the csv as dict iterator input_file = open(input_file, 'rU') reader = csv.DictReader(input_file) # Create all nodes nodes = {} for row in reader: name = row['NODE'] nodes[name] ...
aea8f7ccbadad85495c9d621de78ce31e03df4cb
3,617,029
def build_rnn_dataset(sst_home, reader, class_func=ternary_class_func): """Given an SST reader, return the `class_func` version of the dataset as (X, y) training pair. Parameters ---------- sst_home : str Full path to the 'trees' directory for SST. reader : train_reader or dev_reader ...
52526a5d778c17d229ac48beb7b70dcfd1ad83a0
3,617,030
from datetime import datetime def iso_dt_to_datetime(t: str) -> str: """ """ return default_datetime_repr(datetime.datetime.fromisoformat(t[:-1]))
7b6fbb00188572aeac5629423ef739a5adc01861
3,617,031
def index(): """ 后台管理首页 """ user = g.user return render_template("admin/index.html", user=user.to_dict())
4d1b2fc5af8e5f0774e482a5201b4fc1ac73a839
3,617,032
def test_distance(markers, verbose=True,threshold=200,size=None): """detect if to center is too near than seuil delet the smaller markers : image input verbose : if you want display process threshold : the sqaure distance into center size : the minimum size of area of the retai...
d1c4cefcfb19a75493a5ca1b14a543711ef3eeab
3,617,033
def cs(dataset, pts=0.0, neg=False, **kwargs): """ Circular shift. For multidimensional NDDataset, the shift is by default performed on the last dimension. Parameters ---------- dataset : nddataset nddataset to be shifted pts : int Number of points toshift. neg : bo...
051b56afa521f8c545cba27bef6648c1e21f9edc
3,617,034
def _result_value_flat_to_batchable(result_value_flat, result_flat_signature): """Converts result_value_flat -> result_value_batchable.""" result_value_batchable = [] for (r_value, r_spec) in zip(result_value_flat, result_flat_signature): if isinstance(r_spec, tensor_spec.TensorSpec): result_value_batch...
bc63f3fa692912622bfa1ce84373c94f3f9ec5e3
3,617,035
def sample_action(Q, state, num_actions, epsilon): """ Epsilon greedy action selection. Parameters ---------- Q : numpy array of shape (N, 1) Q function for the environment where N is the total number of states. state : int The current state. num_actions : int The ...
8034037fbdb4bb0538f786b262930c64c4615412
3,617,036
def get_socket_from_cluster_id(cluster_id): """ Returns the socket and token/queue dict for the specified cluster id :param cluster_id: The if of the cluster to check :return: The websocket and dict if found or None """ # Iterate over the connections for sock in CONNECTION_MAP: # Ch...
07ffe7a17e093d7bd8f1087501019f7527681535
3,617,037
from typing import Tuple from typing import Dict def save_user_giphy(user: "Users", giphy: "str") -> "Tuple[Response, int]": """ Saves giphy to user account Params: user (Users): User model provided by token_required giphy (str): Giphy ID provided by GIPHY Returns Tuple[Response, int] ...
2d0ffaa40841cef373cea600c968bea6a9dd9682
3,617,038
def contain_same_digit(a, b): """ This function tests whether or not numbers a and b contains the same digits. """ list_a = list(str(a)) list_b = list(str(b)) if len(list_a) == len(list_b): for elt in list_a: if elt not in list_b: return False return T...
a09feb891e5413593531e56871a92c335e585d7b
3,617,039
def get_names_of_packages(packages_info, without_rpmem): """ Returns names of packages, that should be built. """ packages = [] types = ['-', '-debug-', '-devel-', '-debuginfo-', '-debug-debuginfo-'] for elem in packages_info: # checks if rpmem and rpmemd packages should be built ...
8116824b61bc4d2528458304408c8eb8b3d8fc21
3,617,040
from typing import Union def has_nonnegative_entries(input_matrix: Union[sparse.csr_matrix, np.ndarray]) -> bool: """True if the array has non negative entries.""" if type(input_matrix) == sparse.csr_matrix: return np.all(input_matrix.data >= 0) else: return np.all(input_matrix >= 0)
882bb05a6ef60835145dafdbe1f7a1a5b855fe84
3,617,041
def get_worker(): """ Creates a redis queue worker with a retry exception handler. To run the worker: >> worker = get_worker() >> worker.work(with_scheduler=True) """ settings = get_config() queue = redis_queue(settings) return Worker( queues=[queue], connection=queue.connec...
2397098513afb9fad917b2d1e1ea2cf5cb800077
3,617,042
def setup_platform(hass, config, add_devices, discovery_info=None): """Setup the Command Sensor.""" if config.get('command') is None: _LOGGER.error('Missing required variable: "command"') return False data = CommandSensorData(config.get('command')) add_devices([CommandBinarySensor( ...
784a790b375ab25d4c6bbb4c42f131c08f270c1a
3,617,043
def error_data(code): """Constructs a dictionary with status and message for returning in an error response""" error = { 'status': code, 'message': http_status_message(code), } return error
6e4a01e5b32a74701605dba62b88738f9e852073
3,617,044
from typing import NamedTuple import logging def get_logger(config: NamedTuple) -> logging.Logger: """ Create instance of a logger and configure it using the variables from yaml config variables :return: """ try: # create logger with app name logger: logging.Logger = logging.getLog...
53c1de3180b467eec0ba937565eec524c945259e
3,617,045
def test_Mesh_NO6_transfinite(): """Unittests for the mesh.""" if rAnk == mAster_rank: print(">>> {test_Mesh_NO6_transfinite} ...... ", flush=True) def u(t, x, y, z): return np.cos(np.pi*x) + np.sin(np.pi*y) * np.sin(np.pi*z-0.125)**2 + t/2 def v(t, x, y, z): return np.sin(np.pi*x) + np.sin(np....
aada50c384ffff0477962158f2e3902e8c9f471f
3,617,046
def range_correction(series, range=None, value=np.nan): """Corrects issues with ranges. Some values collected are not within the ranges. They could also be removed using the IQR rule, but if we know the limits we can filter them as errors instead of outliers. .. todo: Warn if replace value is outs...
452472772d955597f3a1495a38cd0a42c7b2accf
3,617,047
def isPILAllowed(): """Return true iff PIL should be used by the caller.""" global _pil_allowed if _pil_allowed is None: app = grailutil.get_grailapp() _pil_allowed = (app.prefs.GetBoolean("browser", "enable-pil") and pil_installed()) return _pil_allowed
34a33d0789cca703c8dc36103b652c307bb51820
3,617,048
import yaml def read_yaml(config_path): """Load config files.""" with open(config_path) as file: data = yaml.load(file, Loader=yaml.FullLoader) return data
b46882ad841228edb3398a5742fa4dea6c4e9495
3,617,049
def read_jsonlines(filepath: str) -> pd.DataFrame: """Function that reads a jsonlines file as a pandas dataframe""" with open(filepath) as f: lines = f.read().splitlines() dicts = [eval(line) for line in lines] return pd.DataFrame(dicts)
01c77934df604de88d747d032045f886ffe33bdf
3,617,050
from typing import Tuple def read_data_attention(strategy: tf.distribute.TPUStrategy, max_len: int, ) -> Tuple[np.array, np.array, np.array, np.array, tf.data.Dataset, tf.data.Dataset, tf.data.Dataset, int]: """ read data from attention models """ logger...
fa3943c787f203a6e57a59da7c93baa090223360
3,617,051
def cosine_sim(text1, text2): """ Calcuates the cosine distance between the skills and the course description. :param text1: Phrase 1 :param text2: Phrase 2 :return: returns the probabilistic measure of similarity. """ vectorizer = TfidfVectorizer(tokenizer=normalize, stop_words='english...
abef404514d9db40ca79c04f3663f1ea062e5b12
3,617,052
def distinct(key_mapper=None): """Returns an observable sequence that contains only distinct elements according to the key_mapper. Usage of this operator should be considered carefully due to the maintenance of an internal lookup structure which can grow large. The source must be a MuxObservable. ...
80f40e88ecfff69a954c82fd15f8fafe797b13f4
3,617,053
def svn_client_commit3(*args): """ svn_client_commit3(svn_commit_info_t commit_info_p, apr_array_header_t targets, svn_boolean_t recurse, svn_boolean_t keep_locks, svn_client_ctx_t ctx, apr_pool_t pool) -> svn_error_t """ return apply(_client.svn_client_commit3, args)
d69ebad3d11e194a7b4bd25935e57f7b8b17362f
3,617,054
def parse_range(string): """ Parses IP range for args parser :param string: formatted string X.X.X.X-Y.Y.Y.Y :return: tuple of range """ ip_rng = string.split("-") return [(ip_rng[0], ip_rng[1])]
6f38e105284d58af2cef94275c25e02ad76acb80
3,617,055
from typing import Optional from typing import Union from typing import Sequence from typing import Literal def panas( data: pd.DataFrame, columns: Optional[Union[Sequence[str], pd.Index]] = None, language: Optional[Literal["english", "german"]] = None, ) -> pd.DataFrame: """Compute the **Positive and...
90933eab4a82f64c37cfee455d756218151d4e46
3,617,056
def notes(l, b, i): """!parent-command !c new !d Create a new note (use \n for newline) !a <title> <message...> !r user !c list !d List all notes available !r user !c append !d Append a line of text to a note !a <title> <message...> !r user...
c2594c2d4fb21bf5d8d1f28d7077f8a5ebd60e49
3,617,057
def measure_circuits_nondeterministic(allow_sampling=True): """"Measure test circuits with non-deterministic count output.""" circuits = [] qr = QuantumRegister(2) cr = ClassicalRegister(2) # Measure |++> state (sampled) circuit = QuantumCircuit(qr, cr) circuit.h(qr) circuit.barrier(qr...
b7e5424c2340753d374ecc1f14fe6f65034e9661
3,617,058
def process_stanford_sentiment_corpus(train_path, dev_path, test_path, pkl_path, unk_threshold, unk_token= '<UNK>', pad_token= '<PADDING>'): """ Input three...
fd341b283801fee3face62117e1a5845e10892b6
3,617,059
from io import StringIO import gzip def _get_data(url): """Helper function to get data over http or from a local file""" if url.startswith('http://'): resp = urllib2.urlopen(url) encoding = resp.headers.dict.get('content-encoding', 'plain') data = resp.read() if encoding == 'pl...
6b7b1a803dd03d6fce25a0e679abf6110cef423a
3,617,060
import inspect def lineno(): # pragma: no cover """ Returns the current line number in our script :return: """ return str(' - line number: ' + str(inspect.currentframe().f_back.f_lineno))
ca40ae90ea44883ac40bd5524fee04c3957b2021
3,617,061
def _require_response_200_ok(response): """ Accept a requests.response object. Raise ResponseNotOK if status code is not 200. Otherwise, return True """ if response.status_code != 200: raise ResponseNotOK( status_code=response.status_code, message=response.text ) ...
4b35584eca30d7b0ac62ef51587f6f7cf03749a3
3,617,062
import fnmatch import os def trial_matrix(root,iwhisker=0,ifeature=3): """ image plot of a feature for a whisker where each row is a trial """ def gen_names(root): for r,dirnames,filenames in os.walk(root): for filename in fnmatch.filter(filenames,'*.measurements'): yield os.path.join(r,file...
5f9f6779060327bfc9302038176317e7cf6a940b
3,617,063
def pf_index(grid: Grid, grid_params: GridParams) -> PFIndex: """Ordered buses and mappings to admittances and slack factors.""" pv_idx = pv_buses(grid, grid_params) pq_idx = pq_buses(grid, grid_params) s_idx = slack_factors(grid, grid_params) y_idx = admittances(grid, grid_params) ret...
2b092b71051bb0bdbd97ed9926b310f016f88d50
3,617,064
import re def read_rdump(filename: str) -> dict: """ Read data formatted using the R dump format. """ contents = open(filename).read().strip() names = [name.strip() for name in re.findall(r'^(\w+) <-', contents, re.MULTILINE)] values = [value.strip() for value in re.split(r'\w+ +<...
3624f56d2872885c50d2d7f521730bb8a8864211
3,617,065
def selectYear(update: Update, context: CallbackContext): """ Select the yaer for which to list expenses """ year = update.message.text context.user_data['inputYear'] = year text = ("Received '"+year+"' as the selected year" +"\nSelect from below the month for which you'd like to list exp...
79c982b1591e15b9014302ca4380ec8900bad17f
3,617,066
def sort_by_field(boxlist, field, order=SortOrder.descend, scope=None): """Sort boxes and associated fields according to a scalar field. A common use case is reordering the boxes according to descending scores. Args: boxlist: BoxList holding N boxes. field: A BoxList field for sorting and reordering the...
a091e699182fe9c1b8a2bca881759004e67fc7d9
3,617,067
import json def process_frame(frame_data, d_width, d_height, features_file, images_dir, min_trajectory_len): """Save faces + features from a frame, and creating face embeddings. """ # Filter to faces with a valid trajectory (len > MIN) valid_faces = [ face for face in frame_data["faces"] ...
07be5d8fe578ca89cf56c763c3ad3c9bbe5c5986
3,617,068
from sympy.polys.polytools import degree from sympy.polys.domains import FractionField from sympy.core.basic import preorder_traversal def minimal_polynomial(ex, x=None, **args): """ Computes the minimal polynomial of an algebraic element. Parameters ========== ex : algebraic element expression ...
7f9c74d05a19858607fecf0b4f87798eafbf9534
3,617,069
import struct import tqdm def init_compress_timepix_data( pos, t, binstep, filename, mask=None, md=None, nobytes=2, with_pickle=True ): """YG.Dev@CHX Nov 19, 2017 with optimal algorithm by using complex index techniques Compress the timepixeldata, in a format of x, y, t x: pos_x in pixel y: pos_y...
6bf01ebc99e0bd2d40dc00152e3329f5fa9427c3
3,617,070
import torch def calc_dihedral(v1, v2, v3, v4, x_idx=None, y_idx=None, eps=1e-6): """ Calculate the dihedral angle between 4 vectors. v1, v2, v3, v4: shape (..., 3) x_idx, y_idx: shape (...), additional information of vectors. return: (x_idx, y_idy, dihedral) """ x = v2 - v1 y = v3 - v...
4ef064aa607ff23d212b628dd5c465e13fffd9b5
3,617,071
def set_convert_inputs(flag): """ This function is a temporary workaround for reducing the overhead of operator invocations. The function `convert_inputs` is disabled if the global state `_enable_convert_inputs` is set to `False`, otherwise enabled. This function is for internal use only, and should be ...
5bf661d6aeef099b7ecdfd117cf9dfdb4fae1285
3,617,072
import ctypes def encode_flush(): """ Flush the encoding buffers and return final frames (if any). """ _lib.lame_encode_flush.argtypes = [ ctypes.c_void_p, ctypes.c_void_p, ctypes.c_int] _lib.lame_encode_flush.restype = ctypes.c_int mp3buffer = (ctypes.c_char * 7200)() mp3buffer_us...
d0f137df60020c55ab27f4b98cb4dba7bc71a60f
3,617,073
import logging import traceback from datetime import datetime async def format_stream(member: discord.Member, osu_score: dict, beatmap: dict): """ Format the stream url and a VOD button when possible. """ stream_url = None for activity in member.activities: if activity and activity.type == discord...
6814fd8329868e13baf4fd2b3d03888c211e39a5
3,617,074
def parse_city_state_zip(city_state_zip): """ Parses city_state_zip into a dict """ city_state_zip = normalize(city_state_zip.replace(",", ", ").replace(".", ". ").strip()) if city_state_zip: # normalize commas _m = " ," while _m in city_state_zip: city_state_zip = city_s...
d60cefd3ac24acae08bc2196bf1629fd1fc92e45
3,617,075
def flows_from_sff(flows): """lines is sff file lines. """ if isinstance(flows, str): flows = flows.splitlines() flows, head = parse_sff(flows) return flows_from_generic(flows)
2a917c4f6e747b388c561ef933f861eef918552b
3,617,076
def common_lens(cube_list): """ Give the common lenses of a list of pySNIFS cubes @param cube_list: input list of datacubes @return: inters: list of the lenses common to all the cubes of the list """ inters = cube_list[0].no for i in xrange(1,len(cube_list)): inters = filter(lambda x...
f8c22e76a92ae187006977e86b5483601088a98d
3,617,077
def protected(Authorize: AuthJWT = Depends()): """ We do not need to make any changes to our protected endpoints. They will all still function the exact same as they do when sending the JWT in via a headers instead of a cookies """ Authorize.jwt_required() current_user = Authorize.get_jwt_s...
a0232bd11634ccac83086733e5032c5ccca9ff73
3,617,078
from typing import Optional import torch def sin(x: DNDarray, out: Optional[DNDarray] = None) -> DNDarray: """ Compute the trigonometric sine, element-wise. Result is a ``DNDarray`` of the same shape as ``x``. Negative input elements are returned as ``NaN``. If ``out`` was provided, ``sin`` is a refer...
74a52f3a72d35eec4bbea94e3ed51abf02bc30ef
3,617,079
from typing import Optional from typing import List def list(lst: 'Optional[List_[PythonValue]]' = None) -> PythonValue: """Returns a List wrapped into a PythonValue""" return PythonValue(List(lst=lst))
08f607b4befae0393561cf6bd06f43c1029dc724
3,617,080
async def set_consumer_to_infernal_job(engine, job_id, consumer_ip): """ Update the infernal_job table to register the consumer who will run the job :param engine: params to connect to the db :param job_id: id of the job :param consumer_ip: ip address of the consumer :return: id or none """ ...
05627d52809ebf378a030e40473dcee8b9e6ecc2
3,617,081
def get_recursively(search_dict: dict, field: str) -> list: """Take a dict with nested lists and dicts, and searche all dicts for a key of the field provided. https://stackoverflow.com/a/20254842 Args: search_dict (dict): Dictionary to search field (str): Field to search for R...
5457a41116cfb58eaf6ab57918a5d87eae7196a6
3,617,082
from pathlib import Path def askDestination(): """ prompts user for backup directory and sets it to destination :returns: new destination """ location = filedialog.askdirectory() # validation p = Path(location) if not p.exists() or not p.is_dir() or location == '': return bm.d...
fe805e9ec3dbe503a2357ac6bcad4c4aa1809be5
3,617,083
def get_hostip(req=None, log=None): """Look up the IP address for a given requested interface name. If interface is not given, do some magic.""" global _hostip # pylint: disable=W0603 if _hostip: return _hostip AF_INET = netifaces.AF_INET # We cre...
27d9d024ae1854b1f122232ef2a17deb8d827eb2
3,617,084
def time_series_sum_of_reoccurring_values(x): """ Returns the sum of all values, that are present in the time series more than once. :param x: the time series to calculate the feature of :type x: pandas.Series :return: the value of this feature :return type: float """ return ts_feat...
020203facf8765f292cb2f19f68dc603c8254b66
3,617,085
def promote_numeric_to_real(stage: ImportStage, value: ir.Value) -> ir.Value: """Promotes the value to RealType.""" return d.PromoteNumericOp(d.RealType.get(), value).result
d1be8cac377e34687a7b7ab680c507d9166820a7
3,617,086
import asyncio async def make_photo(): """Photo from web camera. """ loop = asyncio.get_running_loop() img, _ = await loop.run_in_executor(app.ps_executor, get_png_photo) if img: result = StreamingResponse( png_img_to_buffer(img), media_type="image/png" ) else: ...
5e243950d75a68d245d751fd6636f1416e30a31b
3,617,087
def get_adj_matr(graph): """ Function to create an adjacency matrix representation of a graph. arg: graph - (dict) of 'nodes' : [], 'edges' : [] returns: pd.DataFrame with entry i,j representing an edge from node i to node j """ n = len(graph['nodes']) adj_matr = pd.DataFrame...
81bc0673071c1afe96340039feb94ab1bd3b2393
3,617,088
import sqlite3 def _test_sqlite3_db(db_path): """Very basic test for validity of database.""" # Check for file existance and if it's a sqlite3 db if isfile(db_path): try: conn = sqlite3.connect(db_path) # TODO: If we really care, do a more thorough check # If ...
61b4fd66edbc32e876ac8ddeae166354b18c94ec
3,617,089
import os def get_resourcesize(path): """指定されたリソースの標準サイズを返す。""" dpath = os.path.basename(os.path.dirname(path)) fpath = os.path.splitext(os.path.basename(path))[0] key = "%s/%s" % (dpath, fpath) if key in SIZE_RESOURCES: return SIZE_RESOURCES[key] else: return None
22b09f497cb2b361d72ec2da3ea43eb98a201519
3,617,090
import os def all_files_from(dir, ext=''): """Quick function to get all files from directory and all subdirectories """ files = [] for root, dirnames, filenames in os.walk(dir): for filename in filenames: if filename.endswith(ext) and not filename.startswith('.'): f...
e6e2fc545ceda51a2b4560829b0e995c164c5d9c
3,617,091
import requests import re def get_title(url: str): """ Get the Title of the web page and generates markdown formated link""" html_source = requests.get(url).text title = re.findall('<title>(.*?)</title>', html_source)[0].strip() return f"[{title}]({url})"
c6b0a559e7e3369d34e6266b7636d5c4a13ed2f0
3,617,092
def pow_4_of(number): """ fourth power of number helper function from lalsimulation/src/LALSimIMRPhenomD_internals.h """ pow2 = pow_2_of(number) return pow2 * pow2
9ae515bd8ca9e8027f6ddecd71b714010668cfa3
3,617,093
def item_cost_entry() -> float: """Return the sum of all user entries.""" print('\nENTER ITEMS (ENTER 0 TO END)') subtotal: float = 0.0 while True: cost: float = float(input('Cost of item: ')) if cost == 0: break else: subtotal += cost return subtotal
d9d5bdc53f2d37f348d477086935cba3ba6a8e7e
3,617,094
def mark_duplicates(job, config, name, input_bam): """Run Picard MarkDuplicates :param config: The configuration dictionary. :type config: dict. :param sample: sample name. :type sample: str. :param input_bam: The input_bam file name to process. :type input_bam: str. :returns: str -- Th...
d7987f74d4c12ee190e895374a062cdc140ec2d6
3,617,095
def normalize_tokens(tokens): """ The OP-1 gets confused with multiple line segments in one command. This fixes that by splitting multiple segments into separate commands. Convert from e.g.: ["l", "20", "20", "20", "-20", "10", "10"] To: ["l", "20", "20", "l", "20", "-20", "l", "10", "10"] ...
972b7b2d46ac28d5d06c559fed1878355e18774e
3,617,096
import test def full_train_and_test(filename): """ Uses the entire dataset for both training and testing. Returns the testing accuracy. """ table, cumulative, dataset, index_to_name = train(filename) preds, targets = test(table, cumulative, dataset, index_to_name) n_correct, n_total = acc...
c27a9dafa27eab2b137a6b84d8e60e34665683ad
3,617,097
def _read_attachment(fp, has_arg=False, debug=False): """ Reads an ATTACHMENT block. """ target, arg, header, data = _read_block(fp, has_arg=False, debug=debug) d = dict(header=header, data=data, threshold=0.0) lr = [s.strip() for s in RE_ARROW.split(target)] if len(...
6c175b8e9b8c4f401ce4bab6960eb61dde5e8b16
3,617,098
import torch def mmd2_rbf(X, t, p, sig=0.1): """ Computes the l2-RBF maximum mean discrepancy (MMD) for X given t. http://www.jmlr.org/papers/volume13/gretton12a/gretton12a.pdf -- Eq3 """ it = np.where(t==1)[0] ic = np.where(t==0)[0] Xc = X[ic] Xt = X[it] if list(Xc.shape)[0] == ...
80d61470c84b2ce2c1f06930ae38bd711ff2f0bb
3,617,099