content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def files_permission_factory(obj, action=None): """Permission for files are always based on the type of record. Record bucket: Read access only with open access. Deposit bucket: Read/update with restricted access. """ # Extract bucket id bucket_id = None if isinstance(obj, Bucket): ...
6a565d45d2ff404ad4d9c9536c60e0595d131884
50,545
from typing import Optional def _generate_perfect_bst(height: int) -> Optional[Node]: """Generate a perfect BST (binary search tree) and return its root. :param height: Height of the BST. :type height: int :return: Root node of the BST. :rtype: binarytree.Node | None """ max_node_count = ...
f8fa91d06cde895697d515130c0fa17e62e4ba8b
50,546
def create_plotting_parameters_for_normal_distribution(mean, variance, num_std_dev_to_plot=3): """Create parameters to easily plot a normal distribution Arguments: mean {float} -- Mean of the normal distribution variance {float} -- Variance of the normal distribution """ sigma = sqrt(v...
00525affd974b2698661e1009cfb26b5ebd9df70
50,548
def create_skelgraph(R: nx.Graph, H: nx.DiGraph) -> nx.Graph: """Create a "skelgraph" from a bdc world `H` and its reeb graph, `R`. A skelgraph is a graph of the straight skeletons of each cell of a world `H`, joined by the midpoints of each cell wall on `H`. Traversing the skelgraph of `H` means visit...
7dc500e93b8d2a8d8831cd3d9a591466e55ee72c
50,549
def apply_bounds(grid, lVec): """ Assumes periodicity and restricts grid positions to a box in x- and y-direction. """ dx = lVec[1,0]-lVec[0,0] grid[0][grid[0] >= lVec[1,0]] -= dx grid[0][grid[0] < lVec[0,0]] += dx dy = lVec[2,1]-lVec[0,1] grid[1][grid[1] >= lVec[2,1]] -= dy gri...
34411b7cc1062ade4d45c922225a3364a6c84180
50,550
def is_ericsson_2g_supported(): """ Check if Ericsson 2G is supported :return: string parse_and_import_ericsson_2g | ericsson_2g_not_supported """ if bts_utils.is_vendor_and_tech_supported(1,1) is True : return 'ericsson_2g_supported' else: return 'ericsson_2g_not_supported'
fc48a6b18a800ae2795a8c9c333ab5b9cbc96f94
50,551
def check_env_vars(env_vars): """Checks if the env variables are set as required to run the test. Returns: True if all the env variables are set as required, otherwise False. """ if not env_vars: return True for key in env_vars: if env.get_env(key) != env_vars.get(key): return False retu...
70dc52308cfd049df02c16fd39d669398ac64008
50,552
def custom_sobel(shape, axis): """ shape must be odd: eg. (5,5) axis is the direction, with 0 to positive x and 1 to positive y """ k = np.zeros(shape) p = [(j,i) for j in range(shape[0]) for i in range(shape[1]) if not (i == (shape[1] -1)/2. and j == (shape[0] -1)/2.)] ...
cbf93d623c48c6a26a65862d1cdaca3cb25c8706
50,553
def _check(edges): """Check consistency""" res = True for src, dsts in edges.items(): for dst in dsts: if dst not in edges: print('Warning: edges[%d] contains %d, which is not in edges[]' % (src, dst)) res = False return res
e97a72e31fc99fdf35e3302ab7a6216d7cab924d
50,554
def getParserFile(theHelp, theEpilog=""): """ Get a commandline parser with the defaults of the commandline utils and a list of source files. """ parser = _getParser(theHelp, theEpilog) parser.add_argument("FILE", nargs='+', help="Input file") return parser
a93bf7b5c02da6387116e0ea91a1c3acca7b8d74
50,555
import six def from_pci_stats(pci_stats): """Create and return a PciDevicePoolList from the data stored in the db, which can be either the serialized object, or, prior to the creation of the device pool objects, a simple dict or a list of such dicts. """ pools = [] if isinstance(pci_stats, six...
4a5d3ad396b4677462b9cb698506ef8623c5b78e
50,556
def _cloned_intersection(a, b): """return the intersection of sets a and b, counting any overlap between 'cloned' predecessors. The returned set is in terms of the entities present within 'a'. """ all_overlap = set(_expand_cloned(a)).intersection(_expand_cloned(b)) return set(elem for elem in ...
7c7323a736fa2a9cfc45e07a7197c9245f986953
50,557
def validate(number): """Checks to see if the number provided is a valid EIN. This checks the length, groups and formatting if it is present.""" match = _ein_re.search(clean(number, '').strip()) if not match: raise InvalidFormat() get_campus(number) # raises exception for unknown campus ...
efcaf58702eb7b980275185e7723727b60ecc70f
50,558
import math import asyncio async def search(query_expr: str) -> str: """Search issues and PRs, the query_expr is an expression that GitHub search supports such as 'org:some_org label:some_label'.""" response = await _search(query_expr) items = [_map_search_item(item) for item in response.get("items")]...
9944beb2c500fd88ceb8a37a3f82c6bcef2f0350
50,559
import html def view_the_log() -> 'html': """Display the contents of the log file as a HTML table.""" contents = [] with open('vsearch.log') as log: for line in log: contents.append([]) for item in line.split('|'): contents[-1].append(escape(item)) title...
b14ba57767271056e58df7abb33761339399aeed
50,561
def matches_filter(graph, props): """ Returns True if a given graph matches all the given props. Returns False if not. """ for prop in props: if prop != 'all' and not prop in graph['properties']: return False return True
8d53f198b7ad1af759203909a05cd28916512708
50,563
import torch def goal_pred_loss(grasp_pred, goal_batch, huber=False): """ PM loss for grasp pose detection """ grasp_pcs = transform_control_points( grasp_pred, grasp_pred.shape[0], device="cuda", rotz=True ) grasp_pcs_gt = transform_control_points( goal_batch, goal_batch.shape[0], device="cuda", ...
617a1c2c563e0fdafb4d1281093da2503df820d3
50,564
def biweight_midvariance(a, c=15.0, M=None, axis=None, eps=1e-8, niter=1): """ Copyright (c) 2011-2016, Astropy Developers Compute the biweight midvariance for an array. Returns the biweight midvariance for the array elements. The biweight midvariance is a robust statistic for determining ...
19099001dedba03d6560acb172fa5bfa7d1ffcec
50,566
def card_dealer(cards_dealt, players=1, deck="standard", decks_number=1): """ This function return randomly dealt cards for defined number of players. Args: * `cards_dealt` : number of cards for each player (int) * `players` : number of players Kwargs: * `deck` : options are: * `st...
dd86dc8bbb7ede5a10f8ab75d08e4fd42af196a9
50,567
import json def vulndata(note, parsed_cpe, cve, namelen): """project vulndata object""" data_id = md5( f'{note.host.address}' f'|{note.service.proto if note.service else None}' f'|{note.service.port if note.service else None}' f'|{cve["id"]}'.encode() ).hexdigest() da...
00cdfb44daa80b7d149969746197f79997bfcdec
50,569
def plane_face_intersection(a,b,c,d,face): """ Finds the intersection line of a plane with the face of a solid. Returns the two points that make up the line of intersection. a,b,c,d are the coefficients of the plane ax+by+cz=d while face is a sequence of points which form the plane. args:...
2a731eeee51745bde9fa39bf992ac3085e5845fa
50,570
import requests from bs4 import BeautifulSoup def url2table(url): """From an url given, extract only the 'rangkingTable' using beautifulsoup""" logger.info('url2table') response = requests.get(url) page_html = response.text soup = BeautifulSoup(page_html, 'html.parser') rangkingtable = soup.fi...
326a7ece3cf6bb45688c3cb5aeef4dc5c689442a
50,571
def max(msg, out): """Builtin reduce function that aggregates messages by max. Parameters ---------- msg : str The message field. out : str The output node feature field. Examples -------- >>> import dgl >>> reduce_func = dgl.function.max(msg='m', out='h') The ...
2dc11960e2241b9fdb68ce0a524ba193695f8cf8
50,572
def get_popularity(obj, region=None): """ Returns popularity value for the given obj to use in Elasticsearch. If no region, uses global value. If region and region is not mature, uses global value. Otherwise uses regional popularity value. """ return _property_value_by_region(obj, region=r...
5d66c573fe4b97891c2a266b0ae508fec9abb35e
50,573
def feature_importances_plot(model, labels, **kwargs): """ Calcola l'importanza normalizzata delle variabili di un modello restituendo i dati e mostrando il plot. ----------- Parametri: model : modello di scikit-learn labels : list | np.array lista delle labels delle variabili ...
fd3486eb3e0d7b1a56a1f68c14c9ff0abe21ecdb
50,574
from typing import List from typing import Any from typing import Union import re def human_sort_key(key: str) -> List[Any]: """ Function that can be used for natural sorting, where "PB2" comes before "PB10" and after "PA3". """ def _convert(text: str) -> Union[int, str]: return int(text) ...
31c163250f5b040b18f3f2374825191ce3f61ff4
50,575
def ParseColSpec( col_spec, max_parts=framework_constants.MAX_SORT_PARTS, ignore=None): """Split a string column spec into a list of column names. We dedup col parts because an attacker could try to DoS us or guess zero or one result by measuring the time to process a request that has a very long colum...
8bc1ff31ea5ed2e8ef58bc1d97f3d0109f55ff6d
50,577
def get_class(class_string): """ Returns class object specified by a string. Arguments: class_string -- The string representing a class. Raises: ValueError if module part of the class is not specified. """ module_name, _, class_name = class_string.rpartition('.') ...
a25573ac9cb6115e0b8ad1d28a286f86628d8235
50,578
import hashlib def flip_bloom_filter(string: str, bf_len: int, num_hash_funct: int): """ Hash string and return indices of bits that have been flipped correspondingly. :param string: string: to be hashed and to flip bloom filter :param bf_len: int: length of bloom filter :param num_hash_funct: in...
c245637b86cc16b68d069bf2359b1e5c7483a8fc
50,579
def multiclass_metrics(pred, gt): """ check precision and recall for predictions. Output: overall = {precision, recall, f1} """ eps=1e-6 overall = {'precision': -1, 'recall': -1, 'f1': -1} NP, NR, NC = 0, 0, 0 # num of pred, num of recall, num of correct for ii in range(pred.shape[0]): pred_ind = n...
c8394e2240be1734e387774e4a2bad0620ad4b94
50,580
def positionLogicPlan(problem): """ Given an instance of a PositionPlanningProblem, return a list of actions that lead to the goal. Available actions are game.Directions.{NORTH,SOUTH,EAST,WEST} Note that STOP is not an available action. """ walls = problem.walls width, height = problem.getWi...
c57bb84ff0ddd1a54648b507358d13adbce79f70
50,581
from typing import Any def dataset_from_csv(csv_path: str, **kwargs) -> Any: """ Load dataset from a CSV file using Pandas. kwargs if any are forwarded to the `pandas.read_csv` function. Parameters: csv_path (str): Path of the CSV file to load dataset from. Returns: A...
4f950bc32137861a2a7a556ab6167b5d7b324611
50,582
def quick_sort(array, left: int = 0, right: int = None): """ Quick sort algorithm. :param array: the array to be sorted. :param left: the left index of sub array. :param right: the right index of sub array. :return: sorted array >>> import random >>> array = random.sample(range(-50, 50)...
11b97e008ac9e108a9aac77462fe9f093876c2c4
50,583
def calc_class_metrics(all_preds, all_labels, metric_type="group", span_type="exact"): """ Calculates a set of metrics for each class. :param all_preds, all_labels: A list of list of groups. If metric_type == "joint", the groups should in joint form with an "entities" key :param metric_type: A stri...
873d430596d4cc920fff0c3d8b506edee55a821c
50,584
def convert_to_text(web3, data): """ :param web3: :param data: :return: """ return web3.toText(data)
09f05e836978b38de2246b83e5d992738e83e546
50,585
def CallableParamRegistry(): # noqa: N802 """Callable registry with a keyword parameter.""" class CallableParamRegistry: registry = Registry('kwparam') return CallableParamRegistry
9171de2669d232ab80cc474e063918b8a4a5979d
50,586
def largest_product(product_list): """Find the largest product from a given list.""" largest = 1 for products in product_list: if largest < max(products): largest = max(products) return largest
7f9f2b151afc7d0e35203a5dda665ef100279c65
50,587
def shapes_equal_trailing(*shapes): """Test if shapes are equal, starting from trailing end, except for leading ones.""" for lengths in zip_longest(*[shape[::-1] for shape in shapes], fillvalue=1): if not all(length == lengths[0] for length in lengths): return False return True
bac06c7928f8ad65c34eac189dca33edb558ad8d
50,588
def generate_indices_filename(max_length, vocab_size, seed, inference, step3, set_type, multi_task, multi_task_lambda, disabled_properties): """ Generates a filename from baseline params (see baseline.py) """ name = f'{generate_unique_filename(max_length, vocab_size, seed, inference, step3, set_type, mu...
296c8c3f0654ccd0893d9449b9752402ba97a66e
50,590
import itertools def get_separable_problems(problem): """Return a list of separable problems whose sum is the original one. Parameters ---------- problem : Problem A problem that consists of separable (sub)problems. Returns ------- List A list of problems which are separa...
c823daa7926142c7717b07831fe3f3f6d8157f8c
50,591
def _padded_size(size, padding_multipe=8): """ Return the size of a field padded to be a multiple a give value. """ return int(ceil(size / padding_multipe) * padding_multipe)
95339d88bfa86ac5f84934c086318d7f112c485a
50,592
def add_api_component(logger, name, event_dict): """ Adds the component to the entry if the entry is not from structlog. This only applies to the API since it is handled by external WSGI servers. """ event_dict["component"] = "API" return event_dict
d510d8eb563ffd3b819abd3ec970790ed9d30083
50,593
def make_plans(*by_key, **plans): """ Given by_key which is a list of strings and plans which is a dictionary of key to plan, return a dictionary of key to plans. We will complain if: * A key in by_key is not a registered plan * A key in by_key is also in plans """ if not by_key and no...
0687cf74930143078657dcf391a8552a91e29478
50,594
def split_list(l, split, density=None): """ Splits a list into part a of b split should be a string of the form 'a/b'. For instance, '1/3' would give the split one of three. If the length of the list is not divisible by the number of splits, the last split will have more items. `density` ...
821876bef0034bd7017bc0436a9d85a4defae92b
50,595
def load_files(proof_fnames): """ From a list of XML filenames that contain a <proof> node, it returns a list of lxml root nodes. """ roots = [] parser = etree.XMLParser(remove_blank_text=True) for fname in proof_fnames: docs = etree.parse(fname, parser) roots.append(docs) ...
29ead39fedb4541fc116bd791687dc48db901915
50,596
def encoding(mctx, x): """File can be successfully decoded with the given character encoding. May not be useful for encodings other than ASCII and UTF-8. """ # i18n: "encoding" is a keyword enc = getstring(x, _("encoding requires an encoding name")) s = [] for f in mctx.existing(): ...
ece2169da87867254250b81c8518f46a50f29dd5
50,597
import random def shuffle_string(s: str) -> str: """ Mixes all the letters in the given string Parameters: s(str): the string to shuffle Returns: str: string with randomly reordered letters Examples: >>> shuffle_string('abc') 'cba' >>>...
9c68b276f539d6385e5393cb92fa971fbb6059d4
50,598
def get_data(input_text: str) -> list[Line]: """ returns list of Line objects """ lines = [Line.from_string(line_str) for line_str in input_text.splitlines()] return lines
4f910f080b3fbf8f43ea3ff2abf23f2087db32fa
50,599
import torch def accuracy(output, target, topk=(1,), tok_groups=None, tok_group_labels=None, as_list=False): """Computes the accuracy over the k top predictions for the specified values of k""" mask = target != -1 output = output[mask] target = target[mask] maxk = max(topk) _, pred = output...
359c8993623d89c4e2b603eaf5ce262bbe9c47de
50,600
import warnings def deprecated(func): """This is a decorator which can be used to mark functions as deprecated. It will result in a warning being emmitted when the function is used.""" def new_func(*args, **kwargs): warnings.simplefilter('always', DeprecationWarning) # turn off filter ...
e710d93dae4198e43862016c141750d40b70df5c
50,601
def glove2dict(src_filename): """ GloVe reader. Parameters ---------- src_filename : str Full path to the GloVe file to be processed. Returns ------- dict Mapping words to their GloVe vectors as `np.array`. """ # This distribution has some words with spaces, so...
772a941df0d02703b627e64344f50895cca36c2c
50,604
import numpy import math def shear_matrix(angle, direction, point, normal): """Return matrix to shear by angle along direction vector on shear plane. The shear plane is defined by a point and normal vector. The direction vector must be orthogonal to the plane's normal vector. A point P is transforme...
511b33310f44bf9b95ebd7eee38393ec0f1235c1
50,605
def save_tiled_raster_images(tiled_img, filename): """ Save a a return value from `tile_raster_images` to `filename`. Returns ------- img : WRITEME The PIL image that was saved """ if tiled_img.ndim==2: ensure_Image() img = Image.fromarray( tiled_img, 'L') elif t...
331d286e79b83d83b8ff22c6051ab490139cdd78
50,606
import typing def two_points( reviewed_assertions: typing.List[ReviewedAssertion], ) -> typing.Optional[ReviewedAssertion]: """Extract two point ReviewedAssertion of possible.""" if not any(map(ReviewedAssertion.from_multiple, reviewed_assertions)): return None # is single => no two points el...
9e0adeb878de5b3ea0c75d7ec4049ca12b95819a
50,607
def handler500(request, *args, **argv): """Error 500 configuration.""" return render(request, '{{cookiecutter.project_slug}}/404.html')
cda2b33df6c5ff61da14aea3660833524c800d69
50,609
def klucbGauss(x, level, sig2=1., lower=float("-inf"), upper=float("inf")): """returns u such that kl(x,u)=level for the Gaussian kl-divergence (can be done in closed form).""" if (upper==x): return x - np.sqrt(2*sig2*level) elif (lower==x): return x + np.sqrt(2*sig2*level) else: raise ValueError
4e1bd0fa6b6729f6c6699a986cf5944c9e0ed233
50,610
def base64_decode(data): """Decode a Base64 encodedstring""" return b64decode(data.encode('utf-8')).decode('utf-8')
ba768f2d0df2b3a42a80456396ae74185695014a
50,611
def movie(request, movie_id): """显示电影对应的所有场次""" one_movie = Movie.objects.get(movie_id=movie_id) comments = Movie_comment.objects.filter(movie_id=movie_id) score = False if len(comments) > 0: score = comments.aggregate(avg_score=Avg('score'))['avg_score'] cursor = connection.cursor() ...
f8d5d6d9722a55db02f8da4b69975b5f69d32e50
50,612
def load_file_to_dict(path): """ Takes a file path and loads it into a nested json dict following the format in json_form_schema.json The file may be a xls file or json file. If it is xls it is converted using xls2json. """ if path.endswith(".json"): name = _section_name(path) ...
7bfa1a3455e1cdba17b77ee0e7af49f72c193943
50,613
from typing import Union def can_lead_to_object_uncertainty(gdatalog): """Figure out if a walked GDatalog[Δ] program can lead to object uncertainty. Object uncertainty happens when there is a rule in the program such that: - there exist an atom in the antecedent of the rule such that the ...
dea9d48fece0b6c3cb9eb5d57448c4e3c84f7eae
50,615
def averageRaDec(ra, dec): """Calculate average RA, Dec from input lists using spherical geometry. Parameters ---------- ra : `list` [`float`] RA in [radians] dec : `list` [`float`] Dec in [radians] Returns ------- float, float meanRa, meanDec -- Tuple of average R...
8af0cd4f9a612400a00af64e6a6bee5cb3383ff5
50,616
def onnx2str(model_onnx, nrows=15): """ Displays the beginning of an ONNX graph. See :ref:`onnxsklearnconsortiumrst`. """ lines = str(model_onnx).split('\n') if len(lines) > nrows: lines = lines[:nrows] + ['...'] return "\n".join(lines)
0bca645ab2882cde59788517cc9c8c02d208de2e
50,617
def hessian (f, X, eps=1e-6): """ Check Hessian of function. checkgrad.hessian (f, X, eps=1e-6) Inputs: f Function, returns Y(X), d^2Y / dX^2. X [D1, ..., Dn] Y [E1, ..., Em] d^2Y/dX^2 [E1, ..., Em, D1,...
fc05e13e9fad5be88efcff5574dfd0bd370bf07c
50,619
def is_available(): """ Test whether YouCompleteMe plugin is available (was loaded). """ return 'g:loaded_youcompleteme' in vimp.var
219475c1405ec6fe132a9f1e94db0fa76028c1b9
50,620
import math import numpy as np def rs1_score(sequence): """ Generates a binary matrix for DNA/RNA sequence, where each column is a possible base and each row is a position along the sequence. Matrix column order is A, T/U, C, G """ seq = str(sequence).upper() seq = list(seq) matrix1 = np....
c23abc5ffe18034f26b88d7ea4c3ff7848250eb9
50,621
import copy def get_build_summary(results): """Prints to screen the complication results of example programs. Args: results - results of the compilation stage. which is the output of compile_repos() Returns: Numbers of failed results """ pass_table = PrettyTable() pass_table.field_na...
c4ab123ea89b8e8719fe48a663df99373c4dacf7
50,622
import binascii def s2n(s): """ String to number. """ if not len(s): return 0 return int(binascii.hexlify(s), 16)
21884827bf205bf98878d93b241855fbe4c0abcd
50,623
def diff_lists(old, new): """Returns sorted lists of added and removed items.""" old = set(old or []) new = set(new or []) return sorted(new - old), sorted(old - new)
1359a2c89c20993445491ff2a986a392eaee2aed
50,624
import csv from bs4 import BeautifulSoup import tqdm import urllib def save_csv_given_urls(urls, csv_filename='AAAI_tmp.csv'): """ write IJCAI papers' urls in one csv file :param urls: str, the urls of paper website, such as 'https://www.aaai.org/Library/AAAI/aaai20contents-issue01.php' :param csv_fil...
469e871d5e391e13b4b7bbab773e16be8d7c7ae1
50,625
def indicator_remove(_id, username=None): """ Remove an Indicator from CRITs. :param _id: The ObjectId of the indicator to remove. :type _id: str :param username: The user removing the indicator. :type username: str :returns: dict with keys "success" (boolean) and "message" (list) if failed...
e5e54198daaca2e92587fa0fe551c8e228dbe463
50,626
def get(github_repository, **args): """Send data and perform Core()""" return Core(github_repository, **args).get()
10b068ac4c0411ecee916aae5182da4ffd96f272
50,627
import requests def get_profile(login): """Get the GitHub profile from login""" print("get profile for %s" % (login,)) try: profile = get("https://api.github.com/users/%s" % login).json() except requests.exceptions.HTTPError: return dict(name=login, avatar_url=LOGO_URL, html_url="") ...
f3df77c82410fa4f5779c6892c225fdcc31d2dd1
50,628
def create_U_layer(mol, auxinfo): """ Creates a string with the positions of the atoms that bear unpaired electrons. The string can be used to complement the InChI with an additional layer that allows for the differentiation between structures with multiple unpaired electrons. The string is compose...
cc9b0e172feff70bb72a4bb3564b62c63ad2b6da
50,629
def result(product_id): """ Speak query result""" response = PhoneInterface() result = Product.query.get(product_id) response.speak(to_result(result)) response.speak('Is there anything else we can help you with?') response.listen('listenbot.done', 'yes, no') return str(response)
aa0c48dc77cb009ef94b411a3ac44063cac1e2c6
50,630
def key2board(key): """ Turn a key into a "Game of Life" board. We might add an arbitrary size parameter. """ Z = np.zeros((512 + 2, ((512 * 4) + 2)), int) Z[1:-1, 1:-1] = (np.frombuffer(hex2bin(key), 'u1') - ord('0')).reshape((512, 512 * 4)) return(Z)
46bc2a3f6ccd2895514a9181684c8f500e78574f
50,631
def PV(FV,i,n,m=1): """ future value interest years optional payments per year """ PV = FV / ((1 + i/m)**(m*n)) return PV
7b573f5338ad950295f2e03a584b544c3df81f82
50,632
def getCeleryApp(): """ Lazy loader for the celery app. Reloads anytime the settings are updated. """ global _celeryapp if _celeryapp is None: backend = Setting().get(PluginSettings.BACKEND) or 'amqp://guest:guest@localhost/' broker = Setting().get(PluginSettings.BROKER) or 'amqp://...
9bc201894ef92a13418e7bca8de7f844de802302
50,633
def get_gw_bytes_encoding(): """ get gateway encoding method :return: string """ return "utf-8"
44e23564f5feb086334d7d9c00a8f4283ae5273d
50,634
def build_py_ide_info(target, ctx): """Build PyIdeInfo.""" if not hasattr(target, "py"): return (None, set()) sources = sources_from_target(ctx) transitive_sources = target.py.transitive_sources py_ide_info = struct_omit_none( sources = sources, ) return (py_ide_info, transitive_sources)
05252876bc906f878b1522f9abf48feb90c27414
50,635
def factor_new_space(M): """ Given a new space `M` of modular symbols, return the decomposition into simple of `M` under the Hecke operators. INPUT: - ``M`` - modular symbols space OUTPUT: list of factors EXAMPLES:: sage: M = ModularSymbols(37).cuspidal_subspace() ...
e64f8e1b19f803fe92f3fa0a4cd1d959a8132cba
50,636
import tqdm import io def build_core_template(images, N=5, thresh=40, vb=True): """ Overlay images of core trays from e.g. a drillhole to calculate a template that is used for extracting individual core segments and is robust to data quirks (e.g. empty trays). All images must be identical dimensions a...
38e7f7af20265037163877378a84da647c78455c
50,637
from typing import Dict def cohort_tests(config: Dict, n_days: int) -> Dict[str, int]: """Determines the number of tests required per person for all cohorts. The number of tests required for a person in a cohort is approximately the number of testing days divided by the cohort's target testing interval. ...
3c68bde6016fa25f11c736c80460e7ef35398b46
50,638
def check_oversamplers_classifiers(oversamplers, classifiers): """Extract estimators and parameters grids.""" # Create estimators and parameter grids estimators, param_grids = [], [] for oversampler, classifier in product(oversamplers, classifiers): # Unpack oversamplers and classifiers ...
d8ceed380fd775968ad8f15662ff673c7753c5e2
50,639
def axiom_generator_have_arrow_ssa(t): """ Assert the conditions at time t under which the Agent has the arrow at time t+1 t := time """ "*** YOUR CODE HERE ***" axiom_str = state_have_arrow_str(t+1) + ' <=> (' + state_have_arrow_str(t) + ' & ~' + action_shoot_str(t) + ')' # Comment or...
db37c9365dfaf9016c7a47455ea2f07f9d6956cc
50,641
def map_(key, value, *tail) -> Expression: """ Creates a map of expressions. Example: :: >>> tab.select( >>> map_( >>> "key1", 1, >>> "key2", 2, >>> "key3", 3 >>> )) .. note:: keys and values should have the ...
8c0e4e50320b23d916e660c0d4baa78f9d781407
50,642
def convert_coords(container: pygame.Rect, x: float, y: float) -> (int, int): """Converts the given coordinates for a simulation display purposes. :param container: the simulation surface :param x: the x position coordinate :param y: the x position coordinate :return: converted coordinates """ ...
3d103078658e904887f380425d3c7d3743103633
50,644
def _parse_unit(unit_element, namespace): """returns a list of dicts that represent the values for a given unit or units element """ unit_dict = _element_dict(unit_element) tag_name = unit_element.tag.split('}')[-1] return_dict = {} if '1.0' in namespace: return_dict['name'] = unit_...
2b7b4333c9f0507e3c42528dbe8e19f498a5d6ac
50,646
def kw(sa: 'Atmosphere', frequency: float) -> Tensor1D_or_3D: """ :param frequency: частота излучения в ГГц :param sa: объект Atmosphere :return: весовая функция k_w (вода в жидкокапельной фазе). """ return wf.kw(frequency, sa.temperature)
5070cc2565b95fde5af77e0eb0f55604b2c8c629
50,647
def plot_lines(df: pd.DataFrame, cols: list = None, cols_like: list = None, x: str = None, h: int = 300, w: int = 1200, t_str: str = 'box_zoom,pan,hover,reset,save', x_type: str = 'datetime', show_p: bool = True, t_loc: str = 'right', out_path: str = None, return_p: bool = False, palette: ...
d45234fad9cb16e27e8d420437d95141bbe36423
50,648
import json def add_postgraduate_info(): """ 添加一条信息 :return:{'result': result} """ user_id = request.values.get('openid') # 用户微信openid subject = request.values.get('subject') # 考研方向 msg = request.values.get('msg') # 附加消息 phone = request.values.get('phone') # 联系电话 grade = reques...
9fe9af80063d4a717262c551985088a4aae9e880
50,649
def depth_first_traversal_for_node(node, callback, direction, obj=None): """ Executes a depth-first traversal from this node in a given direction. Raising a StopIteration will terminate the traversal. :type node: treestruct.Node :type callback: (treestruct.Node, treestruct.Node, object) -> () :...
638836150f81ed5261752c01ca9e506242c8cb71
50,650
def build_model(tparams, options): """ Construct computation graph for the whole model """ # inputs (image, sentence, contrast images, constrast sentences) im = tensor.matrix('im', dtype='float32') s = tensor.matrix('s', dtype='float32') cim = tensor.matrix('cim', dtype='float32') cs = t...
9caad070fffd6c2581a86d4226770fabd1fe3516
50,651
def default_slugifier(value, allow_unicode=False): """ Oscar's default slugifier function. When unicode is allowed it uses Django's slugify function, otherwise it uses cautious_slugify. """ if allow_unicode: return django_slugify(value, allow_unicode=True) else: return cautious_s...
e507934e3983816fb011f83e7a991eda13278a54
50,652
def extract_pos_tags(input_xls: str) -> dict: """ Read all post-tas from JUIZ column and returns a dictionary indexed by the sentence id with a list of all pos-tags. Parameters ---------- input_xls: str Input xls file. Returns ------- dict: Dict of sentence ids and ...
3df23b1e7da984b8ead1f27c530e9cef603fba30
50,653
def secure_atbd_version_lock( atbd_id: str, version: str, db: DbSession = Depends(get_db_session), override: bool = False, user: CognitoUser = Depends(require_user), principals=Depends(get_active_user_principals), ): """ Sets locked_by field of ATBD Version to current user. Succeeds ...
6ff5d5eb86e33e1b9ef278b3e319a4c6b6e2b6ff
50,654
from rdkit.sping.PDF import pidPDF from rdkit.piddle import piddlePDF def ClusterToPDF(cluster, fileName, size=(300, 300), ptColors=[], lineWidth=None, showIndices=0, stopAtCentroids=0, logScale=0): """ handles the work of drawing a cluster tree to an PDF file **Arguments** - cluster: t...
8fd99af1900e6f36b148d9c4cbf348e68348833d
50,655
def ants_move(space, pos, inv_distance, pheromones, alpha, beta, del_tau): """Moves the ants from starting position to cover all the nodes. Arguments: space {numpy.ndarray} -- The sample space pos {numpy.ndarray} -- The starting position of the ants inv_distance {numpy.ndarray} -- T...
46695e157efdc343be55f9bf1d85191808821a69
50,656
def list_to_tree(S: list) -> TreeNode: """ :param L: :return: """ L = [TreeNode(val) if val is not None else None for val in S] # print(L) tmp_list = [L[0]] cursor = 1 N = len(L) while tmp_list: n = len(tmp_list) next_cursor = cursor + n * 2 for i, node in...
65b9fa64673964c5e2af4d1923f947f97eb5e73f
50,657
def three_points_to_circle(p1, p2, p3): """ Function that calculates circle parameters defined by three points. Input: - p1 [float,float] : pair (x,y) of coordinates of the 1st point - p2 [float,float] : pair (x,y) of coordinates of the 2nd point - p3 [float,float] : pair (x,y) of coordinates of...
cc45cd43ec9d5555b469ed7001f46935d1bc16da
50,658
def dnlsim(system, u, t=None, x0=None): """Simulate output of a discrete-time nonlinear system. Calculate the output and the states of a nonlinear state-space model. x(t+1) = A x(t) + B u(t) + E zeta(x(t),u(t)) y(t) = C x(t) + D u(t) + F eta(x(t),u(t)) where zeta and eta are polynomials w...
81ede6bdbdaad7ad2ae1cae4d5b23b7e60f1fd98
50,659