content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def build_query(filters, page, request): """ Construye el query de búsqueda a partir de los filtros. """ return filters.buildQuery().order_by('nombre').filter(ambito__path__istartswith=request.get_perfil().ambito.path)
ef04c8b3f9e04b7babe24ee7cbe56fd35402f44e
3,602,199
def json_response(status_code: HTTPStatus, detail: str, body: str) -> JSONResponse: """json response from status, detail & body :param status_code: http status code :param detail: exception name in detail :param body: error stacktrace :return: JSONResponse object """ return JSONResponse( ...
43d0b199c5ff78a0c3eeb4ee1e547715e886fbc6
3,602,200
import requests def request_hk(url,path): """获取恒生指数与恒生国企指数PE""" response = requests.get(url) df = pd.DataFrame(response.json()) df = df.fillna('') if not df.empty: df.columns = ['trade_date','PE','close'] df.to_csv(path,index=False) else: df = None return df
bba2c1b678d82252dcca5de61ac035629b41f665
3,602,201
def aff_trans(matrix, points): """Affine transform a 3D set of points""" if not matrix.shape == (4,4): raise ValueError("Matrix needs to be a 4x4 array") if points.shape[1] == 3: transpose = True points = points.T else: transpose = False p = np.ones((4, poin...
9e206a113886a552ea062e6be9145c0e9e23c540
3,602,202
def make_null_mask(array): """Given a numpy array, return a numpy array of int64s containing the indices of `array` where the value is either invalid or null. Invalid values are: - None - numpy.nat - numpy.nan Args: array (:obj:`numpy.array`) """ mask = [] ...
f3511370a89e2575268392895ee98287422dffe5
3,602,203
def _tf_while_stmt(test, body, init_state, opts): """Overload of while_stmt that stages a TF while_stmt.""" if opts is None: opts = {} return control_flow_ops.while_loop(test, body, init_state, **opts)
9d32518f47ae4a043f313e7bc4f9d837daef62f9
3,602,204
def get_patch( image: np.ndarray, size: int, stride: int, patch_index: int ) -> np.ndarray: """ Returns a single patch from the input image. The patch index should be a number in the interval [0, patch_count). Patches are numbered in row-major ordering. Patch 0, ..., <# of patch columns> is on ...
d68215dcc9725fb0e70593bc302a8ce05155af94
3,602,205
def modified_bisection(f, a, b, eps=5e-6): """ Function that finds a root using modified Bisection method for a given function f(x). On each iteration instead of the middle of the interval, a random number is chosen as the next guess for the root. The function finds the root of f(x) ...
54903a6c1fbe7bfabba43ada92df8b15360f098c
3,602,206
def _range_checker(ip_check, first, last): """ Tests whether an ip address is within the bounds of the first and last address. :param ip_check: The ip to test if it is within first and last. :param first: The first IP in the range to test against. :param last: The last IP in the range to test again...
924e617374fdbc4cabc28cb18e63c45192da3b4c
3,602,207
def get_pressed(joystick, button): """ Return whether or not a joystick button is pressed, or :const:`False` if the requested joystick or button does not exist. Arguments: - ``joystick`` -- The number of the joystick to check, where ``0`` is the first joystick, or the name of the joystick to...
507457ba44412986e90084b5588bc0b1c0e9b267
3,602,208
def ndcg_score(y_true, y_score, k=10, gains="exponential"): """Normalized discounted cumulative gain (NDCG) at rank k Parameters ---------- y_true : array-like, shape = [n_samples] Ground truth (true relevance labels). y_score : array-like, shape = [n_samples] Predicted scores. k...
8a1eef843f3f1ac2c2b258c4c6c2cf88a9bfb4e0
3,602,209
import tqdm def _copy_file_list_internal(file_list, message, callback): """ Takes a list of tuples (src, dest, size) and copies the data in parallel. Returns versioned URLs for S3 destinations and regular file URLs for files. """ if not file_list: return [] total_size = sum(size for _...
406134569e45581218aa120fcfb3f7e2bb79d5c4
3,602,210
import logging import collections def file_based_convert_examples_to_features(examples, label_list, max_seq_length, tokenize_fn, output_file, ...
4e3b7e1fcaa94dbd832afbe8c164ee2caa6b89c7
3,602,212
def _build_signatures(graph: tf.Graph, signature_def_map: dict) -> dict: """ Turn a signature map into a proper argument for ``add_meta_graph`` by creating tensor info for each output name given in ``signature_def_map``. Args: graph: TF Graph instance signature_def_map: Dictionary that ...
d212e6e759387676000d15434b27f32535f51ba6
3,602,213
def config_section_data(): """Produce the default configuration section for app.config, when called by `resilient-circuits config [-c|-u]` """ config_data = u"""[fn_urlhaus] url=https://urlhaus-api.abuse.ch/v1 # these are needed for submitting malware urls submit_url=https://urlhaus.abuse.ch/api/ # ...
ae09bac3b31cef4b7a6204b1baa1886b6457498d
3,602,214
def optional_nrrdvector(inp): """Parse a vector from a nrrd header that can also be none.""" if (inp == "none"): return inp else: return nrrdvector(inp)
1f98c1bf43c5de3a3bf6e22a7b7d7d70bbc88328
3,602,215
def crr_m(ksigma, msf, crr_m7p5): """Cyclic resistance ratio corrected for m_w and confining stress""" return crr_m7p5 * ksigma * msf
76b271ac72b29ec583aa8a23aeb22e8dbf248365
3,602,216
import re def concatenate_lines(lines, pattern): """ concatenate lines >>> import re >>> pattern = re.compile(r"(^\s+)(.+?)") >>> lines = [u"a", u" b", u" c", u" d", u"e"] >>> concatenate_lines(lines, pattern) [u'a', u' b c d', u'e'] >>> lines = [u"a", u" b", u" c", u" d", u"e"] >>> ...
eb21d40771d16d33754aceab106770c8047a83fa
3,602,217
def median_polish_group_wise(data:NDFrame, rtol:float=1e-05, atol:float=1e-08) -> NDFrame: """Apply Median polish group-wise. Args: data (NDFrame) : Input data. Shape = ( ``n_samples``, ``n_features`` ) rtol (float, optional) : [description]. Defaults to ``1e-05``. atol (float, ...
5b962b6757e8f6cd04f77c32fb35a2a19f80f241
3,602,218
def _is_value(v): """ Returns True if the given value is a @value. :param v: the value to check. :return: True if the value is a @value, False if not. """ # Note: A value is a @value if all of these hold True: # 1. It is an Object. # 2. It has the @value property. return _is_object...
9c2b46677f9734cc6c78a5c0068ea3ed833382b7
3,602,220
import zlib def get_message(conn, deco): """ Handle a received TCP message, synchronously reading it to completion. Argument: conn TCP connection Argument: deco ZLIB decompression object Return: updated decompression object in the case where compression was reset """ ...
643d4f98b553cd510b9cd99caaab414c82aaf29b
3,602,221
def collapse_taxa(feature_table_artifact, taxonomy_artifact, collapse_level="asv"): """ Collapse feature table to user specified taxa level (ASV by default). Input: - QIIME2 artifact of type FeatureData[Taxonomy] Returns: - pd.DataFrame (taxa/ASV as rows, samples as columns, numeric index, appends 'Taxon' ...
872a1a0629bf8e81c6fdc59f98edfc8109a4ca30
3,602,223
from bs4 import BeautifulSoup def parse_words(html): """解析 html 源码,返回汉字列表""" soup = BeautifulSoup(html) a_list = soup.find_all('a', attrs={'target': '_blank'}) return [x.text for x in a_list if x.text]
629ccc8be01699ea747061c3340772569109d109
3,602,226
import attr def stacked(graph): """Turn a graph into a stacked graph.""" return attr.assoc( graph, lineWidth=0, nullPointMode=G.NULL_AS_ZERO, stack=True, fill=10, tooltip=G.Tooltip( valueType=G.INDIVIDUAL, ), )
fcdf6c8a6df0dbda16f3cd4f32ae1b548ce3946f
3,602,227
def DeconvolutionalBlock( kernel_size=(2, 2), activation=None, padding="valid", strides=2, normalization=False, norm_kwargs={}, **kwargs, ): """A single 2d deconvolutional layer. Accepts arguments of keras.layers.Conv2DTranspose. Parameters ---------- kernel_size : int ...
a6d2e53edb84b7d00b9180c7ad53cdd264ff0b59
3,602,228
def SSLChannels_ATR(dataframe, length=7): """ SSL Channels with ATR: https://www.tradingview.com/script/SKHqWzql-SSL-ATR-channel/ Credit to @JimmyNixx for python """ df = dataframe.copy() df['ATR'] = ta.ATR(df, timeperiod=14) df['smaHigh'] = df['high'].rolling(length).mean() + df['ATR'] ...
3adeb4d37b84c453b4f559afa115c669244fcd88
3,602,229
def translate_status(sbd_status): """Translates the sbd status to fencing status. Key arguments: sbd_status -- status to translate (string) Return Value: status -- fencing status (string) """ status = "UNKNOWN" # Currently we only accept "clear" to be marked as online. Eventually we...
2274ff63aea9249cecacf455598a57fba1245ace
3,602,230
def format_generic_number(event_value, attribute): """ Creates a filter format string for a generic number attribute. :param str event_value: String that is used to generate the filter string. :param str attribute: The attribute that is used in the filter. :return: A string that can be used in a LQ...
eb27e70aa5b2b0dff5ff0428c3e84a6320fa3c9d
3,602,231
from typing import cast def is_null_ptr(p) -> bool: """[Internal] Return if the passed pointer is NULL""" return not cast(p, c_void_p).value
8a0bce41ebe2aacd984e408f4add4ccecbe27b26
3,602,233
def MergeFilesCoverageDataForPerCL(a, b): """Merges coverage data files for per-cl coverage data. The original data includes 'uncovered blocks', but this merge function drops it because it's non-trivial to merge them, and it won't be useful at all unless Gerrit decides to support displaying them, and it's stil...
2332df9adcfa8a1c9debe25f6543df44015ec027
3,602,234
def subset_multidimensional_raster(input_multidimensional_raster, variables=None, dimension_definition='ALL', dimension_ranges=None, dimension_values=None, ...
980a4fa7309ebaac1c6ef042317728edb15189a7
3,602,235
def html_confirmation_email(confirmation_link: str): """ render template for email to confirm email address :param confirmation_link: link with token created by itsdangerous :return: rendered email html for email confirmation """ return render_template("emails/confirm_email.html", confirmation_l...
6becc3235d6615027fdc6e4f1ec900f7f3cd9009
3,602,236
def get_computation_matrix(a, copy_bcm=False, check_col_vector=False, return_ndim=False, isVector=False): """get_computation_matrix""" if not isinstance(a, FrovedisBlockcyclicMatrix): if type(a).__name__ == 'matrix': ...
d7052a6f69c2c6b67012d80ee82136f27f551913
3,602,237
def indentedBox(widget, sep=20, orientation=Qt.Vertical, **misc): """ Creates an indented box. The function can also be used "on the fly":: gui.checkBox(gui.indentedBox(box), self, "spam", "Enable spam") To align the control with a check box, use :obj:`checkButtonOffsetHint`:: gui.hSlider...
52f7fac4b534c01d0076b36b86306ab95936e24f
3,602,238
def toggle_mode(request): """ Toggles between Tetris/grid. """ session_check = _check_session_valid(request) if session_check: return session_check request.session["analytics"].toggle_mode() return JsonResponse({})
6f1abf6507b5ab0f364009e88679a75d74c25f34
3,602,239
def theta_k(circumbody,k=0,i=0): """ This is from the Section 4 of the paper [Sadraddini and Tedrake, 2020]. Inputs: * AH-polytope: ``circumbody`` * int ``N``: the number of columns added to the subspace of ``U``. For more information, look at the paper. *Default* ...
237673dd600ca4def26ce9f8ece9b7a39b1b5126
3,602,240
def hybridization(atom: Atom) -> HybridizationType: """Hybridisation (HybridizationType). """ return atom.GetHybridization()
011762f6745daeb0e094d2de84a9cff6d3d88bba
3,602,241
import time def yolo_eval(yolo_outputs, anchors, num_classes, image_shape, score_threshold=.5, iou_threshold=.45): """ Obtain predicted boxes axis and corresponding scores Args: yolo_outputs: output (3 feature maps) of YOLO V3 model, sizes are 1*13*13*18; 1*26*26*18; 1*52*52*18 seperately ...
755cb87380ba252bb6843e6dfdf87e5d2e397a8d
3,602,242
from pathlib import Path def get_js_libs_from_yaml(): """ Get all npm package names from the /udfs/js_libs/js_libs.yaml file. :return: dict representation of the js_libs.yaml file """ js_libs_yaml_path = Path('./js_libs/js_libs.yaml') if js_libs_yaml_path.is_file(): with open(js_l...
dcd8d56dc80e097227ca89661ececcdbabf94b3a
3,602,243
def create_resource( resource: "definitions.Resource", namespace: str = None, echo: bool = False ) -> ResponseInfo: """...""" try: status = resource.create_resource(namespace) response = ResponseInfo(resource, "+", "Created", status=status) except ApiException as error: response ...
55e11d595c4bfb012e732ee205c21a78ee57d36f
3,602,244
def _get_locations(request): """ Get's the user desired location from the query Args: request (Request): contains info about the conversation up to this point (e.g. domain, intent, entities, etc) Returns: list(string): resolved locations entity """ return [e for e in re...
9e6c4d642053cfaa5120fb8fa020020f3f724193
3,602,245
def register_functions(prefix): """Construct a dict of certain functions defined in a module. This lets scripts that import the module access these functions dynamically using a dict rather than using getattr messiness, importlib (which makes imports invisible to htools requirements.txt builder), or eva...
c702c326874e96538e85e31e4c46608f267f6111
3,602,246
def moving_average_exp(input, n_points): """ Calculate Exponential Moving Average Paremeters: input: ndarray input signal n_points: int numbers of moving average points Returns: result: ndarray moving-averaged signal """ alpha = 2.0 / (n_points...
acd3035e1e6dd25f76453eeab0c3730be70bef4b
3,602,248
def whitelist_add(request): """ API endpoint to add a whitelist item """ user = request.user success = False errors = {} data = None _type = request.POST.get('form_type', None) if request.POST and request.is_ajax(): if _type == "whitelist": url = request.POST.ge...
708da564a67c137db37739c632337b635c29cfc4
3,602,249
def version(*names, **kwargs): """ Common interface for obtaining the version of installed fileset/rpm package. CLI Example: .. code-block:: bash salt '*' pkg.version vim salt '*' pkg.version foo bar baz """ return __salt__["pkg_resource.version"](*names, **kwargs)
8b5bbf766119614b43485378530688b5c2aef6aa
3,602,251
import itertools def generate_transitions_dictionary(education_levels): """build a lookup table for next education targets Example frame looks like.. ETH.group,MB.0,M0.1,M1.2,...,M98.99,M99.100,M100.101p,FB.0,F0.1,F1.2,...F98.99,F99.100,F100.101p BAN,Less than GCSE, BAN,GCSE, BAN,CSE, BA...
b47018d0701f5674724d01a708a099fc34012044
3,602,252
import math def entropy(data): """ Calculate informational entropy. """ entropy = 0.0 frequency = {} for instance in data: p_instance = int(round(instance/5) * 5) if p_instance in frequency: frequency[p_instance] += 1 else: frequency[p_instance] ...
4b96c229e4cc0318a764990569d2951003447a72
3,602,253
def get_transformed_bounds(img, transform): """ Returns the transformed bounds of an image, after applying the given affine transformation. Two points are returned: the new origin of the image and the new diagonal. Their coordinates are relative to the original origin point. """ maxX, maxY = img.sh...
cb40ebeb2771c52198ea3fc6e1dd0404a7e1f4ca
3,602,254
def rate_scheduler(lr=.001, decay=0.95): """Schedule the learning rate based on the epoch. Args: lr (float): initial learning rate decay (float): rate of decay of the learning rate Returns: function: A function that takes in the epoch and returns a learning rate. ""...
5808da433b8752921551c8149346374d83634461
3,602,256
def get_pdb_data(pdb, data_dir="", assembly=1, skip_download=0): """Function to get atom coordinates and atom/residue metadata from pdb structures. Args: pdb (str): pdb ID data_dir (str): path to pdb directory assembly (int): 0/1 indicator of whether to use biological assembly or ...
59dfc3e3fb7e57966939c6949fa1d4c1ca51d9e2
3,602,257
def _compute_initial_position_alt_2(A, a, B, b): """ This is an alternative implementation to _compute_initial_position using Rainer's line of thought. """ rows = cols = (0,1,2,3,6) AL = A[rows,:][:,cols] BL = B[rows,:][:,cols] AR = np.array([ [ 0, 0, 0, 0], [-1, 0, 0, ...
e76ea795febb90bd78221bafe5f29b31d85ca8b2
3,602,258
from re import TEMPLATE def get_workbook(args): """Load the excel workbook from the template and set initial data.""" wb = openpyxl.load_workbook(TEMPLATE) cover = wb["Cover"] cover["E13"] = args.name cover["E14"] = args.tax_ref cover["E15"] = args.year summary = wb["Summary"] summary[...
208d7b8b230e393766330ac058333c8a34432cb0
3,602,259
def _set_options(options): """Sets default options if none are given""" if options is None: # Set defaults options = '' if SHOW_HOST_NAMES: options += 'show_hostnames,' return options
97ee0d9f3639144e8c2e92ebdcd6353097e997b1
3,602,260
def get_dsproc_logger() -> Logger: """Attach the logger of this module""" return get_default_logger('DSProc')
e30be30daac005f6ec87ed6cb57f49cd118fddf4
3,602,261
def tsp(edges, time_limit=5, concorde=False, precision=0) -> list: """Compute TSP solution Args: edges (list): List of tuple (source, target, weight) time_limit (int, optional): Time limit to run. Default to 5 seconds. concorde (bool, optional): Shall we run concorde? Defaults to False....
9b9fa8470d523c375b6853cc168a194351f5b0a3
3,602,262
import jinja2 def check_template(template_string): """ Check the syntax of a template. Return an error tuple (line number, message) if the template is invalid or None if it is valid. """ try: jinja2.filters.FILTERS['multi_sort'] = multi_sort jinja2.Template(template_string) exc...
08281ecab5e2acd4d63a1a6dbe181477288cc1fb
3,602,263
def _GetPseudoAAC1(ProteinSequence, lamda=10, weight=0.05): """ ####################################################################################### Computing the first 20 of type I pseudo-amino acid compostion descriptors based on [_Hydrophobicity,_hydrophilicity,_residuemass]. #################...
cd1b83b3c4cc8b7c60b9460c8f4bedafb066bb25
3,602,264
def plot_scatter(ax, prng, nb_samples=100): """Scatter plot.""" for mu, sigma, marker in [(-0.5, 0.75, "o"), (0.75, 1.0, "s")]: x, y = prng.normal(loc=mu, scale=sigma, size=(2, nb_samples)) ax.plot(x, y, ls="none", marker=marker) ax.set_xlabel("X-label") ax.set_title("Axes title") re...
02f23849ed4f2dded875866027eead00ebd1f0dc
3,602,265
def findGlobals(pool_name, auth_identity, classad_type, additional_constraint=None): """ Query the given pool to find the globals classad. Can be used to query glidefactoryglobal and glidefrontendglobal classads. """ status_constraint = '(GlideinMyType=?="%s")' % classad_type # identity checki...
0def2bcb7a7a48bb98b4c4948a3ff5760562fe21
3,602,268
def getBestReinforcement( user: User, mine: Game, maxPrice: Tus, teamConfig: ConfigTeam = None, lootingOrMining: TeamStatus = None, ) -> CrabForLending: """ Find best crab to borrow for the given mine and at the given max price, using the first suitable Reinforce strategy provided in the...
f2f7ab28d5c168396e2d643274ea80bed248dfb1
3,602,269
def do_or(node: Node) -> bool: """ Evaluate the value of an OR expression. Parameters ---------- node The ast representing an or expression. Returns ------- bool The expression's evaluated value. """ return any((visit_tree(child) for child in node.children))
38059b61e032d07e146cd26c1d840fb4cb2bd6ac
3,602,270
def create_db_from_files(files, database_name=":memory:"): """Creates a database with the data extracted for a list fo files. The file must be an estimators.dat-type file. A new database is created. The database is created in memory if no database_name is provided. Parameters ---------- filen...
5d3be702c53a9cef4e4c9f6e3db59cb18ce9aca2
3,602,271
def s2c_stereographic(sph): """ Stereographic projection from the sphere to the plane. """ u = sph[..., 0] v = sph[..., 1] w = sph[..., 2] return (u + 1j*v)/(1+w)
1aff6cf6accd6bb26c647f014dc964404e84b979
3,602,272
def compute_param_matrix(parameters, t): """Calculate all the possible parameters for a set of search values Parameters ---------- t : nd vector time vector from the data Returns ------- generator each iter returns a tuple of 2 (gaussian) or 3 (gamma) values tuple of 2 ...
48e75e6307c98d74bb89e9694f42b844c126bcd6
3,602,273
import time def simulation(models: dict, ts_data: SimulationDataset, retrain_frequency: int): """Run one portfolio simulation over the input DataFrame. :models: Dictionary of ("Model Name", "Model Object") key-value pairs. Will look for "Model Name".pkl files to load pre-trained models. :ts_data: DataFram...
cf1ee477317efb4366a40956beeb9115b85852a4
3,602,276
def text(node): """ Get all the text of an Etree node Returns ------- str """ return ''.join(node.itertext())
f5000a6220da74059230a499dc2b48057e5c4ada
3,602,277
def periodic(x, axis, depth): """ Copy a slice of an array around to its other side Useful to create periodic boundary conditions for overlap """ left = ((slice(None, None, None),) * axis + (slice(0, depth),) + (slice(None, None, None),) * (x.ndim - axis - 1)) right = ((sli...
71713988cab28cfa04f711f4f0887b8a134e176b
3,602,278
def plot_results(results, plot_order, method_legend_colour_marker_dict, x_label, y_label, x_bounds=None, y_bounds=None, to_plot_legend=True, true_maxval=None, outlier_frac=0.0, plot_title=None, options=None): # pylint: disable=too-many-arguments """ Plots the results using Matp...
c4fe18dec7c28cd8cd821714515d2636c71791b9
3,602,279
import yaml def update_metadata(workspace_path, profile, verb, new_data=None, no_init=False, merge=True): """Update the catkin_tools verb metadata for a given profile. :param workspace_path: The path to the root of a catkin workspace :type workspace_path: str :param profile: The catkin_tools metadata...
7577fe9c2a0d9ae79628de0b38a52a603c5c07c8
3,602,280
from typing import Union from typing import Callable def fully_qualified_name(thing: Union[type, Callable]) -> str: """Construct the fully qualified name of a type.""" return thing.__module__ + '.' + thing.__qualname__
eacbffdcda78fa38667af0b9d7bc0c53c2fbdb1f
3,602,281
def remove_whitespace(text): # type: (str) -> str """strips all white-space from a string""" if text is None: return "" return "".join(text.split())
747538de63b11e49d498b2f4ccb8286975019ec8
3,602,282
def draw_at_bottom_left_of_raft_number_float(img_bgr, rafts_loc, neighbor_count_wt, num_of_rafts): """ write a subscript to indicate nearest neighbor count or weighted nearest neighbor count """ font_face = cv.FONT_ITALIC font_scale = 0.5 font_color = (0, 165, 255) # BGR font_thickness = 1 ...
aa32e138693ca299a31b50f78332d765aab96614
3,602,283
def sol(board): """ Plain backtracking, find which cell is empty and assign the number. Return on first True """ row, col = None, None row, col = findEmptyCell(board) if row == None and col == None: # Careful about using 'not row' return True for num in range(1, 1...
824ddcc27372d70c3d31eb7d9a5b72dc9eb9521a
3,602,285
import re def address_line1(a): """Return only the main part of a multipart address Warnings: - Only works on canonicalized addresses. Call canonicalize() first. - Returns addresses that are incorrect! - Only use the output of this function for fuzzy matching. >>> address_line1('1910 south m...
453e68ed2889e899ef339def772191c32f7997bc
3,602,286
from typing import Dict def _invert(mapping: Dict) -> Dict: """Invert dictionary {k: v} -> {v: k}.""" return {target: source for source, target in mapping.items()}
013894d56e95a5df273a5bed6a7acc9c49c18d10
3,602,287
def multilabel_sample( y_labels: npt.ArrayLike, size: float or int = 1000, min_count: int = 5, seed: int = None, ) -> npt.NDArray[np.int_]: """ Takes a pd.DataFrame or np.ndarray matrix of binary labels `y_lables` and returns sorted np.ndarray of indices for the sample of size `size` if ...
aa84d31bd21342d5e770d534b8ccd8546e0fa655
3,602,288
def near_edge(img, contour): """Check if a contour is near the edge in the given image.""" x, y, w, h = cv2.boundingRect(contour) ih, iw = img.shape[:2] mm = 80 # margin in pixels return (x < mm or x + w > iw - mm or y < mm or y + h > ih - mm)
d4c2aa20dbec1ff89020c509e27ea28077397e53
3,602,291
def convert_to_radians(value): """method converts an individual value to radians""" try: return value * pi / 180 except: print('An unexpected error occurred! Please try again.') exit()
59659cd52acdb5af9ea87979be68861adb6f3d0b
3,602,292
from typing import Optional from typing import Tuple def result_with_template(fun, **results: Optional[TelQueryResult]) -> Tuple[ClauseElement, ClauseElement]: """ Apply the function to each result's `.sql` and `.template`, returning a tuple of both results. :param fun: function accepting as many ClauseEl...
86cfc9362200ee3003a26918e06c95050da71257
3,602,293
import torch def greedy_decode(model,bert,tokenizer, sent,glyph2ix, pinyin2ix,pos2ix, ix2glyph,device): """ Generate a Couplet Sentence through Greedy Approach Output dimension is glyph dim. return in list format e.g.(['1','2','3']) """ ...
8d50a9cd2a4b8f1a5b343170044783ff05eac8fc
3,602,294
def _process_rget_with_transform(func, ignore_errors=False): """Post process the JSON result (if successful) with F(json_d) -> T""" def wrapper(total_url, headers=None): j = _process_rget(total_url, ignore_errors=ignore_errors, headers=headers) return func(j) return wrapper
3f31cb677d25c57b9e8f569178dd2d4e2df14e47
3,602,295
def test_case(request, user_test_id, test_id): """ Shows information about test before user could start it. Check if test is exists and available for current user (@return(option 1)). When user starts test (@return(option 2)): - if test has time limit add to request.session expire time (if not exis...
66742d41b7bc5ef1984779541946cd9bf1e22a02
3,602,296
from typing import Dict from typing import Any def flatten_array(arr: jnp.ndarray, shape: Dict[str, Any]): """Flatten array.""" s = shape assert arr.shape[-len(s['shape'] ):] == s['shape'], f'{arr.shape} incompat {s["shape"]}' arr = arr.reshape(arr.shape[:-len(s['shape'])] + (s['size'],...
c0e1b314c5b999388f7470efd5afa104878b1c3b
3,602,297
def mock_role_form_data(model, data): """ In order for form to don't fail submission, all permission fields need to receive values. This function populates data dict with default values for permissions, making form validation pass """ for form in get_permissions_forms(model): for field i...
0b79aa35dc2275a81d6dc8628c549b7faed169d0
3,602,299
import warnings def plugin(version: str): """See `https://mypy.readthedocs.io/en/latest/extending_mypy.html`_.""" if float(version) < 0.7: warnings.warn( "This plugin not tested below mypy 0.710. But you can" f" test it and let us know at {ISSUE_URL}." ) return JSON...
7f770cf1ae9ceeb8e55f795390f9f3f9532b213b
3,602,300
def kd(*a): """ Dump pointers and symbols at the specified address. """ return pwndbg.commands.telescope.telescope(*a)
f14408c044baf7dcb378a5ee56a0650d6357cba3
3,602,301
def Logout(request): """ List all code snippets, or create a new snippet. """ logout(request) return Response({"status":"user logged out"})
d6757df2ec17d74dc063dcda9d0f1982d36bc915
3,602,303
def copy_request_to_notice(doc_change_id): """ Copy all stakeholders from request to notice. :param doc_change_id: :return: """ # Get stakeholders to copy stakeholders = Request.query \ .filter(Request.doc_change_id == doc_change_id) \ .with_entities(Request.doc_change_id, ...
fbffd158c177f40b6470b119e0d5c4e565fbfcb1
3,602,304
async def flow_id(): """ 1 -> 2 -> 3 -> 4 -> 5 \ / 7 -> 8 -> 9 -> 10 / 6 """ t1 = prefect.Task("t1", slug="t1") t2 = prefect.Task("t2", slug="t2") t3 = prefect.Task("t3", slug="t3") t4 = prefect.Task("t4", slug="t4") t5 = prefect....
c51e39f62b00f58be66455d04bca224f1700d756
3,602,305
def check(requirements_paths=[], metadata=[], projects=[]): """Return True if all of the specified dependencies have been ported to Python 3. The requirements_paths argument takes a sequence of file paths to requirements files. The 'metadata' argument takes a sequence of strings representing metadata. ...
343d5f7c5b07fdd720d904b4ac48994039085314
3,602,306
def _options_handler(request): """Request handler for OPTIONS requests This is a request handler suitable for return from _get_handler_for_request. It returns a 200 and an empty body. Args: request (twisted.web.http.Request): Returns: Tuple[int, dict]: http code, response body. ...
319b083565551f2512a71bb671dd76cfd76063dc
3,602,307
def Smooth121(v, sdims, NSmooths= 1, perdims= []): """ Applies [1 2 1]/4 stencil in multiple dimensions Usage ----- Smooth121(DataArray,list1,Nsmooths=int1,perdims=list2) name : xarray.DataArray - e.g., ds.var list1: list of dimensions over which to smooth - e.g., ['Y','X'] ...
9b2ccef223defe1d4caaaf9d982109907998c805
3,602,309
def kind(event): """ Finds the type of an event :param event: the event :return: the type of the event """ return event.type
68f0170eac9fc06f954542769dcd0d4ef974e725
3,602,310
def get_entities_by_kind(membership_cache=None, is_active=True): """ Builds a dict with keys of entity kinds if and values are another dict. Each of these dicts are keyed off of a super entity id and optional have an 'all' key for any group that has a null super entity. Example structure: { ...
c5307c7ac5b27bbbbb7e6ba7a78fb34e8f191cc5
3,602,311
def pontoon_js_url(request): """ Inserts a context variable PONTOON_JS_URL from settings """ return {'PONTOON_JS_URL': getattr(settings, 'PONTOON_JS_URL', None) or "https://pontoon-dev.mozillalabs.com/en-US/static/" "js/project/pontoon.js"}
2ff3253c2860f327730c0a2b66f34a12fc4884c5
3,602,312
def extensions(app): """ Register 0 or more extensions (mutates the app passed in). :param app: Flask application instance :return: None """ # from profile.database import db, migrate db.init_app(app) ma.init_app(app) migrate.init_app(app, db) return None
f0725e7fccefd2bb5e6368829eddd80f9bf81747
3,602,313
from operator import gt def _pad_feature(feature: gt.Field, *, padding_value: gt.Field, target_size: int) -> gt.Field: """Pads a single feature to the target total number of elemenets.""" result = tensor_utils.pad_to_nrows( feature, target_nrows=tf.constant(target_size), padding...
a469906b0001962e5e9dc722e3d5ef2c358cbae0
3,602,315
def YscMatrix(): """(read-only) Complex array of Ysc matrix at bus. Column by column.""" return get_float64_array(lib.Bus_Get_YscMatrix)
62053a6d58842a5b990c93c7bb94d726495a8566
3,602,316
def select(*_): """ Always return None """ return None
9f29559a50440143d9e3fe46be766590516f1fc4
3,602,317
def question_resource(request): """ Secured question API. Only authenticated users have access. Don't allow suspect characters in fields - prevent injections. Permission rules: You can create question only for your current user. Your question will be approved by the administrator. ...
a00f561199a4e5b14be9dd891bb95f92553269c6
3,602,318