content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def cache_root(environ=None): """ The root directory for zipline cache files. Parameters ---------- environ : dict, optional An environment dict to forward to zipline_root. Returns ------- cache_root : str The zipline cache root. """ return zipline_path(['cache']...
b87345170f7e21a4cb02834646e552e5c3584a1a
34,575
def save_wechat_config(request): """ 保存微信配置信息 """ # 只有管理员有权限 if not request.user.is_superuser: return redirect('admin:index') conf_name = request.POST.get('conf_name') conf_value = request.POST.get('conf_value') if not conf_name or not conf_value: return render_json({'re...
551ee887aa13873265303a861c49a9f359194ff4
34,576
import logging def ParseQuickEditCommand( cnxn, cmd, issue, config, logged_in_user_id, services): """Parse a quick edit command into assignments and labels.""" parts = _BreakCommandIntoParts(cmd) parser = AssignmentParser(None, easier_kv_labels=True) for key, value in parts: if key: # A key=value as...
d009967514bd30ed493e72d3462c485424e5eb3b
34,577
def get_dict_X_dynamic(ar_iterations, forecast_cycle, input_k): """Provide information to load the dynamic data required by an AR model.""" dict_X_past = {} for i in range(ar_iterations+1): idxs = get_idx_lag(idx_start=0, ar_iteration=i, forecast_cycle=forecast_cycle, input_k=input_k) idxs_p...
a32df9643fb80533010630793c785d7a33e57062
34,578
def CMDterminate(parser, args): """Tells a bot to gracefully shut itself down as soon as it can. This is done by completing whatever current task there is then exiting the bot process. """ parser.add_option( '--wait', action='store_true', help='Wait for the bot to terminate') options, args = parser.p...
81c6f1df97c9dbf2ea955d4e5635ac2e06b007e2
34,579
def calculate_equilibrium( model, P, T, z, number_of_trial_phases=3, compare_trial_phases=False, molar_base=1.0, optimization_method=OptimizationMethod.PYGMO_DE1220, solver_args=PygmoSelfAdaptiveDESettings(50, 250) ): """ Given a mixture modeled by an EoS at a known PT-conditions, calculate the ther...
28716e9dcdb8368d4a682812d4fc094292ec6c81
34,580
def get_closing(image, n_erode=1, n_dilate=1, kernel=(5,5)): """ Performs the specified number of dilations, followed by the specified number of erosions to get the closing of the image. Parameters ---------- image : np.ndarray The image to perform the closing on. n_erode : int, op...
d53a8cfcf173dc72b43c707d856b29f65ddd04b4
34,582
def ZAdrift(pminitial, pmfinal, pos, smoothing = 0, deconvolve = 0, lptbool = 0): """ This function takes in initial density field, calculates ZA displacement, \ shifts the particle with that displacement and paints them. """ if not lptbool: ZAdisp = ZA(pminitial, pos) elif lptbool == ...
789bb9d20807b964a4d1f55471871e1bf10cf4e9
34,583
def create_candlestick(open, high, low, close, dates=None, direction="both", **kwargs): """ **deprecated**, use instead the new_plotly.graph_objects trace :class:`new_plotly.graph_objects.Candlestick` :param (list) open: opening values :param (list) high: high values :param (list) low: low valu...
1c0e8afba2f9f03924b84fccce470b675266d698
34,584
def sine_f0(duration: float, srate: int) -> np.ndarray: """Return the f0 contour of a sine wave of duration seconds long.""" sine_arr = np.sin(2 * np.pi * np.arange(srate * duration) * 440.0 / srate).astype( np.float64 ) f0 = pyworld.stonemask(sine_arr, *pyworld.dio(sine_arr, srate), srate) ...
aaaed0934317c884d3b7d3814fc55520f605888d
34,585
import requests def generate_download_list(years, doctype='grant'): """ Given the year string from the configuration file, return a list of urls to be downloaded """ if not years: return [] urls = [] link = 'https://www.google.com/googlebooks/uspto-patents-grants-text.html' if doctype ...
94259e49a9491f2d95643c6e0dfb8507a95748be
34,588
from typing import Union import uuid import base64 def readable_uuid(source: Union[str, uuid.UUID], *, _tt=str.maketrans('+/', '-_')) -> str: """ Formats the given UUID using modified base64 without padding. Returns a string of exactly 22 characters length. """ if isinstance(source, str): ...
fd0ff92ef177f2c456686c67fcb5895e34cb2409
34,589
def auto_sigma_y(sino, weights, snr_db = 30.0, delta_pixel = 1.0, delta_channel = 1.0): """Computes the automatic value of ``sigma_y`` for use in MBIR reconstruction. Args: sino (ndarray): 3D numpy array of sinogram data with shape (num_views,num_slices,num_channels) weights (ndarra...
f76f2abfee6466d9a50d04e1eaecda485a24935c
34,590
def neighborhoods(as_geo=False): """Neighborhood names and centers (lon, lat). Note: Names take from from the Parking meter data at: http://seshat.datasd.org/parking_meters/treas_parking_meters_loc_datasd.csv Location taken from wikipedia, or manual estimates derived via Google Maps. (This should ...
202ffaad18d0158b109df0797c510ee514cb1922
34,591
from typing import Tuple from typing import Any from typing import Optional import json def list_projects(base_url: str, api_key: str) -> Tuple[Any, Optional[error.URLError]]: """GET /projects.[format]""" try: params = { "key": api_key } req = request.Request(f"{base_url}/p...
ca1ae2bae493082c1ec810d7acd3046ebd5f518d
34,592
def index_at_direction(cell_index_array, direction): """ Returns the index of the neighbouring cell in the given direction""" index_array = cell_index_array.copy() if ( (index_array[1] == GRID_SIZE - 1 and RIGHT in direction) or (index_array[1] == 0 and LEFT in direction) or (index_array[0] == 0 and UP in dir...
c7127556b876133e2af1620d257832e95ac71b28
34,594
def _create_average_ops(params): """Build moving average ops.""" tf.logging.info('Creating moving average ops') with tf.variable_scope('moving_average'): moving_average_step = tf.get_variable( 'step', [], dtype=tf.float32, trainable=False) all_vars = tf.trainable_variables() average_pairs = [] ...
39e358056753f08f51b486eb20dddeac28f8375e
34,595
def reset_color_picker(modal_open, font_color): """ Reset the color-picker to white font color after closing the modal component. Parameters ---------- modal_open : bool A boolean that describes if the modal component is open or not font_color : dict of { 'hex': str, ...
03aaf2207f351eee70fbc8dda406ec0d8bc04530
34,596
from typing import Any from typing import List def get_tree_effects(tree: Any) -> List[str]: """ Return all effects of a tree as action strings. I.e. traverses the tree and returns the first child of each falback node, and the postconditions of the last child of each sequence node. Args ----...
440dc454ce8e32b87a4c7711f408398d757c90ca
34,598
def obtainTagVersionList(adshList, fileLocation): """ Scans the Pre file to find the Tags and the Versions used in the filing in question so as to populate the Tags table with only that subset """ with open(fileLocation + 'pre.txt') as fileHandle: tagVersionList = list() # read schema and adv...
217aaf4a9458404cb2082ec0f8bb6bba0a5d991a
34,599
def get_lightcurve(meteor_array): """ Calculates the sum of column level values of a given array. For croped meteor image this gives its lightcurve. """ ncols = len(meteor_array[0]) lightcurve = [] for i in range(ncols-1): lightcurve.append(np.sum(meteor_array[:, i:i+1])) return lightc...
3b231653d31444f274f867f7bb52fb5d73c376b3
34,601
def __neighcom(node, graph, status, threshold) : """ Compute the communities in the neighborood of node in the graph given with the decomposition node2com """ weights = {} for neighbor, datas in graph[node].iteritems() : if (neighbor != node) : # #if distance(neig...
36377dfd418fde5de34d2c815733be49748957b2
34,602
import six def wheel_is_compatible(filename): """ Return True if the wheel is compatible, False otherwise. """ data = parse_wheel_name(filename) if ("py2.py3" in data["python_tag"]) or ("py3.py2" in data["python_tag"]): # only here to skip elif/else pass elif six.PY3: i...
2de1d1c27629bbed863d6de6dd995da57f3bda0d
34,603
import numpy def _njit_itakura_mask(sz1, sz2, max_slope=2.): """Compute the Itakura mask without checking that the constraints are feasible. In most cases, you should use itakura_mask instead. Parameters ---------- sz1 : int The size of the first time series sz2 : int The siz...
c0905f4159aca4fc9b2c3448545770fa0019967f
34,604
def add_kl_to_loss(kl, loss, jacobian_dict): """Adds the KL to the optimized loss and updates jacobians accordingly.""" if kl is None: return loss, jacobian_dict loss += kl jacobian_dict = utils.add_grads_to_jacobians(jacobian_dict, kl) return loss, jacobian_dict
695627ca17fddf7126b8bcca50c11f6680b0152e
34,606
def _unicodeToBuiltInType(input_to_convert): """ Convert a string into a string, a float or an int depending on the string :param input_to_convert: unicode or string element to convert :Example: >>> _unicodeToBuiltInType("1") 1 >>> _unicodeToBuiltInType("1.0") 1.0 >>> _unicodeToBuiltInType("a") 'a' ...
1023ed1c22d71daef8277f2f0b7d1b642656fc09
34,607
def fxa_oauth_token(request): """Return OAuth token from authorization code. """ state = request.validated['querystring']['state'] code = request.validated['querystring']['code'] # Require on-going session stored_redirect = request.registry.cache.get(state) # Make sure we cannot try twice ...
1581ea350b18d70c10255a988ad1b2375e80f2f0
34,608
def minimaxav_score(profile, committee): """ Return the Minimax AV (MAV) score of a committee. Parameters ---------- profile : abcvoting.preferences.Profile A profile. committee : iterable of int A committee. Returns ------- int The ...
7bc9b4c81088341ca4f9fe2e5e03d71e36463504
34,609
def set_lipid(path, lipid): """ Establish save directory of cutoff test data. """ save_dir = "{}/PyLipID_cutoff_test_{}".format(path, lipid) fig_dir = check_dir(save_dir, "Figures", print_info=False) return fig_dir
a5ec6ab7af2f1006e96fd6ecb54eb3a6e8c45501
34,610
import re def format_bucket(bucket, appid): """兼容新老bucket长短命名,appid为空默认为长命名,appid不为空则认为是短命名""" if not isinstance(bucket, string_types): raise CosClientError("bucket is not string") if not bucket: raise CosClientError("bucket is required not empty") if not (re.match(r'^[A-Za-z0-9][A-Za-...
1d322982fd29d1f380d6bc19c319abefa23d4d7c
34,611
def model(pretrained=False, **kwargs): """VGG 16-layer model (configuration "D") Args: pretrained (bool): If True, returns a model pre-trained on ImageNet 'D': [64, 64, 'M', 128, 128, 'M', 256, 256, 256, 'M', 512, 512, 512, 'M', 512, 512, 512, 'M'], """ model = VGG(make_layers(cfg['O'], di...
ae38f9ad96f226152c47029c25bb1cbd40774c0e
34,612
def get_location_from_uri(uri): """ Given a URI, return a Location object that has had an appropriate store parse the URI. :param uri: A URI that could come from the end-user in the Location attribute/header Example URIs: https://user:pass@example.com:80/images/some-id ...
574c7cbf4fbe5b6e87a95e9ccdc283fbf7182337
34,613
def Coding(incoming_msg): """ Function to retrieve a meme on brooklyn99. :param incoming_msg: The incoming message object from Teams :return: A text or markdown based reply """ # our test search search_term = "coding" return SearchGif(incoming_msg, search_term)
1163ba5393dd15ac9a1004bb57defdcf45d07dcb
34,614
def false_pos(pred_labels, true_labels, groups): """ Calculates the number of elements in a group with a positive prediction but negative true label. :math: :math:`\\hat{Y} = 1, Y=0` :return: dictionary of total false positive predictions for each group """ if isinstance(pred_labels, Tens...
1e58ff4e5becf2beeea620fe232c800b8ad00009
34,615
def merge_mesh(mesh1: Mesh, mesh2: Mesh) -> Mesh: """Merge two meshes into a single mesh Keyword arguments: mesh1 -- First mesh mesh2 -- Second mesh """ m1_vertices = list(mesh1.absolute_vertices()) m2_vertices = list(mesh2.absolute_vertices()) mesh = Mesh() mesh.material = deepcopy...
71507c155446f9afd8ce017699a6ad859c4ba94b
34,616
def traverse(tree, it): """ Traverse tree until a leaf node is reached, and return its symbol. This function consumes an iterator on which next() is called during each step of traversing. """ nd = tree while 1: nd = nd.child[next(it)] if not nd: raise ValueError("...
5f4be6c4fedfe4220855c0ec12547a9f9eb2ac87
34,617
def deposit_create(): """Create a new deposit.""" return render_template( "invenio_app_rdm/records/deposit.html", forms_config=get_form_config(createUrl=("/api/records")), searchbar_config=dict(searchUrl=get_search_url()), record=new_record(), files=dict( defa...
66a79bb5e09c4f5934d19c1e5b5534645cf20fa8
34,618
def load_synthetic_mammogram(image_path): """Load a synthetic mammogram from file :param image_path: path to the image one disk. :returns: ndarray -- the image as an ndarray """ img, image_header = load(image_path) img = np.invert(img) img = img.astype('float64') img = skimage.transform...
6a35d963153f119b6f39eabb4f83235e35b0e934
34,619
def setUnitStatus(unitID: bytes, status: bytes) -> bytes: """ Sets the status for a unit :param unitID: :param status: :return: """ return wrap(b"g" + b"E" + b"U" + unitID + status)
04d34052d4ff5f337d8dcb972efebf36d289baa4
34,620
import re import json def _parsing_dayprice_json(pageNum=0): """ 处理当日行情分页数据,格式为json Parameters ------ pageNum:页码 return ------- DataFrame 当日所有股票交易数据(DataFrame) """ url = ct.SINA_DAY_PRICE_URL%pageNum request = urllib2.Request(url) text = urllib2.urlop...
d32a628a879796d56ed6a8eba288d1066ae416b7
34,621
def get_cammoun_schaefer(vers='fsaverage5', data_dir=None, networks='7'): """ Returns Cammoun 2012 and Schaefer 2018 atlases as dictionary Parameters ---------- vers : str, optional Which version of the atlases to get. Default: 'fsaverage5' data_dir : str or os.PathLike, optional ...
2a05cadcaef9f4ec2c24b027346a1cc658971924
34,622
def sql_schemas(dict_kwargs=None) -> SearchStrategy[dict[str, Table]]: """ Build objects describing multiple tables in a SQLite3 database. """ if dict_kwargs is None: dict_kwargs = {} return dictionaries(keys=sql_identifiers(), values=tables(), **dict_kwargs)
3cd11aa9fa26fd6692f193459d34e352d4b78b5b
34,623
import random def select_rand_pen(t_s: int, t_d: int, t_e: int, p: np.array) -> int: """ Simulate Multi Query Read Scheduling by sampling at random according to the inverse of the penalty function. @see selectRand :param t_s: int start time of the interval [t_s, t_e] :param t...
8106e2aab0ca4573415bde25450074c7518a9884
34,624
from typing import OrderedDict import array def _height_fit_fun(parameters, names, heights_dict, # in um radius, # in um data_dict=None, # in units [1, nm/mV, pN/nm] errors_dict=None, # in units [1, nm/mV, pN/nm] ...
ecc219a253f0e644e34e6435cd161a6a090e4d99
34,625
import ctypes import array import warnings def _get_bytes_pointer(inp): """Returns pointer to bytes-like input """ if isinstance(inp, np.ndarray): assert inp.dtype == np.uint8 # https://stackoverflow.com/q/60848009/5133167 if not inp.flags["C_CONTIGUOUS"]: # Make a cont...
db754acc506a7370aa3c9c29d87cdca12e3703ef
34,626
def no_trajectory_xml(): """Emulates a XML response for no trajectory case""" STREAM = b'<INST nbVeh="0" val="1.00"><CREATIONS><CREATION entree="Ext_In" id="0" sortie="Ext_Out" type="VL"/></CREATIONS><SORTIES/><TRAJS/><STREAMS/><LINKS/><SGTS/><FEUX/><ENTREES><ENTREE id="Ext_In" nb_veh_en_attente="1"/></ENTREES...
abd90b9f87beb39b04bbf8fc889c952d81d4e7f8
34,627
from typing import Dict from typing import List def get_scalars(tensors: Dict[str, tf.Tensor], names: List[str] = None, pattern: str = None) -> Dict[str, tf.Tensor]: """Retrieve scalars from tensors. Parameters ---------- tensors : Dict[str, tf.Tensor] Dictionary names : List[str], option...
0d4524925f62715d429b5def6ea0d3582eb07714
34,628
def rle_encoding(x): """ Run-length encoding stolen from https://www.kaggle.com/rakhlin/fast-run-length-encoding-python Args: x (np.ndarray): ndarray of size (height, width) representing the mask of an image Returns: run_lengths (list): List of predicted road pixels if x[i,j] ...
3a38de0b83bc25067f4adab26dc8b8287de0a66d
34,629
import re def normalize_date(date): """normalze date Returns: [string] -- [normalized result date] """ char = re.compile('[年月./]') date=date.group(0) date = char.sub('-',date) if '日' in date: date=date.replace('日','') return date
11197775c975fd09aa54a12de47b5e113d99f954
34,631
def get_rendersetup_layer(layer): """Return render setup layer name. This also converts names from legacy renderLayer node name to render setup name. Note: `defaultRenderLayer` is not a renderSetupLayer node but it is however the valid layer name for Render Setup - so we return that as is. ...
098e6286e018b4057498aa8afe66a28dde473ed8
34,632
from typing import List import math def grid(topology: Topology, template: AgentTemplate) -> List[AgentState]: """ Generate agents on every integer location within the `topology` bounds. Args: topology: the `context.globals()["topology"]` value. template: an agent definition, or a functio...
852a58136b55302d336aeb727387767b9241b17a
34,633
def formatNumber(number, numberOfDigits): """ The function formatNumber() return a string-representation of a number with a number of digits after the decimal separator. If the number has more digits, it is rounded. If the number has less digits, zeros are added. @param number: the number to fo...
04bb35fc3f7bab847709c48c6acdb72260a038eb
34,634
def get_plugin_manager(name="DEFAULT"): """Return the Collection Plugin manager for events logging. :param name: the name of the logger to be associated with the plugin. :type name: str :returns: the Logger plugin manager :rtype: LoggerPluginManager """ global _logger_plugin_managers t...
a830db601e18323c50818b989543b0e7f0df24a1
34,635
from foreshadow.smart import SmartTransformer from foreshadow.concrete import StandardScaler def smart_child(): """Get a defined SmartTransformer subclass, TestSmartTransformer. Note: Always returns StandardScaler. """ class TestSmartTransformer(SmartTransformer): def pick_transform...
d9a01815887ce33276dfe8b2feb2fddaf3e41cbd
34,636
def compute_species_interaction_weights( model: CommunityModel, df: pd.DataFrame, alpha: float = 1.0 ) -> Array: """Compute interaction between two species. The values lie between -1 (negative interaction) and + 1 postitive interaction. Be :math:`p_{ij}` the number of metabolites produced by i and consu...
575fa13797cfffa646757b8ac56dc3d132adf256
34,637
def unsupported_sequence_terminals(request): """Terminals that emit warnings for unsupported sequence-awareness.""" return request.param
6a85fcd35d3d4813ec14c530b867171518cb584e
34,638
def get_timed_data_sheet(wb,fkeys,pkeys,date_nums,ras,decs,azs,elevs): """ See if the timed data sheet exist and create it if not A timed data sheet is basically the power VtoF data as a function of time (rows) and frequency/polarization (columns). This initiates the sheet but does not fill it. fill_map_sh...
bbd46286e0ff1efc25089d46f81d8b31e3687f38
34,639
from pathlib import Path from typing import List from typing import Tuple def rtconvert(*, in_file: Path, reference_series: Path, out_file: Path, struct_names: List[str], struct_colors: List[str], fill_holes: List[bool], roi_interpreted_types: List[str], modelId: str, manufacturer: str, in...
80ee5e84bd67509367fa051b242ee4ff08e76017
34,640
def get_diamond_prediction(diamond_data, protein_accession): """Retrieve DIAMOND prediction data from dbCAN overview.txt file. :param diamond_data, str, output data from DIAMOND written in the overview.txt :param protein_accession, str Return a CazymeProteinPrediction instance. """ # check if ...
03f3feacd5263d0bc1d81b496bc2b9f537b14604
34,641
def train_batch(b, verbose=False): """ :param b: contains: :param imgs: the image, [batch_size, 3, IM_SIZE, IM_SIZE] :param all_anchors: [num_anchors, 4] the boxes of all anchors that we'll be using :param all_anchor_inds: [num_anchors, 2.0] array of the indices into the concatenat...
20f6c84803ef6ad5e148a8a5c0e8f172d8587a3f
34,642
def convert_image_idx_to_padded_string(n, numCharacters=6): """ Converts the integer n to a padded string with leading zeros """ t = str(n) return t.rjust(numCharacters, '0')
71309d7765e3fdc740f50db8f46b4e5b71eb512d
34,643
import math def compute_frequency(occurrence_count): """ frequency is too coarse. taking the log from it is going to smooth it somehow :param occurrence_count: :return: """ return round(math.log(occurrence_count), 2)
e797bf26feee3379a781b3eefe8a988700728c8f
34,645
def determineCalibrants(functions): """ Automatically determine suitable calibrant peaks. This function is part of the automated peak detection functionality, where it attempts to determine the most suitable n number of calibrations (n is the user defined setting of minimum number of peaks for cali...
3a45b14c2fcf1e48f35735ffa3b5f18d4ac05395
34,646
from datetime import datetime import spwd import crypt def check_pw(user, password): """Check the password matches local unix password on file""" # log the username & password # in openssh-server, if user is invalid, password must be overwrite. # source code: # badpw[] = "\b\n\r\177INCORRECT"; ...
c1a1bb9f9ce59d25eb453158be1ac28d40ac926e
34,647
def get_error_stats(errors, tokens): """ Returns a dictionary recording each error and its frequency in the document. Uses the FreqDist function from NLTK. `errors` generated with the `identify_errors` function. References: :func:`nltk.FreqDist` :func:`identify_errors` Args: ...
0be0b111ad9343e7ea3c740a4f4c6cf4b72f3755
34,648
def extended_figure(*args, **kwargs): """ Creates an Extended_Figure object. Parameters ---------- *args: *list Any argument accepted by matplotlib.pyplot.figure **kwargs: **dict Any keyword argument accepted by matplotlib.pyplot.figure Returns ------- fig: Extended...
bf9e8c00d35496b1ce74b7726ae61abe7c39ff00
34,649
async def handle_webhook(hass, webhook_id, request): """Handle incoming webhook from Locative.""" try: data = WEBHOOK_SCHEMA(dict(await request.post())) except vol.MultipleInvalid as error: return web.Response(text=error.error_message, status=HTTP_UNPROCESSABLE_ENTITY) device = data[ATT...
80cc23ab06066be8641fc3c9c7a0d321f0e22be2
34,650
def mat2flat(H): """ Converts an homography matrix with shape `[1, 3, 3]` to its corresponding flattened homography transformation with shape `[1, 8]`. """ H = tf.reshape(H, [-1, 9]) return (H / H[:, 8:9])[:, :8]
46896c0a3179df2e2678e26f3508de7b889bbc7a
34,651
def fibonacci_peak(cam,focus,ak,bk,aoi,hysteresis,tolerance): """Fibonacci peak search taken from E. Krotkov: "Focusing" P.233""" # cam: camera already opened # focus: focus from used LenseController # ak: start step no. # bk: stop step no. # aoi: area of interest in form [x1,y1,x2,y2] # hysteresis: offse...
7fdae0cc8b3e2ba6ed8d5b40091258e4e1bb47eb
34,653
def convert_params_to_string(params: dict) -> str: """ Create a string representation of parameters in PBC format """ return '\n'.join(['%s %s' % (key, value) for (key, value) in params.items()])
d121ea62f14333ad7f02727a7a6777b8880fef45
34,654
import time def get_series_nuclear_data(self, summary, sidx, **kwargs): """Function for parallelized single-pixel nuclear data retrieval. Args: summary (list): list of summaries. sidx (int): series index. **kwargs: ncores. Returns: np.array: series nuclear data. """ # Se...
29720e83df11623bdafd2f268b2a9da21a830ce4
34,655
def _encode_as_png(data, profile, dst_transform): """ Uses rasterio's virtual file system to encode a (3, 512, 512) array as a png-encoded bytearray. Parameters ----------- data: ndarray (3 x 512 x 512) uint8 RGB array profile: dictionary dictionary of kwargs for png writing...
535ece2c1375c0b2fe96f67547b012050bd9de9b
34,656
def arch_from_macho(cputype, cpusubtype): """Converts a macho arch tuple into an arch string.""" arch = ffi.new('SymbolicMachoArch *') arch[0].cputype = cputype & 0xffffffff arch[0].cpusubtype = cpusubtype & 0xffffffff try: return str(decode_str(rustcall(lib.symbolic_arch_from_macho, arch)))...
204815ecb1d4ab2d2d7aae4ac13522e37f68e7f9
34,657
def interpret_keypress(): """ See whether a number was pressed (give terminal bell if so) and return value. Otherwise returns none. Tries to handle arrows as a single press. """ press = getch() if press == "Q": raise Exception("Exiting expo by user request from pressing Q") i...
bc3b2e25b3c15c49daf6f7a3907e41bb04aa8d5e
34,659
def generate_numbers(limit): """ @param: limit - length of the sequence of natural numbers to be generated @return: list_of_numbers - list of the generated sequence """ if limit <= 0: raise ValueError('Invalid limit specified') list_of_numbers = list() for...
f0cd027f6978be01b80c4a86914ecc8d3444d251
34,660
def get_supplier(supplier_id): """ Read a single Supplier This endpoint will return a Supplier based on it's id """ app.logger.info("Request for supplier with id: %s", supplier_id) supplier = Supplier.find(supplier_id) if not supplier: raise NotFound("Supplier with id '{}' was not fo...
b358bfcaad48c6fbfb98ca6b64f799da6fe8eb78
34,662
import warnings def se_diversity(gen, k=None, n_jobs=1, fp_type='morgan', dist_threshold=0.65, normalize=True): """ Computes Sphere exclusion diversity i.e. fraction of diverse compounds according to a pre-defined Tanimoto distance. :param k: :param gen: :param n_jobs: :...
2be39404b8ae143efb7a37a78e753c1978676374
34,663
def get_root_y(c_sys: CompositeSystem) -> Gate: """returns root of Y gate. Parameters ---------- c_sys : CompositeSystem CompositeSystem containing gate. Returns ------- Gate root of Y gate. Raises ------ ValueError CompositeSystem is not 1quit. Val...
572deeb46a8a23d37a7138716b983d91136dc34b
34,664
def sanitize_sql(sql, keep_transaction=False): """Sanatize the sql string """ # remove comments string = remove_comments(sql) # remove transactionals if not keep_transaction: string = remove_transactional(string) # remove new lines string = remove_newlines(string) # remove...
9ef3c12b823f9eabc4f6b61fe389ea68db6c209d
34,665
def create_whimsy_computation_lambda_empty(): """Returns a lambda computation and type `( -> <>)`.""" value = computation_factory.create_lambda_empty_struct() type_signature = computation_types.FunctionType(None, []) return value, type_signature
741629cd80ba4bbaf27af22d4061226176dfc683
34,666
def fire_weather_index(isi, bui): """Fire weather index. Parameters ---------- isi : array Initial spread index bui : array Build up index. Returns ------- array Build up index. """ fwi = np.where( bui <= 80.0, 0.1 * isi * (0.626 * bui ** 0.809...
bae3f683a2870c36ce1b3c0c6f33d872968f851c
34,667
from typing import Optional import logging def read_file(filename: str) -> Optional[str]: """ Read a common file and return its content. Returns ------- content The file content """ try: with open(filename, 'r') as f: content = f.read return content ...
46ceb903af8b655edf85588d31987e02a7667ef4
34,668
def power(b, e): """ @purpose: Using a binary list to calculate power of two integers @param: b: The base number e: The exponent @precondition: A valid positive base and exponent are input @postcondition: The power of b^e is print out @Complexity: Best Case: O(1) if expon...
f510642c8b3eee9eac231b33d2e5260855c4bbf2
34,669
def get_all_items(): """Get all items""" items = Item.query.all() items_list = [] for item in items: item_object = { 'id': item.id, 'subject': item.subject, 'status' : item.status, 'url': item.url, 'requestor': item.requestor, ...
0dadd886096f8a3bcea2413830c70a89b4eb06fb
34,670
def usergenerator(no1, no2, no3, no4, mode): """ 生成中文拼音和随机字母组成的用户名 :param no1 表示声母: :param no2 表示韵母: :param no3 表示第一位随机字母: :param no4 表示第二位随机字母: :param mode 选择姓名的次序: :return 返回用户名: """ list1 = ['b', 'p', 'm', 'f', 'd', 't', 'n', 'l', 'g', 'k', 'h', 'j...
0875297000dc00bb3a6ba46844993047137261ec
34,671
def verify_input(json_data): """ Verifies the validity of an API request content :param json_data: Parsed JSON accepted from API call :type json_data: dict :return: Data for the the process function """ # callback_uri is needed to sent the responses to if 'callback_uri' not in json_dat...
77f609923bd774732c1233413633b077d47e5919
34,672
def detail_slug_dct(slug): """ Function to localize Slug's detail properties. :param slug: model Slug :return: dictionary with Slug's detail properties localized """ return _detail_slug_form.fill_with_model(slug)
13d7f41c706a45bf4534cc8be9f2be14e31bc6bd
34,673
import warnings def is_myst_available(): """Whether the myst-parser package is available.""" if myst_parser is None: return False major, minor = myst_parser.__version__.split(".")[:2] if int(major) < 1 and int(minor) < 8: warnings.warn("The installed myst-parser version is less than th...
15b54b642e2a4096438f41b12ac2c6b83b651716
34,674
def CreateTrimmedSurface(trimSource, surfaceSource, multiple=False): """ Constructs a Brep using the trimming information of a brep face and a surface. Surface must be roughly the same shape and in the same location as the trimming brep face. Args: trimSource (BrepFace): BrepFace which contains...
5b317a6c64c3607feb3338844a505e3b62fde970
34,675
def formatdatetime(datatimes): """ 格式化日期时间为指定格式 :param datatimes: 数据库中存储的datetime日期时间,也可以是字符串形式(2021-09-23 11:22:03.1232000) :return: 格式化后的日期时间如:2021-09-23 11:22:03 """ if datatimes: try: if isinstance(datatimes, str): if "." in datatimes: ...
8346fe27eb27994a647837c8b280e04e178c91d4
34,677
def get_difference(stocks: pd.DataFrame) -> pd.DataFrame: """Calculates the gains or loss for each stock.""" stocks = stocks.astype({"closing_price": "float", "initial_value": "float"}) stocks["gain_loss"] = stocks["closing_price"] - stocks["initial_value"] stocks["gain_loss"] = stocks["gain_loss"].ro...
141caa895a6d5761e41f0656307c851c64df2df5
34,678
import math def random_mini_batches(X, Y, batch_size=64, seed=0): """ Creates a list of random minibatches from (X, Y) Arguments: X -- input data, of shape (number of examples, input size) Y -- true "label" vector of shape (number of examples, number of features) batch_size -- size of the min...
ee6eec6d90a61f33c44fa01ced15e9a718a4a58e
34,679
def stelab(pobj: ndarray, vobs: ndarray) -> ndarray: """ Correct the apparent position of an object for stellar aberration. https://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/stelab_c.html :param pobj: Position of an object with respect to the observer. :param vobs: Veloc...
ebdead6d87c4f916afcca8897758fb189fa4a58a
34,680
import tqdm import torch def train(train_loader, model, args, optimizer, scheduler, epoch, device, writer=None): """Train for one epoch on the training set""" # switch to train mode model.train() print('\nEpoch: %d' % epoch) train_loss = 0 total = 0 correct = 0 for j, (input,...
55f25cf0d7ed93a973443442ad93ba5ed0eea0ba
34,681
def add_noise(input_image, noise, multiple_image_std, size=224): """Transformation of a single image by adding noise. If a random gaussian distribution of noisy is specified (noise='r_normal'), the standard deviation of the noise added is based upon the dynamic range of the image weighed by multiple_image_std ...
99f290f498b6abea5d592787ee60a137d805ff33
34,682
def evaluate_topic_models(data, varying_parameters, constant_parameters=None, n_max_processes=None, return_models=False, metric=None, **metric_kwargs): """ Compute several Topic Models in parallel using the "gensim" package. Calculate the models using a list of varying parameters `...
01ad43f2ab07dbbd3c64e2a9bc8ee3b7f5fddfad
34,684
from re import T def n_step_bootstrapped_returns(r_t: T, discount_t: T, v_t: T, targets: T, lambda_t: T, seq_len: int, n: int) -> T: """Computes strided n-step bootstrapped return targets over a sequence. The returns are computed according to the below equation iterated `n` times: Gₜ = rₜ₊₁ + γₜ₊₁ [(1 - λₜ...
ec729b840a47f4d37eff65f5e7c36a7467237fc2
34,685
import requests import json def questions (category, token): """Contacts API and retrieves questions + answers based on category""" # Retrieve questions and answers from API try: response = requests.get(f"https://opentdb.com/api.php?amount=1&category={category}&type=multiple&token={token}") ...
7ff86a66e82dd442fc57b68ac02a7b793336d290
34,686
async def reset_clean_filter_timer(obj): """Reset the Clean Filter indicator timer.""" return await obj["madoka"].reset_clean_filter_timer.update(ResetCleanFilterTimerStatus())
a746aa0ce2527dc3a135c4ab71d8841f133b85bb
34,687
def getFigureSpec(iteration: int, perceptual: bool): """ Get 2x2 Figure And Axis Parameters ---------- iterations : int perceptual : bool If true, generate the axis of perceptual loss Return ------ fig, axis : matplotlib.figure.Figure, matplotlib.axes.Axes The plott...
2003ce5d4ddfa316ba5bd56bfb5150d9c96b96ab
34,688