content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import io def inscription_summary(request, pk): """ Print a PDF summary of inscription """ candidat = get_object_or_404(Candidate, pk=pk) buff = io.BytesIO() pdf = InscriptionSummaryPDF(buff) pdf.produce(candidat) filename = slugify('{0}_{1}'.format(candidat.last_name, candidat.first_n...
aeedaaff96e3d08ca0dc503ac6641951a4fa804a
29,011
def hello(name='persona', lastmane='exposito'): """Function that return 'name and last name'. name: strung, lastname:string, return: string, """ if name != 'persona': return f'¿Como estas {name}?' return f'Hola {name} {lastname}'
537ffb6beab2ad2c65c4cbf556738c9be1a8467d
29,012
def get_num(prompt: str) -> float: """Function to check if users input is a num""" while True: try: num = int(input(prompt)) return num except Exception as e: print(e)
39fdc0588d20cc2268a98db0a729e7c6044e29a0
29,013
import random def create_negative_mentions(doc, pos_mention_spans, neg_mention_count, max_span_size, context_size, overlap_ratio=0.5): """ Creates negative samples of entity mentions, i.e. spans that do not match a ground truth mention """ neg_dist_mention_spans, neg_dist_mention_...
570c431a3a02505b3c81c2242ae4d3448a17f744
29,014
def show_item(item_id): """Show individual item.""" try: item = db_session.query(Item).filter_by(id=item_id).one() except: flash("This item does not exist") return redirect(url_for('index')) # Make sure that user is authorised to see the item if item.public or item.user_id ==...
5502d904fa02af975af6a52f3c3892133d62061d
29,015
def yaw_from_pose(pose): """ Extract the yaw (orientation) from a pose message. """ quat = np.array([pose.orientation.x, pose.orientation.y, pose.orientation.z, pose.orientation.w]) euler = tf.transformations.euler_from_quaternion(quat) return euler[2]
5112ef95693655af1dce50a2fa51de3d7c42006c
29,016
import logging def create_influxdb_datasource_config(influxdb_parameters, cert, key) -> dict: """ :param influxdb_parameters: The retrieved InfluxDB parameter JSON :param cert: The InfluxDB cert for HTTPS. :param key: The InfluxDB key for HTTPS. :return: data: The datasource JSON to add. """ ...
e57f26336ddad2c56919e776239edaba0fc2ebe7
29,017
def render_incrementals(iterable, **kwds): """helper function for simple incremental_expansion calls :param iterable: sequence of items to incrementally stack :param kwargs: options to pass to incremental_expansion :return: a set of the rendered results from incremental_expansion """ s = set() ...
d545fc237ba6ddaf59c20795cfae1f60197938fc
29,019
import re def get_queues_labels(queue_labels_data): """Returns parsed data for main metrics. Converts input string with raw data to a dictionary.""" queue_regexp = r'QUEUE\(([^)]+)\)' curdepth_regexp = r'CURDEPTH\(([^)]+)\)' maxdepth_regexp = r'MAXDEPTH\(([^)]+)\)' queue_type_regexp = r'TYPE\(...
908aa435c95028d8f34fb35a6cb02da2aa7ca706
29,020
def is_auto(item): """ Checks if a parameter should be automatically determined """ if isinstance(item, float): if item == 9999.9: return True elif isinstance(item, str): if 'auto' in item.lower(): return True return False
fe6320adef43c51cdffd5b5d4a0bf34ac43d9c5a
29,021
from typing import Union def black_scholes_price(S: float, K: Union[float, np.ndarray], is_call: bool, vol: Union[float, np.ndarray], disc: float, T: float, div_disc: float =...
888845c47fc7d5c17921f83321b6b966adfaaf33
29,022
def has_group_perm(user_level, obj, ctnr, action): """ Permissions for groups Groups are assigned a subnet """ if not obj.subnet in [ip_range.subnet for ip_range in ctnr.ranges.all()]: return False return { 'cyder_admin': True, #? 'ctnr_admin': action == 'view', #? ...
aa55bcf846389492734046b8d33c2676ed165763
29,023
def get_tags_with_sha(repo_dir): """ _get_tags_with_sha_ Get list of tags for a repo and return a map of tag:sha """ repo = git.Repo(repo_dir) return {tag.name: tag.commit.hexsha for tag in repo.tags}
d1443ea8289f5588e29517e42da4564cbcc65177
29,024
from typing import List from typing import Tuple def get_reference_sample_name(sample_list: List[Tuple[str, str]]) -> str: """Gets the name from the reference sample, raising an exception if it does not exist in the sample table.""" for sample, sample_type in sample_list: if sample_type == 'yes': ...
5b702c1395fe9c19135279cee7deff870f4707c4
29,025
def form_check(form_field: BoundField, col: str = '') -> dict: """ Делаем бутстраповский чекбокс из джанговского поля формы Фичи: - если после валидации нашлись косяки, показываем их - если в поле есть хелп-текст, то показываем его - опционально передаем в form-group CSS-класс для выстраивания п...
0fbfe9a57c1e496f0726c0bcb65f8cf14a85000e
29,026
import fnmatch def IncludeFiles(filters, files): """Filter files based on inclusion lists Return a list of files which match and of the Unix shell-style wildcards provided, or return all the files if no filter is provided.""" if not filters: return files match = set() for filter in filters: ma...
03d9a6359cd1c88e496f8f8a047f08c868c7b976
29,027
def make_fade_window_n(level_start, level_end, N_total, fade_start_end_idx=None): """ Make a fade-in or fade-out window using information on sample amounts and not time. f_start_end defines between which start and stop indexes the fade happens. """ if not fade_start_end_idx: fade_start_idx,...
7566cc95eb58ee03e7cb90da5a03b7e24f8ea114
29,028
def translate_ethosu_tir_call_extern(tir_call_extern): """This is a dispatcher function to dispatch correct translation call depending on the extern call's first argument""" supported_call_extern = { "ethosu_conv2d": translate_ethosu_conv2d, "ethosu_copy": translate_ethosu_copy, ...
b9cc6ce7b9db7d311695d7d4d1086f9faefca4f8
29,029
def _getSinglePosValueKey(valueRecord): """otBase.ValueRecord --> (2, ("YPlacement": 12))""" assert isinstance(valueRecord, ValueRecord), valueRecord valueFormat, result = 0, [] for name, value in valueRecord.__dict__.items(): if isinstance(value, ot.Device): result.append((name, _ma...
b49e60fdba99f2deb11c002d1632b34bd82226f0
29,030
def top_half(bbox=full_frame()): """Returns a bounding box covering the top half of ``bbox``.""" return make_bbox(bbox['x1'], bbox['y1'], bbox['x2'], (bbox['y1'] + bbox['y2']) / 2.)
a005568dc4d8ca2a99120ca319e66ebf64371a89
29,031
def __command(client, command, default_method, use_bytes=False): """ Private function supporting multiple command formats: - string - function - (function, args, kwargs) """ if is_function(command): return command(client) elif is_list(command): a, kw = (), {} ...
ba6b46820756486c81b757da4b04a0e97c7c7cd7
29,032
def designate_node(fqdn, type): """ """ execCmd = ' '.join([BDVAGENT, OPTION, 'designate', type, fqdn]) return executeCmd(execCmd)
e1f89a01c182bb1302c6997fb2a5461b09cd5319
29,033
def get_identity_for_user(user): """Get the Identity for the user specified via email or ID.""" identity = None if user is not None: # note: this seems like the canonical way to go # 'as_user' can be either an integer (id) or email address u = current_accounts.datastore.get_use...
a7cdd089ab25ee67de21d22ab1811dca3fbab0df
29,035
import torch def MetaOptNetHead_Ridge(query, support, support_labels, n_way, n_shot, lambda_reg=50.0, double_precision=False): """ Fits the support set with ridge regression and returns the classification score on the query set. Parameters: query: a (tasks_per_batch, n_query, d) Tensor. ...
07e83a8dd597a332c03f9ef01633c1c6007b9fc8
29,036
def getUserZaduzenja(userClass): """ Vraca zaduzenja datog korisnika """ _result = [] for k,v in _rented.items(): if int(k) == userClass.GetCardNumber(): _result.append(v) return _result
5dc236baaad480c7169724685d8c6035a9839a61
29,038
def add_testcase_properties(xml_obj, tcconfig=None): """add properties to testcases""" if xml_obj.tag == "testsuites": expression = "./testsuite/testcase" else: expression = "./testcase" multile_test_ids = {} for testcase in xml_obj.findall(expression): tcproperties = et.El...
ca8b59367e4cff027ca3eae81fd740a7bff121cd
29,039
def calc_rho(RhoRef,T,S,alpha=2.0E-4, beta=7.4E-4): """----------------------------------------------------------------------------- calc_rho calculates the density profile using a linear equation of state. INPUT: state: xarray dataframe RhoRef : reference density at the same z as T and S slices. C...
844a324481fccf2e695caac282a6f8711546c38f
29,040
import gettext def get_request_details(request_id=None, srp_request=None): """Handles responding to all of the :py:class:`~.models.Request` detail functions. The various modifier functions all depend on this function to create the actual response content. Only one of the arguments is required. Th...
e47197af84c88f59b866e0476da32055091dbb2b
29,041
import numpy from typing import Tuple from typing import Optional from typing import Dict from typing import Any import copy import itertools def packSpecialData( data: numpy.ndarray, paramName: str ) -> Tuple[Optional[numpy.ndarray], Dict[str, Any]]: """ Reduce data that wouldn't otherwise play nicely wi...
ec07057f4c38b8169cd1bc04ee19dd79a585a050
29,042
def swapaxes(x, axis1, axis2): """Swap two axes of a variable. Args: x (~chainer.Variable): Input variable. axis1 (int): The first axis to swap. axis2 (int): The second axis to swap. Returns: ~chainer.Variable: Variable whose axes are swapped. """ return Swapaxes(a...
274f6960fb463e7660b0bf6e963f51957ab3b728
29,043
def add_header(img, labels, mark_midpoints=True, header_height=20): """Adds labels to the image, evenly distributed across the top. This is primarily useful for showing the names of channels. Args: img: A PIL Image. labels: list of strs. Labels for segments to write across the top. mark_midpoints: b...
f3d8d69009dd72f7e7e9c0305b248492cdc076fc
29,044
def predict_by_lr_model(test_feature, lr_model): """ predict by lr_model (调用 sklearn 实例方法) """ result_list = [] #存储每个样本label为1的概率 prob_list = lr_model.predict_proba(test_feature) for index in range(len(prob_list)): result_list.append(prob_list[index][1]) #下标为0的对应label为0的概率,下标为1的对应label为1...
03ea185aa4398e8ccb7449d9e32006dd391e9c13
29,045
def _default_schedule(outs): """Default schedule for gpu.""" outs = [outs] if isinstance(outs, tvm.tensor.Tensor) else outs s = tvm.create_schedule([x.op for x in outs]) scheduled_ops = [] def traverse(op): if tag.is_broadcast(op.tag) or op.tag in ['bbox_score', 'sorted_bbox']: s...
b2e328e04e2ad522580e8966f66eb52d4f4b0d4d
29,046
def get_track_reviewer_abstract_counts(event, user): """Get the numbers of abstracts per track for a specific user. Note that this does not take into account if the user is a reviewer for a track; it just checks whether the user has reviewed an abstract in a track or not. :return: A dict mapping t...
c73b00bd641e20c6b6f3c1e51173b6162e8f76ee
29,047
def fit_logistic(X, w, var_prior, X_test, initial_phi): """MAP logistic regression. Input: X - (D + 1) * I training data matrix, where D is the dimensionality and I is the number of training examples. w - I * 1 vector containing world states for each e...
ba425ca35cbb1fe5359019ed46d4756daa62779b
29,048
from typing import Optional from enum import Enum def middle_drag_and_drop( element_path1: UI_Element, element_path2: UI_Element, duration: Optional[float] = None, mode: Enum = MoveMode.linear, timeout: Optional[float] = None) -> UI_Element: """ Drags and drop with midd...
f7325683af4b0891e68add86a0efc6abc9b5044d
29,049
def get_pi0(pv, lambdas): """ Compute Storey's C{pi0} from p-values C{pv} and C{lambda}. this function is equivalent to:: m = len(pv) return [sum(p >= l for p in pv)/((1.0-l) * m) for l in lambdas] but the above is C{O(m*n)}, while it needs only be C{O(m+n) (n = len(la...
4937aaa13ce3f5dda18fa3669e535c4d88be3ad6
29,050
def read_accelerometer(serial, calibration): """ Reads the raw values from the Arduino, parses them into separate variables and uses the calibration data to normalize the data Args: serial: a reference to the serial connection with the Arduino calibration: a reference to the calibration...
3c5537e2a017f57dca8dccd24c2ba083a9c47345
29,051
def get_access(name): """Get access based on name In Python __var__ refers to a private access _var refers to protected access and var would refer to public access """ assert isinstance(name, str), "Expecting name to be a string" if len(name) > 4 and "__" == name[:2] and "__" == name[-2:]: ...
ffe072ed1820ce0536533a5882af1e1270780744
29,052
def run_query_series(queries, conn): """ Iterates through a list of queries and runs them through the connection Args: ----- queries: list of strings or tuples containing (query_string, kwargs) conn: the triplestore connection to use """ results = [] for item in queries: ...
7a3e920663222b57233e9a01d1b3cacb039a02eb
29,053
def _get_key(block_id, block_dict, extra_args): """ Given a dictionary, return an element by ``key``. block_id: Block id block_dict: key: (Mandatory) Key value to get starting_dict: (Optional) Starting dictionary param ...
1c966f9d4966ff9eaafde60fce13f88a176def3d
29,054
def AP(predictions, scores): """ Computes the average precision per class, the average precision and the interpolated average precision at 11 points :param predictions: list of lists of every class with tp, fp and fn. fps are zeros, the others one, indicating this is a ground truth :param scores: confi...
bc8b98d91153487261a76c07befe4cce6211d0d3
29,055
def _sample_optimization_test_problems( rng): """Sample an optimization test function problem.""" is_noise = utils.sample_bool(rng, 0.5) return { "problem": rng.choice(sorted(_opt_test_problems.keys())), "noise_stdev": utils.sample_log_float(rng, 0.01, 10.0) if is_noise else 0....
47edaa72d9d0f43e3c9c67684b686f5abbeb74d8
29,056
def get_domain_id_field(domain_table): """ A helper function to create the id field :param domain_table: the cdm domain table :return: the id field """ return domain_table + '_id'
5805da82b4e57d14d4105d92a62cf4b5cc4bc3f2
29,057
def construct(symbol, strategy, chains, **kwargs): """ This is a convenience method to allow for creation of option spreads from predefined sources. :param symbol: The symbol of the option chains :param strategy: The option strategy filter to use :param chains: Option chains data to use. This d...
99ff1d3e9cb6a4718fc06e767904a95340ca9b6f
29,058
def get_delete_query(table_name: str) -> str: """Build a SQL query to delete a RDF triple from a MVCC-PostgreSQL table. Argument: Name of the SQL table from which the triple will be deleted. Returns: A prepared SQL query that can be executed with a tuple (subject, predicate, object). """ return f"...
9ff605f77caa7e8d2e6a7ea1e2b82c22821c86dd
29,059
def _parse_ipv6(a): """ Parse IPv6 address. Ideally we would use the ipaddress module in Python3.3 but can't rely on having this. Does not handle dotted-quad addresses or subnet prefix >>> _parse_ipv6("::") == (0,) * 16 True >>> _parse_ipv6("1234:5678::abcd:0:ff00") (18, 52, 86, 120, 0...
9a999df1cd352fe175801cbe4476f2080cc5d37d
29,060
def weighted(weights,metric='categorical_accuracy'): """ weighted metric Args: - weights<list>: * a weight for each value in y_true - metric<str|metric>: * snake-case strings will be turned to camel-case * if metric is not a string the passed metric will be r...
ffb356a178c50c517485d126c90724b5bc408ad2
29,061
from typing import Tuple def compute_reg_strs(product_graph: TwoPlayerGraph, coop_str: bool = False, epsilon: float = -1) -> Tuple[list, dict, TwoPlayerGraph]: """ A method to compute strategies. We control the env's behavior by making it purely cooperative, pure adve...
99d3632ed6d692c1531a4420f794cd84df5c3264
29,062
import torch from typing import Tuple import functools def make_tanh_warp_grid(matrix: torch.Tensor, warp_factor: float, warped_shape: Tuple[int, int], orig_shape: Tuple[int, int]): """ Args: matrix: bx4x4 matrix. warp_factor: The warping factor....
3f1226ea19006c5cbf683deff15a120ffb7c7af6
29,063
def insertion_sort(arr): """ Returns the list 'arr' sorted in nondecreasing order in O(n^2) time. """ for i in range(1,len(arr)): key = arr[i] j = i-1 while j >= 0 and arr[j] > key: arr[j+1] = arr[j] j = j-1 arr[j+1] = key return arr
cafd83cd31cbadcbc0a5c3aaff7d21f3ae907083
29,064
def tokens_refresh_post(body=None, project_name=None, scope=None): # noqa: E501 """Refresh tokens for an user Request to refresh OAuth tokens for an user # noqa: E501 :param body: :type body: dict | bytes :param project_name: Project Name :type project_name: str :param scope: Scope for ...
58e59e54cf53ecf23ca2e45f62b00094adfb49ab
29,065
def load_xml_data(path, start_node="header", search_node="name"): """ load the XML data """ retval = [] fetched_xml = minidom.parse(path) item_list = fetched_xml.getElementsByTagName(start_node) for value in item_list: retval.append(value.attributes[search_node].value) return ret...
6a281b2b9ce3fac22ec32afa151438c8259b4f94
29,066
def saturationcheck(thermal_data,startframe,sat_threshold=0.9): """ Determine the fraction of thermal_data that is saturated on or after startframe (0 based). It is assumed the highest temperature recorded in thermal_data for a particular pixel is the saturation value and that the thermal data has alre...
d706c14c9ce59ad738cf6817240c5095664ad866
29,067
def make_image_justification(g, doc_id, boundingbox, system, confidence, uri_ref=None): """ Marks a justification for something appearing in an image. :param rdflib.graph.Graph g: The underlying RDF model :param str doc_id: A string containing the document element (child) I...
8561c8b890cd53318fa3e76ce66fd3ec7e204858
29,068
def update_u_gates(drag_params, pi2_pulse_schedules=None, qubits=None, cmd_def=None, drives=None): """ Update the cmd_def with new single qubit gate values Will update U2, U3 Args: drag_params: list of drag params pi2_pulse_schedules: list of new pi/2 gate as a pulse s...
f5719f9d14c0f37d347629207484e200b0934b1e
29,069
import select def make_acc_fun(network_apply_fun, num_outputs=1): """ Given a network function and number of outputs, returns an accuracy function """ if num_outputs == 1: prediction_function = lambda x: (x >= 0.).astype(jnp.int32) else: prediction_function = lambda x: x.argmax(axis=-1).astype(jnp.in...
977d18c7b3309abee5ab3233d5355a72712f00dd
29,071
from typing import Union from typing import Dict from typing import Any from typing import List from typing import Tuple def upsert_all( engine: Engine, table: Table, data: Union[Dict[str, Any], List[Dict[str, Any]]], ) -> Tuple[int, int]: """ Update data by primary key columns. If not able to upd...
070c0091bdbef01459c0d8a46340e5997bdf0a34
29,073
def index(): """Root route test""" return "Weights route"
c2a609f067a8155f16bd2a638a7a5c9f399a1575
29,074
from typing import Optional def get_backend_health(backend_name: Optional[str] = None, backend_set_name: Optional[str] = None, network_load_balancer_id: Optional[str] = None, opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetBackendHealthR...
6bd328878a45fa128e13bbe2fd6cd9d2c3f80129
29,076
def calculate_velocity(start_longitude, start_latitude, start_time, end_longitude, end_latitude, end_time): """ Finds the magnitude of the velicty, in kilometers per hour. """ distance_traveled = calculate_distance(start_longitude, start_latitude, ...
1a36fce9340de4fc6271a9d3bc3515b3b8806293
29,078
def get_raw_html_pbp(season, game): """ Loads the html file containing this game's play by play from disk. :param season: int, the season :param game: int, the game :return: str, the html pbp """ with open(get_game_pbplog_filename(season, game), 'r') as reader: page = reader.read()...
b2bee91be984e8d6782ee0bfabb32fc9e43dc4f4
29,079
def prepare_inputs_by_partition( df, partition_col, split_date, categorical_cols=None, output_col=0, lookback=12, num_predictions=12, ): """ Lags, splits and normalizes a dataframe based around a partition. """ partitions = df[partition_col].unique() scalers = {} trai...
95bdd21be019d7ed9f27797d8268c43c64d2c22e
29,080
def read_fits_data(filename, dtype="float32", **kwargs): """ Read fits image into numpy array. Args: filename (str): The name of ther file to read. dtype (str, optional): The data type for the array. Default: float32. **kwargs: Parsed to fits.getdata. Returns: np.array: The i...
d8e5fa22c636cfa263b0acfdabfa642e87ef486a
29,081
def streamplot(UV, ax=None, map=None, geodata=None, drawlonlatlines=False, basemap_resolution='l', cartopy_scale="50m", lw=0.5, cartopy_subplot=(1,1,1), axis="on", **kwargs): """Function to plot a motion field as streamlines. Parameters ---------- UV : array-like ...
bd634a5602ae0ec2a95a0e9d918a872d91691296
29,082
import random def random_add_text(new_canvas: np.ndarray): """ :param new_canvas: RGBA image. :return RGBA image. """ # font font_list = [ cv2.FONT_HERSHEY_SIMPLEX, cv2.FONT_HERSHEY_PLAIN, cv2.FONT_HERSHEY_DUPLEX, cv2.FONT_HERSHEY_COMPLEX, cv2.FONT_HERSH...
dc5f0a63ed8ccfd6cd2aee798f8b70706c6019d0
29,083
import torch def len_to_mask(len_seq, max_len=None): """len to mask""" if max_len is None: max_len = torch.max(len_seq) mask = torch.zeros((len_seq.size(0), max_len)) for i, l in enumerate(len_seq): mask[i, :l] = 1 return mask
58cf7b3de6e28a541531ce5a6f516671493b5e08
29,084
def get_games_for_steamid(steamid: str) -> set[tuple[int, str]]: """Gets the games owned by a Steam user Parameters ---------- steamid : str The user's 64-bit Steam ID Returns ------- set[tuple[int, str]] The set of games this user owns, in tuples of appid and game name """ body = steam_request('IPlayer...
7edbf85fcb5a337681c1aa21bb54948be9122fa2
29,085
from typing import Callable from typing import Any import functools def normalize(how: str) -> Callable[..., Any]: """Apply a row or column normalization to a pandas DataFrame argument. Parameters ---------- how : str The normalization method to apply. Can be one of {'row', 'colum', 'minmax',...
5e837d0e8754ef4d2fc42d0b9484f1f699fb3b67
29,087
from typing import Union def resize_image( image: np.ndarray, target_shape: Union[list, tuple], ground_truth: np.ndarray = None, ): """ @param `image`: Dim(height, width, channels) @param `target_shape`: (height, width, ...) @param `ground_truth`: [[center_x, center_y, w, h, class_...
8a3474728546605a462f4ddbab551af0afa675f5
29,090
def _get_security_item(security_type, exchanges, code=None): """ get the security item. Parameters ---------- code : str the security code,default: None security_type : str the security type exchanges : list the exchanges Returns ------- DataFrame ...
a0c8b555dbdf3c5fa1b5f7b69fceeb7bea4f9c8f
29,091
def generate_launch_description(): """Launch file for training node to training network.""" return LaunchDescription([ DeclareLaunchArgument( 'yaml_file', default_value=[get_default_file_path('template.yaml')], description='Parameter file for experiment.' ), ...
ca388302307fcef3e57d672ef3375751a297c9a3
29,092
def plot_density( data, data_labels=None, var_names=None, credible_interval=0.94, point_estimate="mean", colors="cycle", outline=True, hpd_markers="", shade=0.0, bw=4.5, figsize=None, textsize=None, ): """Generate KDE plots for continuous variables and histograms for ...
1d0ef2ea506a6c6013844aa7d43ca867332903ca
29,093
def _vivid_light(a, b): """ :type a: ImageMath._Operand :type b: ImageMath._Operand :rtype: ImageMath._Operand """ color_burn = _color_burn(a, b * 2) color_dodge = _color_dodge(a, 2 * (b - 128)) return color_burn * (b < 128) + color_dodge * (b >= 128)
7465a4441dd05b0e6d83acaee6a9c387654899fb
29,094
def normalize_cookies(cookies): """Takes cookies from Selenium or from Python Requests and converts them to dict. This throws away information that Selenium otherwise has (like the host and such), but a dict is essentially all we need. """ requests_cookies = {} if type(cookies) == list: ...
5a57fc15e7545427e8797439264245f1b7bebe7c
29,095
def from_file(filename): """Create a list structure from a special format of file. Args: filename: in which the formated string is located. Returns: A 2d list object. """ with open(filename, 'r') as f: return from_text(f.read())
1035da5c6709be1a0429b955a6ef88d6877a2101
29,096
def plot_data(data): """ Returns a scatter plot that visualizes the passed dataframe. Currently, tailored to merely encapsulate very specific visualization. """ # lets play with namedtuples for fun. kinda like a struct-ish PlotArgs = namedtuple('PlotArgs', ['color', 'label', 'marker']) plottin...
98f4f517894a9e5b16c9b471cf28bbaae72007ff
29,097
def rotate(img): """ Rotation: OpenCV provides scaled rotation with adjustable rotation center so that you can rotate at any location you prefer. To find this modified transformation matrix, OpenCV provides a function, cv2.getRotationMatrix2D. Check below example which rotates the image by 9...
89bb652c43d61896db74be1a97bffd492d7ab95f
29,098
import hashlib def get_sign(data_dict, key): """ 签名函数 :param data_dict: 需要签名的参数,格式为字典 :param key: 密钥 ,即上面的API_KEY :return: 字符串 """ params_list = sorted(data_dict.items(), key=lambda e: e[0], reverse=False) # 参数字典倒排序为列表 params_str = "&".join(u"{}={}".format(k, v) for k, v in params_lis...
ea7ee65cd3ae72e19293dc851255bc0f3ad4b321
29,100
def string(): """String representation.""" return "{:s}".format('something')
d13ae4fe229f767c515b0f0d6439ac61c6bfdbe8
29,101
def find_films_in_location(films: pd.DataFrame) -> pd.DataFrame: """finds films filmed in certain location Args: films (pd.DataFrame): films with their locations Returns: pd.DataFrame: films which were filmed in certain location """ films.dropna(inplace=True) # change for more ...
91801357aab19e2a263951907fe74f114b833f68
29,102
def _if_installed(pname): """Run if the given program name is installed. """ def argcatcher(func): def decorator(*args, **kwargs): envs = [x for x in args if hasattr(x, "system_install")] env = envs[0] if envs else None if shared.which(pname, env): ...
63eb3a0a3c2b2b6c7370ee4db449e6e3e1d2c84e
29,104
def check_gym_environments(env: gym.Env) -> None: """Checking for common errors in gym environments. Args: env: Environment to be checked. Warning: If env has no attribute spec with a sub attribute, max_episode_steps. Raises: AttributeError: If env has no observati...
95d3a3b7804981cb8308269580359111b257eefe
29,105
def WI(bands: dict) -> xr.DataArray: """ Water Index (2015): Fisher et al. (2016) Args: bands (dict): Bands as {band_name: xr.DataArray} Returns: xr.DataArray: Computed index """ return ( 1.7204 + 171 * bands[obn.GREEN] + 3 * bands[obn.RED] - 70 ...
400c7277d5d7cca07df7953b0db957f3d4fdfd0a
29,106
import io def readZipData(filePath): """ Opening the zip file in READ mode and transform scalars.csv to data frame :param filePath: path to zip-file :return: data frame with scalars.csv content """ with ZipFile(filePath.as_posix(), 'r') as zip: scalars = None for i in zip.namel...
2efd90426366754454f13a8c5e9e61ed2a1c150d
29,107
def calc_relative_scale(skeleton, ref_bone_lengths, joint_tree) -> (float, float): """Calculate the factor by which the reference is larger than the query skeleton. Args: skeleton (torch.DoubleTensor): The query skeleton. ref_bone_lengths (torch.DoubleTensor): The reference skeleton bone length...
cf1bbf2692666e393eb50eeb4ae9d0724af78c7f
29,108
def vertical_move(t, v_speed=2/320): """Probe moves vertically at v_speed [cm/s]""" return 0.*t, 0*t, v_speed*t
eb6a066bf6b6659728647c78dd7673a3d45b250d
29,109
def get_favored_peaks(rama_key): """ returns exact favored peaks with their score value """ assert rama_key in range(6) if rama_key == RAMA_GENERAL: return [((-115.0, 131.0), 0.57068), ((-63.0, -43.0), 1.0), ((53.0, 43.0), 0.323004), ((53.0, -127.0), 0.0246619)] if r...
79bf814becbbf36796e229f69d0a99cd8ef1716e
29,110
def get_all_tablespace_acls(conn): """ Returns: List of :class:`~.types.RelationInfo` objects. """ return [RelationInfo(**row) for row in conn.execute(_pg_tablespace_stmt)]
561514b7986d374ba1dc7a4addf4d0588b53e59b
29,111
import regex def chunk_pars(content): """Given the context contained between `\\beginnumbering` and `\\endnumbering`, return list of paragraphs. This is able to handle paragraphs demarcated by `\\pstart` and `\\pend` as well as when `\\autopar` is used (see §5.2.2 of the reledmac documentation). ...
958890791c67c90a9ed3264e82caca9bfebb5885
29,112
def bound(): """ Generate boundary for testing""" bound = data.Boundary() bound.degree = 3 bound.start = np.array([0.0, 0.0, 0.0]) bound.end = np.array([1.0, 0.0, 0.0]) bound.num_ctrlpts = 5 return bound
210636e3e0618ff8b5ffd48b48f4aa035a38e928
29,113
from typing import Union def to_tensor(pic: Union[Image, np.ndarray]) -> Tensor: """Convert a ``PIL Image`` or ``numpy.ndarray`` to tensor.""" if not (F_pil._is_pil_image(pic) or _is_numpy(pic)): raise TypeError(f"input pic should be PIL image or numpy.ndarray, Got {type(pic)}") if _is_numpy(pic) ...
26040d594cee200200945d7561bc9e6bcda95f01
29,114
import numpy def dummy_image(): """Create a dummy image""" x = numpy.linspace(-1.5, 1.5, 1024) xv, yv = numpy.meshgrid(x, x) signal = numpy.exp(- (xv ** 2 / 0.15 ** 2 + yv ** 2 / 0.25 ** 2)) # add noise signal += 0.3 * numpy.random.random(size=signal.shape) return signal
8cbf5f31cde69b8ac775114277cee8f88d6dd932
29,115
def update_user(uid, **kwargs): """Updates an existing user account with the specified properties. Args: uid: A user ID string. kwargs: A series of keyword arguments (optional). Keyword Args: display_name: The user's display name (optional). Can be removed by explicitly passing ...
0b52b7e42f286861b43e6e2e25a9547b1cd354d7
29,118
def add_center_dist(nusc: NuScenes, eval_boxes: EvalBoxes): """ Adds the cylindrical (xy) center distance from ego vehicle to each box. :param nusc: The NuScenes instance. :param eval_boxes: A set of boxes, either GT or predictions. :return: eval_boxes augmented with center dista...
5a0c09f9de689efe294a6ce500ba4dbf09885149
29,119
def check_address(btc_addr, network='test'): """ Checks if a given string is a Bitcoin address for a given network (or at least if it is formatted as if it is). :param btc_addr: Bitcoin address to be checked. :rtype: hex str :param network: Network to be checked (either mainnet or testnet). :type n...
9f236f5d6ccf2f28944c577e2ce8fbfb2c2a58b8
29,120
import time def format_time(record): """Format time to ISO 8601. https://en.wikipedia.org/wiki/ISO_8601 """ utc_time = time.gmtime(record.created) time_string = time.strftime('%Y-%m-%d %H:%M:%S', utc_time) return '%s.%03dZ' % (time_string, record.msecs)
ea07736965711a214a738f5443f68cf02e20fcb2
29,121
def _cb_decode(s, maxsize=8192): """Decode a list of IDs from storage in a cookie. ``s`` is text as encoded by ``_cb_encode``. ``maxsize`` is the maximum size of uncompressed data. ``0`` means no limit. Return a list of text IDs. """ dec = decompressobj() squashed = unquote(s).encode('lati...
bf1239cf33bf83b1163d96641a20e4adc3e83221
29,122
def validate_model(df, fix=False): """ Validates the form of a model dataframe. A model dataframe must look something like this: pos val_A val_C val_G val_T 3 1.1 4.3 -6.19 5.2 4 0.01 3.40 -10.5 5.3 5 0 1.4 10.9 231.0 A 'po...
81c8663934c2ae33318635dd68939cff5652912b
29,123
def create_training_instances(input_files, tokenizer, max_seq_length, dupe_factor, short_seq_prob, masked_lm_prob, max_predictions_per_seq, rng): """Create `TrainingInstance`s from raw text.""" all_documents = [[]] # Input file format: # (1) One sente...
0274db246e701ac1da78564707c851c9e295a21e
29,124