content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def painel(request): """ Exibe o painel do usuário. """ return render(request, "lancamentos/painel.html")
ff40db732402077eb6678f8586582877d96e3ede
4,526
def q_statistic(y, c1, c2): """ Q-Statistic. Parameters ---------- y : numpy.array Target sample. c1 : numpy.array Output of the first classifier. c2 : numpy.array Output of the second classifier. Returns ------- float Return the Q-Statistic measur...
83f83bffcb469ff45c22a1f35efc6e60ccdd0d2d
4,528
def nan_helper(y): """Helper to handle indices and logical indices of NaNs. Input: - y, 1d numpy array with possible NaNs Output: - nans, logical indices of NaNs - index, a function, with signature indices= index(logical_indices), to convert logical indices of NaNs to 'equ...
b6bd981369403a5542f8bcefb3e8a68315fb697f
4,529
import re def convert_parameters(child, text=False, tail=False, **kwargs): """ Get child text or tail :param child: :param text: :param tail: :return: """ p = re.compile(r'\S') # Remove empty info child_text = child.text if child.text else '' child_tail = child.tail if chil...
2421e515491f1256c56eb9ac6935a3c0c1de64be
4,532
def Get_Country_Name_From_ISO3_Extended(countryISO): """ Creates a subset of the quick chart data for a specific country. The subset includes all those rows containing the given country either as the origin or as the country of asylum. """ countryName = "" # June-22 - This function has been u...
d6e5b34223582f3a5a5ca20fd798ef5cfb1b1e8d
4,533
def thetaG(t,t1,t2): """ Return a Gaussian pulse. Arguments: t -- time of the pulse t1 -- initial time t2 -- final time Return: theta -- Scalar or vector with the dimensions of t, """ tau = (t2-t1)/5 to = t1 + (t2-t1)/2 thet...
9e05358bfbf5f11b30f2a6b44504214ab4db4ea5
4,536
def choose_string(g1, g2): """Function used by merge_similar_guesses to choose between 2 possible properties when they are strings. If the 2 strings are similar, or one is contained in the other, the latter is returned with an increased confidence. If the 2 strings are dissimilar, the one with the...
e39a66c9f3f941b12225dde879bc92956694d2d0
4,537
def update_alert_command(client: MsClient, args: dict): """Updates properties of existing Alert. Returns: (str, dict, dict). Human readable, context, raw response """ alert_id = args.get('alert_id') assigned_to = args.get('assigned_to') status = args.get('status') classification = a...
237aa63f449dc6395390a26007b15123d5763874
4,538
def create_payment(context: SagaContext) -> SagaContext: """For testing purposes.""" context["payment"] = "payment" return context
e96db6e57996d8f704e453bf14b8e4a3c63da1a6
4,539
import asyncio async def TwitterAuthURLAPI( request: Request, current_user: User = Depends(User.getCurrentUser), ): """ Twitter アカウントと連携するための認証 URL を取得する。<br> 認証 URL をブラウザで開くとアプリ連携の許可を求められ、ユーザーが許可すると /api/twitter/callback に戻ってくる。 JWT エンコードされたアクセストークンがリクエストの Authorization: Bearer に設定されていないとアクセ...
2245c3b2d842c455fa9cb36390c84c8470c3b8e1
4,540
import random def post_sunday(request): """Post Sunday Details, due on the date from the form""" date_form = SelectDate(request.POST or None) if request.method == 'POST': if date_form.is_valid(): groups = DetailGroup.objects.filter(semester=get_semester()) details = settin...
84787109d0981920bbced7a734d0b67c84d4a9a7
4,541
from typing import Dict from typing import List def reconstruct(lvl: Level, flow_dict: Dict[int, Dict[int, int]], info: Dict[int, NodeInfo]) -> List[List[int]]: """Reconstruct agent paths from the given flow and node information""" paths: List[List[int]] = [[]] * len(lvl.scenario.agents) start_flows = flo...
d792ed6b937f49177ac85609ada3edb2089e2642
4,542
import traceback def arch_explain_instruction(bv, instruction, lifted_il_instrs): """ Returns the explanation string from explanations_en.json, formatted with the preprocessed instruction token list """ if instruction is None: return False, [] parsed = parse_instruction(bv, instruction, lifted_il_...
57c6146ac06317df8a9e9b846a279fa950a970bc
4,543
def get_subnet_mask(subnet: int, v6: bool) -> int: """Get the subnet mask given a CIDR prefix 'subnet'.""" if v6: return bit_not((1 << (128 - subnet)) - 1, 128) else: return bit_not((1 << (32 - subnet)) - 1, 32)
57c8de0bff70b0939dd8c646da0840be7c2839e1
4,545
def home(request): """return HttpResponse('<h1>Hello, Welcome to this test</h1>')""" """Le chemin des templates est renseigne dans "DIRS" de "TEMPLATES" dans settings.py DONC PAS BESOIN DE RENSEIGNER LE CHEMIN ABSOLU""" return render(request, "index.html")
04a671daa9425ea76841b491f8eefd133b6e2c67
4,547
def extract_commands(data, *commands): """Input function to find commands output in the "data" text""" ret = "" hostname = _ttp_["variable"]["gethostname"](data, "input find_command function") if hostname: for command in commands: regex = r"{}[#>] *{} *\n([\S\s]+?)(?={}[#>]|$)".forma...
6fcbf9584f5a2f799839c9964a5ae6235f4e8b50
4,549
def get_version() -> str: """ Returns the version string for the ufotest project. The version scheme of ufotest loosely follows the technique of `Semantic Versioning <https://semver.org/>`_. Where a minor version change may introduce backward incompatible changes, due to the project still being in activ...
b34eac3aef7661b65408c60ce606cd24a06ae0ee
4,550
async def clear_pending_revocations(request: web.BaseRequest): """ Request handler for clearing pending revocations. Args: request: aiohttp request object Returns: Credential revocation ids still pending revocation by revocation registry id. """ context: AdminRequestContext = ...
98db34266f3afbe9ecfeddcf802c1441ae7ea58b
4,551
from datetime import datetime def add_filter(field, bind, criteria): """Generate a filter.""" if 'values' in criteria: return '{0}=any(:{1})'.format(field, bind), criteria['values'] if 'date' in criteria: return '{0}::date=:{1}'.format(field, bind), datetime.strptime(criteria['date'], '%Y-...
2358cab297b2a2cbc42af02b3b6d14ac134c8b71
4,552
def ireject(predicate, iterable): """Reject all items from the sequence for which the predicate is true. ireject(function or None, sequence) --> iterator :param predicate: Predicate function. If ``None``, reject all truthy items. :param iterable: Iterable to filter through. :yields: A ...
98f9416ac1db1f2909d1d895ee0c0bc70c8b2249
4,553
def construct_config_error_msg(config, errors): """Construct an error message for an invalid configuration setup Parameters ---------- config: Dict[str, Any] Merged dictionary of configuration options from CLI, user configfile and default configfile errors: Dict[str, Any] Di...
02954620115308d7d50ca28b23b98a2ba410489f
4,554
def _haversine_GC_distance(φ1, φ2, λ1, λ2): """ Haversine formula for great circle distance. Suffers from rounding errors for antipodal points. Parameters ---------- φ1, φ2 : :class:`numpy.ndarray` Numpy arrays wih latitudes. λ1, λ2 : :class:`numpy.ndarray` Numpy arrays wih ...
bb57ddeacd761abead5ee499610ead8c9ba38a9f
4,556
def differentiate_branch(branch, suffix="deriv"): """calculates difference between each entry and the previous first entry in the new branch is difference between first and last entries in the input""" def bud(manager): return {add_suffix(branch,suffix):manager[branch]-np.roll(manager[branch],1)} return bud
298b19b1e151e04df9c040f0c48e4799bcc3f3d2
4,557
import typing def etf_holders(apikey: str, symbol: str) -> typing.Optional[typing.List[typing.Dict]]: """ Query FMP /etf-holder/ API. :param apikey: Your API key. :param symbol: Company ticker. :return: A list of dictionaries. """ path = f"etf-holder/{symbol}" query_vars = {"apikey": ...
f405fa92296c28a8ba8ca87b6edac27392ec1f85
4,558
def clean_visibility_flags(horizon_dataframe: pd.DataFrame) -> pd.DataFrame: """ assign names to unlabeled 'visibility flag' columns -- solar presence, lunar/interfering body presence, is-target-on-near-side-of-parent-body, is-target-illuminated; drop then if empty """ flag_mapping = { u...
906432120babffacb709b1d45e7c4dd86c60775d
4,559
def calib(phase, k, axis=1): """Phase calibration Args: phase (ndarray): Unwrapped phase of CSI. k (ndarray): Subcarriers index axis (int): Axis along which is subcarrier. Default: 1 Returns: ndarray: Phase calibrated ref: [Enabling Contactless Detection of Mov...
5e1f59c0a13440ad8e1304523976c2fbe6562d5a
4,560
def rescale_as_int( s: pd.Series, min_value: float = None, max_value: float = None, dtype=np.int16 ) -> pd.Series: """Cannot be converted to njit because np.clip is unsupported.""" valid_dtypes = {np.int8, np.int16, np.int32} if dtype not in valid_dtypes: raise ValueError(f"dtype: expecting [{va...
31772759c67d33f20b89fd87aa91c9249ae2bb9a
4,561
def format_headers(headers): """Formats the headers of a :class:`Request`. :param headers: the headers to be formatted. :type headers: :class:`dict`. :return: the headers in lower case format. :rtype: :class:`dict`. """ dictionary = {} for k, v in headers.items(): if isinstanc...
0a0890c10378d9f8e20f353b1b9383e728f0a4f7
4,562
def decode_field(value): """Decodes a field as defined in the 'Field Specification' of the actions man page: http://www.openvswitch.org/support/dist-docs/ovs-actions.7.txt """ parts = value.strip("]\n\r").split("[") result = { "field": parts[0], } if len(parts) > 1 and parts[1]: ...
1a1659e69127ddd3c63eb7d4118ceb4e53a28ca0
4,563
import tqdm def compute_norm(x_train, in_ch): """Returns image-wise mean and standard deviation per channel.""" mean = np.zeros((1, 1, 1, in_ch)) std = np.zeros((1, 1, 1, in_ch)) n = np.zeros((1, 1, 1, in_ch)) # Compute mean. for x in tqdm(x_train, desc='Compute mean'): mean += np.sum...
e49012075adfa03b33bb6308d1d50f4c22c1cc2c
4,564
def _nonempty_line_count(src: str) -> int: """Count the number of non-empty lines present in the provided source string.""" return sum(1 for line in src.splitlines() if line.strip())
ad2ac0723f9b3e1f36b331175dc32a8591c67893
4,565
import json def geom_to_xml_element(geom): """Transform a GEOS or OGR geometry object into an lxml Element for the GML geometry.""" if geom.srs.srid != 4326: raise NotImplementedError("Only WGS 84 lat/long geometries (SRID 4326) are supported.") # GeoJSON output is far more standard than GML, ...
a2702e8ac4e3cb24f787513f820df60ad973e305
4,566
def precision(y_true, y_pred): """Precision metric. Only computes a batch-wise average of precision. Computes the precision, a metric for multi-label classification of how many selected items are relevant. Parameters ---------- y_true : numpy array an array of true labels y_pred...
d57f1d782628e312b2e52098658be81e32351f3d
4,568
def get_validators(setting): """ :type setting: dict """ if 'validate' not in setting: return [] validators = [] for validator_name in setting['validate'].keys(): loader_module = load_module( 'spreadsheetconverter.loader.validator.{}', validator_name) ...
db3b5594122685f3190cdae053ab7a385065d17e
4,569
def worker(remote, parent_remote, env_fn_wrapper): """ worker func to execute vec_env commands """ def step_env(env, action): ob, reward, done, info = env.step(action) if done: ob = env.reset() return ob, reward, done, info parent_remote.close() envs = [env_fn_w...
aaf5a16a72e97ec46e3a1ae4676c4591bc7f0183
4,571
from functools import reduce def greedysplit_general(n, k, sigma, combine=lambda a, b: a + b, key=lambda a: a): """ Do a greedy split """ splits = [n] s = sigma(0, n) def score(splits, sigma): splits = sorted(splits) return key(reduce(combine, (sigma(a, b) ...
6480db8f613f37704e7bf6552407e5b0f851ab47
4,572
def public_assignment_get(assignment_id: str): """ Get a specific assignment spec :param assignment_id: :return: """ return success_response({ 'assignment': get_assignment_data(current_user.id, assignment_id) })
2f3d828975c0d7db663556da5f0dc590124075b2
4,573
def recursion_detected(frame, keys): """Detect if we have a recursion by finding if we have already seen a call to this function with the same locals. Comparison is done only for the provided set of keys. """ current = frame current_filename = current.f_code.co_filename current_function = c...
ebf30e715d2901169095bc920e8af6c715f2a1de
4,574
def pars_to_blocks(pars): """ this simulates one of the phases the markdown library goes through when parsing text and returns the paragraphs grouped as blocks, as markdown handles them """ pars = list(pars) m = markdown.Markdown() bp = markdown.blockprocessors.build_block_parser(m) root = mark...
f71d4460847ec4b69ad53470aba26c145d296388
4,576
from bs4 import BeautifulSoup def extract_intersections_from_osm_xml(osm_xml): """ Extract the GPS coordinates of the roads intersections Return a list of gps tuples """ soup = BeautifulSoup(osm_xml) retval = [] segments_by_extremities = {} Roads = [] RoadRefs = [] Coordinat...
6cff1fe39891eb4a6c595196eabfd4569af2fd8e
4,577
def spark_session(request): """Fixture for creating a spark context.""" spark = (SparkSession .builder .master('local[2]') .config('spark.jars.packages', 'com.databricks:spark-avro_2.11:3.0.1') .appName('pytest-pyspark-local-testing') .enableHive...
e7a95ad7ebea876976923c6dd16c7a761116427d
4,578
import yaml def _load_model_from_config(config_path, hparam_overrides, vocab_file, mode): """Loads model from a configuration file""" with gfile.GFile(config_path) as config_file: config = yaml.load(config_file) model_cls = locate(config["model"]) or getattr(models, config["model"]) model_params = config[...
97af7dc919de5af96332c8445e162990006079f4
4,579
import ast def _get_assignment_node_from_call_frame(frame): """ Helper to get the Assign or AnnAssign AST node for a call frame. The call frame will point to a specific file and line number, and we use the source index to retrieve the AST nodes for that line. """ filename = frame.f_code.co_filename # Go...
edb7f2425d170721e12dc4c1e2427e9584aeed8c
4,580
def check_existing_user(username): """ a function that is used to check and return all exissting accounts """ return User.user_exist(username)
573e9a8a6c0e504812d3b90eb4a27b15edec35ab
4,581
def createevent(): """ An event is a (immediate) change of the world. It has no duration, contrary to a StaticSituation that has a non-null duration. This function creates and returns such a instantaneous situation. :sees: situations.py for a set of standard events types """ sit = Situation(...
998f0a473c47828435d7e5310de29ade1fbd7810
4,582
def _dump_multipoint(obj, fmt): """ Dump a GeoJSON-like MultiPoint object to WKT. Input parameters and return value are the MULTIPOINT equivalent to :func:`_dump_point`. """ coords = obj['coordinates'] mp = 'MULTIPOINT (%s)' points = (' '.join(fmt % c for c in pt) for pt in coords) ...
cdea05b91c251b655e08650807e3f74d3bb5e77b
4,583
def do_inference(engine, pics_1, h_input_1, d_input_1, h_output, d_output, stream, batch_size, height, width): """ This is the function to run the inference Args: engine : Path to the TensorRT engine pics_1 : Input images to the model. h_input_1: Input in the host ...
e9e452e96d42167bf17bc6bef8dc014fa31dbe8f
4,584
import ast def make_import(): """Import(alias* names)""" return ast.Import(names=[make_alias()])
e9085ee9b4b0438857b50b891fbee0b88d256f8b
4,585
from typing import Union from typing import List def preprocess( image: Union[np.ndarray, Image.Image], threshold: int = None, resize: int = 64, quantiles: List[float] = [.01, .05, 0.1, 0.25, 0.5, 0.75, 0.9, 0.95, 0.99], reduction: Union[str, L...
afa36739309ada2e97e18e63ae65362546b1b52c
4,586
def binary_distance(label1, label2): """Simple equality test. 0.0 if the labels are identical, 1.0 if they are different. >>> from nltk.metrics import binary_distance >>> binary_distance(1,1) 0.0 >>> binary_distance(1,3) 1.0 """ return 0.0 if label1 == label2 else 1.0
2c4eaebda2d6955a5012cc513857aed66df60194
4,587
def calc_commission_futures_global(trade_cnt, price): """ 国际期货:差别很大,最好外部自定义自己的计算方法,这里只简单按照0.002计算 :param trade_cnt: 交易的股数(int) :param price: 每股的价格(美元) :return: 计算结果手续费 """ cost = trade_cnt * price # 国际期货各个券商以及代理方式差别很大,最好外部自定义计算方法,这里只简单按照0.002计算 commission = cost * 0.002 return co...
ddd2c4571abfcdf7021a28b6cc78fe6441da2bd3
4,589
def is_section_command(row): """CSV rows are cosidered new section commands if they start with <SECTION> and consist of at least two columns column. >>> is_section_command('<SECTION>\tSection name'.split('\t')) True >>> is_section_command('<other>\tSection name'.split('\t')) False >>> is_...
7942625e119c4a0d3707fd5884ade6e48b2dfb1a
4,590
def to_int(matrix): """ Funciton to convert the eact element of the matrix to int """ for row in range(rows(matrix)): for col in range(cols(matrix)): for j in range(3): matrix[row][col][j] = int(matrix[row][col][j]) return matrix
9f277ab0c0fe7df145e8a4c0da36fba25a523756
4,592
def create_tastypie_resource(class_inst): """ Usage: url(r'^api/', include(create_tastypie_resource(UfsObjFileMapping).urls)), Access url: api/ufs_obj_file_mapping/?format=json :param class_inst: :return: """ return create_tastypie_resource_class(class_inst)()
cba76e51073612124c5cd968c9360e9c4748d604
4,593
def make_collector(entries): """ Creates a function that collects the location data from openLCA. """ def fn(loc): entry = [loc.getCode(), loc.getName(), loc.getRefId()] entries.append(entry) return fn
83fb167c38626fde79262a32f500b33a72ab8308
4,594
def apiname(funcname): """ Define what name the API uses, the short or the gl version. """ if funcname.startswith('gl'): return funcname else: if funcname.startswith('_'): return '_gl' + funcname[1].upper() + funcname[2:] else: return 'gl' + funcname[0].up...
06575fce76ac02990c973a6dd17ff177ae5e3ddc
4,595
def add_numeric_gene_pos(gene_info): """ Add numeric gene (start) genomic position to a gene_info dataframe """ gene_chr_numeric = gene_info['chr'] gene_chr_numeric = ['23' if x == 'X' else x for x in gene_chr_numeric] gene_chr_numeric = ['24' if x == 'Y' else x for x in gene_chr_numeric] ge...
ab77e6c3a1f6e8d780f5b83a3beb4d94eaf8198b
4,596
import pathlib def read_list_from_file(filename: str) -> set: """Build a set from a simple multiline text file. Args: filename: name of the text file Returns: a set of the unique lines from the file """ filepath = pathlib.Path(__file__).parent.joinpath(filename) lines = filep...
c6fd5f80e05cc74bad600a7af21e36b5bd672b63
4,597
def qlist(q): """Convenience function that converts asyncio.Queues into lists. This is inefficient and should not be used in real code. """ l = [] # get the messages out while not q.empty(): l.append(q.get_nowait()) # now put the messages back (since we popped them out) for i in...
0ce6fb0d543646fb036c35c800d75bbadf670b0d
4,601
def is_stdin(name): """Tell whether or not the given name represents stdin.""" return name in STDINS
535ce3fee9e4a9a42ef24e4b35f84420a61cc529
4,602
def filter_marker_y_padding(markers_y_indexes, padding_y_top, padding_y_bottom): """ Filter the markers indexes for padding space in the top and bottom of answer sheet :param markers_y_indexes: :param padding_y_top: :param padding_y_bottom: :return: """ return markers_y_indexes[(markers...
b1eed0ac24bd6a6354072427be4375ad188572a5
4,603
def hr_admin(request): """ Views for HR2 Admin page """ template = 'hr2Module/hradmin.html' # searched employee query = request.GET.get('search') if(request.method == "GET"): if(query != None): emp = ExtraInfo.objects.filter( Q(user__first_name__icontains=query)...
b78f78c57282b60b527bbaa03eab9064d881aea1
4,605
def create_aws_clients(region='us-east-1'): """Creates an S3, IAM, and Redshift client to interact with. Parameters ---------- region : str The aws region to create each client (default 'us-east-1'). Returns ------- ec3 A boto3 ec2 resource. s3 A boto3 s3 resour...
3a422ac88791e404d67127bc85bab12b6a8aa4d9
4,606
def apply_function(f, *args, **kwargs): """ Apply a function or staticmethod/classmethod to the given arguments. """ if callable(f): return f(*args, **kwargs) elif len(args) and hasattr(f, '__get__'): # support staticmethod/classmethod return f.__get__(None, args[0])(*args, **kwa...
374be0283a234d4121435dbd3fa873640f2b9ad1
4,607
def join_data(ycom_county, census, land_area_data): """ Getting one dataframe from the three datasets """ census['LogPopDensity'] = np.log10(census['TotalPop']/land_area_data['LND110200D']) data = pd.concat(([ycom_county, census]), axis=1) return data
171c08d0c5dac721c3100df9be747c90b299a6c1
4,608
def path_graph(): """Return a path graph of length three.""" G = nx.path_graph(3, create_using=nx.DiGraph) G.graph["name"] = "path" nx.freeze(G) return G
c5fd4ea322b512bd26755d94581d56ddfb4d52bf
4,610
def dropStudentsWithEvents(df, events, saveDroppedAs=None, studentId='BookletNumber', eventId='Label', verbose=True): """ Drop students with certain events. It finds students with the events, and use...
5308ec96c8d5d3c9704f4a42202656bc4126e645
4,611
def create_slides(user, node, slideshow_data): """ Generate SlideshowSlides from data """ """ Returns a collection of SlideshowSlide objects """ slides = [] with transaction.atomic(): for slide in slideshow_data: slide_obj = SlideshowSlide( contentnode=node, ...
6fc31c11f0dc24d17fd82eacd366a0026fb95157
4,613
def is_valid(sequence): """ A string is not valid if the knight moves onto a blank square and the string cannot contain more than two vowels. """ if any(letter == "_" for letter in sequence): return False # Check for vowels # Strings shorter than 3 letters are always ok, as they ...
0c3a72d05155eaf69ffeb7a734e9ceeabe0c44c2
4,614
import urllib def is_dataproc_VM(): """Check if this installation is being executed on a Google Compute Engine dataproc VM""" try: dataproc_metadata = urllib.request.urlopen("http://metadata.google.internal/0.1/meta-data/attributes/dataproc-bucket").read() if dataproc_metadata.decode("UTF-8")....
21044a482b534ce3625b49080d1c472d587039ad
4,618
def lookup_all(base): """Looks up a subclass of a base class from the registry. Looks up a subclass of a base class with name provided from the registry. Returns a list of registered subclass if found, None otherwise. Args: base: The base class of the subclass to be found. Returns: A list of subcla...
de6a8504d0c6cf6f149b597e4d8b41f7b5fc1eff
4,619
def makepyfile(testdir): """Fixture for making python files with single function and docstring.""" def make(*args, **kwargs): func_name = kwargs.pop('func_name', 'f') # content in args and kwargs is treated as docstring wrap = partial(_wrap_docstring_in_func, func_name) args = ma...
420733f4ee299514dba4172cfcc93b7429c635ca
4,620
from PIL import Image, ImageDraw, ImageFont def createTextWatermark(msg, size, loc, fontcolor='white', fontpath='arial.ttf', fontsize=18): """Creates a watermark image of the given text. Puts it at the given location in an RGBA image of the given size. Location should be a 2-tuple denoting the center loca...
6a1ae202a92b351f7d7301735dc825e826898522
4,621
def get_server_pull_config(config:dict): """ takes a config dictionary and returns the variables related to server deployment (pull from intersections). If there is any error in the configuration, returns a quadruple of -1 with a console output of the exception """ try: server = config["Data...
3a5a882bf91cb65462cdbf4fe202bbbc9d52ae2c
4,622
def buff_push(item: BufferItem): """ Add BufferItem to the buffer and execute if the buffer is full """ q.put(item) make_dependencies(item) if q.full(): return buff_empty_partial(q.maxsize - 1) return None
d45c0f67fa21cade7a0c2462e1cd8167f4939e0b
4,623
from rx.core.operators.take import _take from typing import Callable def take(count: int) -> Callable[[Observable], Observable]: """Returns a specified number of contiguous elements from the start of an observable sequence. .. marble:: :alt: take -----1--2--3--4----| [ take(2)...
636cc982c6c8c9b13a2cecb675bb0ca7aadbcd91
4,625
from typing import List from typing import Union def format_fields_for_join( fields: List[Union[Field, DrivingKeyField]], table_1_alias: str, table_2_alias: str, ) -> List[str]: """Get formatted list of field names for SQL JOIN condition. Args: fields: Fields to be formatted. tabl...
691a154f8b984b11ed177a7948fe74398c693b25
4,626
def get_payment_balance(currency): """ Returns available balance for selected currency This method requires authorization. """ result = get_data("/payment/balances", ("currency", currency)) payment_balance = namedtuple("Payment_balance", get_namedtuple(result[0])) return [payment_balance(...
354abbf4e9bc1b22a32e31555106ce68a21e9cd1
4,627
import torch def build_scheduler(optimizer, config): """ """ scheduler = None config = config.__dict__ sch_type = config.pop('type') if sch_type == 'LambdaLR': burn_in, steps = config['burn_in'], config['steps'] # Learning rate setup def burnin_schedule(i): ...
b205b323db322336426f3c13195cb49735d7284d
4,628
def rpca_alm(X, lmbda=None, tol=1e-7, max_iters=1000, verbose=True, inexact=True): """ Augmented Lagrange Multiplier """ if lmbda is None: lmbda = 1.0 / np.sqrt(X.shape[0]) Y = np.sign(X) norm_two = svd(Y, 1)[1] norm_inf = np.abs(Y).max() / lmbda dual_norm = np.max(...
8c09f8f4b004b9a00655402e5466636aa9fc4390
4,629
def dwt_embed(wmImage, hostImage, alpha, beta): """Embeds a watermark image into a host image, using the First Level Discrete Wavelet Transform and Alpha Blending.\n The formula used for the alpha blending is: resultLL = alpha * hostLL + beta * watermarkLL Arguments: wmImage (NumPy arr...
939e8d14ceb9452dc873f7b2d9472630211c0432
4,630
def make_file_iterator(filename): """Return an iterator over the contents of the given file name.""" # pylint: disable=C0103 with open(filename) as f: contents = f.read() return iter(contents.splitlines())
e7b612465717dafc3155d9df9fd007f7aa9af509
4,631
def little_endian_bytes_to_int(little_endian_byte_seq): """Converts a pair of bytes into an integer. The `little_endian_byte_seq` input must be a 2 bytes sequence defined according to the little-endian notation (i.e. the less significant byte first). For instance, if the `little_endian_byte_seq` i...
d8d0c6d4ebb70ea541e479b21deb913053886748
4,633
def higher_follower_count(A, B): """ Compares follower count key between two dictionaries""" if A['follower_count'] >= B['follower_count']: return "A" return "B"
d4d182ca5a3c5bff2bc7229802603a82d44a4d67
4,634
def _element_or_none(germanium, selector, point): """ Function to check if the given selector is only a regular element without offset clicking. If that is the case, then we enable the double hovering in the mouse actions, to solve a host of issues with hovering and scrolling, such as elements a...
b3de13ecefc7b8593d4b61e7caf63eee41d1521a
4,635
def ENDLEMuEpP_TransferMatrix( style, tempInfo, crossSection, productFrame, angularData, EMuEpPData, multiplicity, comment = None ) : """This is LLNL I = 1, 3 type data.""" logFile = tempInfo['logFile'] workDir = tempInfo['workDir'] s = versionStr + '\n' s += "Process: 'Double differential EMuEpP...
224e72f52ad6b143e51a50962d548084a8e7c283
4,636
def createfourierdesignmatrix_chromatic(toas, freqs, nmodes=30, Tspan=None, logf=False, fmin=None, fmax=None, idx=4): """ Construct Scattering-variation fourier design matrix. :param toas: vector of time series in seconds ...
59420ea9bde77f965f4571bdec5112d026c63478
4,638
def get_word_data(char_data): """ 获取分词的结果 :param char_data: :return: """ seq_data = [''.join(l) for l in char_data] word_data = [] # stop_words = [line.strip() for line in open(stop_word_file, 'r', encoding='utf-8')] for seq in seq_data: seq_cut = jieba.cut(seq, cut_all=False...
8ca306d0f3f4c94f6d67cdc7b865ddef4f639291
4,639
from typing import List from typing import Dict from typing import Any def get_output_stream(items: List[Dict[str, Any]]) -> List[OutputObject]: """Convert a list of items in an output stream into a list of output objects. The element in list items are expected to be in default serialization format for ou...
841bffba3f0e4aeab19ca31b62807a5a30e818f1
4,641
def lvnf_stats(**kwargs): """Create a new module.""" return RUNTIME.components[LVNFStatsWorker.__module__].add_module(**kwargs)
1bdf94687101b8ab90684b67227acec35205e320
4,642
import re def parse_float(string): """ Finds the first float in a string without casting it. :param string: :return: """ matches = re.findall(r'(\d+\.\d+)', string) if matches: return matches[0] else: return None
4adea9226d0f67cd4d2dfe6a2b65bfd24f3a7ecb
4,643
def objectproxy_realaddress(obj): """ Obtain a real address as an integer from an objectproxy. """ voidp = QROOT.TPython.ObjectProxy_AsVoidPtr(obj) return C.addressof(C.c_char.from_buffer(voidp))
6c2f1a2b0893ef2fd90315a2cd3a7c5c5524707f
4,644
def delta_shear(observed_gal, psf_deconvolve, psf_reconvolve, delta_g1, delta_g2): """ Takes in an observed galaxy object, two PSFs for metacal (deconvolving and re-convolving), and the amount by which to shift g1 and g2, and returns a tuple of tuples of modified galaxy objects. ((g1plus, g1minus), (g2plus, g2minu...
13ab29088a1a88305e9f74ab1b43351f2d19b3c6
4,646
def estimateModifiedPiSquared(n): """ Estimates that value of Pi^2 through a formula involving partial sums. n is the number of terms to be summed; the larger the more accurate the estimation of Pi^2 tends to be (but not always). The modification relative to estimatePiSquared() is that the n terms a...
652376bf0964990905bf25b12ad8ab5156975dea
4,647
def pattern_match(template, image, upsampling=16, metric=cv2.TM_CCOEFF_NORMED, error_check=False): """ Call an arbitrary pattern matcher using a subpixel approach where the template and image are upsampled using a third order polynomial. Parameters ---------- template : ndarray T...
adb98b96d9ca778a909868c0c0851bf52b1f0a1b
4,648
def main(argv=[__name__]): """Raspi_x10 command line interface. """ try: try: devices_file, rules_file, special_days_file = argv[1:] except ValueError: raise Usage('Wrong number of arguments') sched = Schedule() try: sched.load_conf(devices...
583df25dc3fb3059d6ed5b87d61a547fc1a11935
4,649
def HexaMeshIndexCoord2VoxelValue(nodes, elements, dim, elementValues): """ Convert hexamesh (bricks) in index coordinates to volume in voxels with value of voxels assigned according to elementValues. dim: dimension of volume in x, y and z in voxels (tuple) elementValues: len(elements) == len(eleme...
8dcab059dd137173e780b7dd9941c80c89d7929c
4,650
def hamiltonian(latt: Lattice, eps: (float, np.ndarray) = 0., t: (float, np.ndarray) = 1.0, dense: bool = True) -> (csr_matrix, np.ndarray): """Computes the Hamiltonian-matrix of a tight-binding model. Parameters ---------- latt : Lattice The lattice the tight-bi...
63df0f8557ba13fe3501506974c402faca1811f5
4,651
def pad_in(string: str, space: int) -> str: """ >>> pad_in('abc', 0) 'abc' >>> pad_in('abc', 2) ' abc' """ return "".join([" "] * space) + string
325c0751da34982e33e8fae580af6f439a2dcac0
4,652
def get_existing_rule(text): """ Return the matched rule if the text is an existing rule matched exactly, False otherwise. """ matches = get_license_matches(query_string=text) if len(matches) == 1: match = matches[0] if match.matcher == MATCH_HASH: return match.rule
9c41241532977b0a30485c7b7609da3c6e75b59c
4,654