content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
from operator import add def set(isamAppliance, name, properties, attributes=None, description=None, type="JavaScript", new_name=None, check_mode=False, force=False): """ Creating or Modifying a JavaScript PIP """ ret_obj = search(isamAppliance, name=name) id = ret_obj['data'] if id =...
6c7f097eb22a1f3033dce2cdf3264bff5f7c9acb
29,708
import logging def init_model(model, opt, argv): """select the network initialization method""" if hasattr(opt, 'weight_init') and opt.weight_init == 'xavier': network_weight_xavier_init(model) elif hasattr(opt, 'weight_init') and opt.weight_init == 'MSRAPrelu': network_weight_MSRAPrelu_in...
5c53efd15af6403a6323d25dc877dc652e4a49b1
29,709
import math def shoulders_up(x, y, max_angle=10): """ 1:"Neck", 2:"RShoulder", 5:"LShoulder". looks at line from left shoulder to neck, and line from right shoulder to neck if either are not straight returns 1 if both are flat (slope of 0 or close to 0) returns 1 """ left_degre...
2a6adce5dad431c91cac77bd79e4011964f76341
29,711
def str(x: i32) -> str: """ Return the string representation of an integer `x`. """ if x == 0: return '0' result: str result = '' if x < 0: result += '-' x = -x rev_result: str rev_result = '' rev_result_len: i32 rev_result_len = 0 pos_to_str: list...
6af580da343eb6adab58021eb489cf837b50571c
29,712
def grad_spsp_mult_entries_x_reverse(b_out, entries_a, indices_a, entries_x, indices_x, N): """ Now we wish to do the gradient with respect to the X matrix in AX=B Instead of doing it all out again, we just use the previous grad function on the transpose equation X^T A^T = B^T """ # get the transp...
64e5fbf5ca12fb9516c7aab2a357823c201d3d5a
29,713
def execute_until_false(method, interval_s): """Executes a method forever until the method returns a false value. Args: method: The callable to execute. interval_s: The number of seconds to start the execution after each method finishes. Returns: An Interval object. """ interval = Interval...
eee730604ea98080e669d02f18a6ca55c4a4fe97
29,715
def vecnorm(a): """Return a/|a|""" return a / mdamath.norm(a)
425de4c8ddae138e1528ada448f86781b4c5130e
29,716
def count_qubits(operator): """Compute the minimum number of qubits on which operator acts. Args: operator: FermionOperator, QubitOperator, DiagonalCoulombHamiltonian, or PolynomialTensor. Returns: num_qubits (int): The minimum number of qubits on which operator acts. Rais...
9963c7b8202a825725ca3906b95f16d0243f81ed
29,717
def datenum_to_date(date_num): """Transform date_num to datetime object. Returns pd.NaT on invalid input""" try: total_seconds = round(dt.timedelta(days=date_num - 366).total_seconds()) return dt.datetime(1, 1, 1) + dt.timedelta(seconds=total_seconds) - dt.timedelta(days=1) except Overf...
f2a523f0e1c1af15835ae042fdeac8ebcf0a5717
29,718
def save_ground_truth_part(name, tuple_path, mean, sem, std, sestd): """Saves a ground truth part to strings. This is meant to be called with outputs of `nest.flatten_with_tuple_paths(ground_truth_mean)`. Args: name: Python `str`. Name of the sample transformation. tuple_path: Tuple path of the part o...
a4b769383dd0b250375205efeed363161b28ed0a
29,719
def parse_cpe(cpe): """ Split the given CPE name into its components. :param cpe: CPE name. :type cpe: str :returns: CPE components. :rtype: list(str) """ ver = get_cpe_version(cpe) if ver == "2.2": parsed = [cpe22_unquote(x.strip()) for x in cpe[5:].split(":")] if ...
4dfbac57d3719a1c6ed00b5884be1321800827f5
29,720
def draw_points(xs, ys, covs, M): """ Resample a set of points M times, adding noise according to their covariance matrices. Returns ------- x_samples, y_samples : np.array Every column j, is x[j] redrawn M times. Has M rows, and every row is a realization of xs or ys. """ #...
5609efcf6ba42fc2a059d308e8391b6057de3a16
29,721
def k_folds_split(raw_indexes, n_splits, labels=default_pars.validation_pars_labels, shuffle=default_pars.validation_pars_shuffle, random_state=default_pars.random_state, return_original_indexes=default_pars.validation_pars_return_original_indexes): """Splits a raw set of indexes...
77394ca5d345d97423abaa0fe421e50cb0017762
29,722
def element_wise_entropy(px): """ Returns a numpy array with element wise entropy calculated as -p_i*log_2(p_i). Params ------ px (np.array) Array of individual probabilities, i.e. a probability vector or distribution. Returns ------- entropy (np.array) Array of element...
7637cac96e51ce6b89a395c306a6104e77bcef0d
29,723
def score_page(preds, truth): """ Scores a single page. Args: preds: prediction string of labels and center points. truth: ground truth string of labels and bounding boxes. Returns: True/false positive and false negative counts for the page """ tp = 0 fp = 0 fn = ...
25b3d4280db734ded586eb627fe98d417164601d
29,724
import re def _validate_eida_token(token): """ Just a basic check if the string contains something that looks like a PGP message """ if re.search(pattern='BEGIN PGP MESSAGE', string=token, flags=re.IGNORECASE): return True return False
746fbd011b38abab43be983a1a054505526dcf78
29,725
def dn_histogram_mode_5(y, y_min, y_max): """ Mode of z-scored distribution (5-bin histogram) """ return histogram_mode(y, y_min, y_max, 5)
0dc10f46136e60e2523f4ca79449f18aaedd4854
29,726
def _make_element(spec, parent, attributes=None): """Helper function to generate the right kind of Element given a spec.""" if (spec.name == constants.WORLDBODY or (spec.name == constants.SITE and (parent.tag == constants.BODY or parent.tag == constants.WORLDBODY))): return _Attac...
7635e8380e8238541544495f250e78a5da3ad441
29,727
def nlf_css(parser, token): """Newsletter friendly CSS""" args = token.split_contents() css = {} css_order = [] for item in args[1:]: tag, value = item.split("=") tag, value = tag.strip('"'), value.strip('"') css[tag] = value css_order.append(tag) nodelist = parse...
eadf74cdd6e58fb4e1551f1b951ad74226e175c2
29,730
def data_context_connectivity_context_connectivity_serviceuuid_requested_capacity_bandwidth_profile_peak_information_rate_put(uuid, tapi_common_capacity_value=None): # noqa: E501 """data_context_connectivity_context_connectivity_serviceuuid_requested_capacity_bandwidth_profile_peak_information_rate_put create...
c9ee5c8751e8424732f066598525a44d1c66d1c5
29,731
import logging def _get_default_dataset_statistics( statistics: statistics_pb2.DatasetFeatureStatisticsList ) -> statistics_pb2.DatasetFeatureStatistics: """Gets the DatasetFeatureStatistics to use for validation. If there is a single DatasetFeatureStatistics, this function returns that. If there are multi...
8466e67c9ea5d795ea9b6c16c637b9a55048056c
29,732
from typing import Callable from re import A def foldr(_folder: Callable[[A, B], B], _init: B, _linked_list: LinkedList[A]) -> B: """ foldr """ if _linked_list.content is None: return _init else: head = _linked_list.content[0] tail = _linked_list.content[1] return _folder(h...
93aa3749442d8028dd115619e358e8fcf40ada46
29,733
def get_per_lane_sample_dist_plot(sample_data: pd.DataFrame) -> dict: """ A function for returing sample distribution plots :params sample_data: A Pandas DataFrame containing sample data :returns: A dictionary containing sample distribution plots """ try: lane_plots = dict() for...
143094fc909ac9044c5986c958cff79e9e218414
29,734
def mark_volatile(obj): """DEPRECATED(Jiayuan Mao): mark_volatile has been deprecated and will be removed by 10/23/2018; please use torch.no_grad instead.""" return stmap(_mark_volatile, obj)
2e299889fe7982069fb5987f6af0e56ae365a9ee
29,735
def list_keys(bucket): """ Lists all the keys in a bucket. :param bucket: (string) A bucket name. :return: (string list) Keys in the bucket. """ _check_bucket(bucket) bucket_path = _bucket_path(bucket) keys = [] for key_path in bucket_path.iterdir(): keys.append(key_path.name...
0a84c72165cf76970221974196911853d0db027a
29,736
def h6(content, accesskey:str ="", class_: str ="", contenteditable: str ="", data_key: str="", data_value: str="", dir_: str="", draggable: str="", hidden: str="", id_: str="", lang: str="", spellcheck: str="", style: str="", tabindex: str="", title: str="", translate...
c68a5ba229643571ce49e535b32e99580443e56c
29,737
def extractUniversesWithMeaning(item): """ """ vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title']) if not (chp or vol) or 'preview' in item['title'].lower(): return None if 'Angel of Death' in item['title']: return buildReleaseMessageWithType(item, 'Angel of Death', vol, chp, frag=frag, ...
0a00cc344bdb1d5a2498252f529536b2c58f2825
29,738
def get_provenance(message): """Given a message with results, find the source of the edges""" prov = defaultdict(lambda: defaultdict(int)) # {qedge->{source->count}} results = message['message']['results'] kg = message['message']['knowledge_graph']['edges'] edge_bindings = [ r['edge_bindings'] for r...
1f6dfe9e48da49b72cb55f3f949146db3db164f2
29,739
def bricklinkColorToLEGO(colornum): """ Get the LEGO equivalent to a bricklink color number if it exists :param colornum: :return: """ default = {"name": "Unknown", "Lego": colornum, "BrickLink": colornum} if colornum < 0: return default for color in color_data: if colo...
9ed77c271168025c5864a28624470c26ae3a0a9e
29,740
def bounds(gdf): """Calculates the bounding coordinates (left, bottom, right, top) in the given GeoDataFrame. Args: gdf: A GeoDataFrame containing the input points. Returns: An array [minx, miny, maxx, maxy] denoting the spatial extent. """ bounds = gdf.to...
48242e870edd1db9b1191518c4b9ba7433420610
29,741
def powerport_get_row_boot_strap (port_id, raw = False): """ Get boot strapping setting """ result = powerport_get_port_status (port_id + 24, "pdu", raw) state = result.pop ("Port State", None) if (state): result["Boot Strap"] = "Normal" if (state == "Off") else "Network" ...
00d41e0a505c6d88ce44c4a701865556ccff0f89
29,743
def inv_ltri(ltri, det): """Lower triangular inverse""" inv_ltri = np.array((ltri[2], -ltri[1], ltri[0]), dtype=ltri.dtype) / det return inv_ltri
539bbcec02286f991d5cc426ebe631d1cbe0b890
29,744
def create_dummy_review(user, title='Review 1'): """Simple function for creating reviews of a user""" review = Review.objects.create( reviewer=user, title=title, rating=5, summary='This is my first review!!!', ip='190.190.190.1', ...
ffa9ad526072fa48eff513f9b6d10628e700a266
29,745
def check_user(update): """verify that a user has signed up""" user = update.message.from_user if db.tel_get_user(user.id) is not None: return True else: return False
6654ba29d15158b63f78cea16d796f26f9199b07
29,747
def acmg(): """Calculate an ACMG classification from submitted criteria.""" criteria = request.args.getlist("criterion") classification = get_acmg(criteria) return jsonify(dict(classification=classification))
83e70afcd986ca8b7fe0e442130615cff2e84a1b
29,748
def import_bin(filename, **kwargs): """ Read a .bin file generated by the IRIS Instruments Syscal Pro System and return a curated dataframe for further processing. This dataframe contains only information currently deemed important. Use the function reda.importers.iris_syscal_pro_binary._import_bin...
2ec4d3febad7eae08db4b2df5b4552459b627dd9
29,749
def get_messages(receive_address, send_address, offset, count): """ return most recent messages from offset to count from both communicators """ conn = connect_db() cur = conn.cursor() cur.execute( "(SELECT * FROM message WHERE (recvAddress=%s AND sendAddress=%s) ORDER by id DESC LIMIT %s OFFSET...
13e46a46a4bc15931de77374249ae701f5b65c1a
29,750
def get_test_node(context, **kw): """Return a Node object with appropriate attributes. NOTE: The object leaves the attributes marked as changed, such that a create() could be used to commit it to the DB. """ db_node = db_utils.get_test_node(**kw) # Let DB generate ID if it isn't specified expli...
6ce089c0d6643f2c58633ce846a4a46d2c9e5732
29,751
from typing import OrderedDict def GlobalAttributes(ds, var): """ Creates the global attributes for the netcdf file that is being written these attributes come from : https://www.unidata.ucar.edu/software/thredds/current/netcdf-java/metadata/DataDiscoveryAttConvention.html args: runinfo Table containing all t...
b5fcf1627f8c23964a1ec2fe4fa657a60cb8efa3
29,752
from typing import List from typing import Tuple def extend_path(path: List[Tuple[MerkleTree, hash.HashTriple]], tree: MerkleTree, ) -> List[List[Tuple[MerkleTree, hash.HashTriple]]]: """Extend path if possible.""" paths = [] for t in (tree.left, tree.right): if t i...
294ea5b1e2b844065a2fd962768f1b6501b4513f
29,753
def load_dictionary(loc): """ Load a dictionary """ with open(loc, 'r') as f: worddict = pkl.load(f) return worddict
f659ebb94410e02bbeab51b04b60e727cc749641
29,756
import json def get_specific_post(post_id): """Get specific post""" value = posts.get(post_id) if not value: return json.dumps({"error": "Post Not Found"}), 404 return json.dumps(value), 200
86ca2ee5847c3e7043dbd52f1a713477ea6191c5
29,757
def first_half(dayinput): """ first half solver: """ houses = { (0,0): 1 } coords = [0, 0] for h in dayinput: coords = change_coords(h, coords) home = (coords[0], coords[1]) if houses.get(home, None): houses[home] += 1 else: houses[home] = ...
c0ed5c66c3f259257e14c2c6bc4daec406028135
29,758
def compute_cluster_metrics(neighbor_mat, max_k=10, included_fovs=None, fov_col='SampleID'): """Produce k-means clustering metrics to help identify optimal number of clusters Args: neighbor_mat (pandas.DataFrame): a neighborhood matrix, created from create_neighb...
bc13b2eb1b4bd9824e4134395ed5d31a9cfa7cb0
29,759
def map_flat_line(x, y, data, linestyles='--', colors='k', ax=None, **kwargs): """Plot a flat line across every axis in a FacetGrid. For use with seaborn's map_dataframe, this will plot a horizontal or vertical line across all axes in a FacetGrid. Parameters ---------- x, y : str, float, or li...
dd46189458ee0da79785d2c9119a41969dc1357e
29,760
def build_dictionary(sentences, size): """ Create dictionary containing most frequent words in the sentences :param sentences: sequence of sentence that contains words Caution: the sequence might be exhausted after calling this function! :param size: size of dictionary you want :return: dict...
24a998d9df539b44c2dad1ffabb2737a189e7a3e
29,762
import re def simplestr(text): """convert a string into a scrubbed lower snakecase. Intended use is converting human typed field names deterministically into a string that can be used for a key lookup. :param text: type str text to be converted """ text = text.strip() text = text.replace(...
b030c50cd300dd97d69a9d2b8421892bb1f0c23a
29,763
def lti_launch(request): """ This method is here to build the LTI_LAUNCH dictionary containing all the LTI parameters and place it into the session. This is nessesary as we need to access these parameters throughout the application and they are only available the first time the application loads. ...
a65d4395095e36f4e27ae802ae7c2635f211521e
29,764
def cartesian_to_altaz(x): """ Converts local Cartesian coordinates to Alt-az, inverting altaz_to_cartesian """ x, y, z = x return np.arcsin(z), np.arctan2(-y, x)
e585fb57a9509fab277e15f08e76e1367c8334d4
29,766
def discount_opex(opex, global_parameters, country_parameters): """ Discount opex based on return period. Parameters ---------- cost : float Financial cost. global_parameters : dict All global model parameters. country_parameters : dict All country specific parameter...
6e079ffc9accc7679bada3b31d07748c93d4b18c
29,768
import torch def permute(x, perm): """Permutes the last three dimensions of the input Tensor or Array. Args: x (Tensor or Array): Input to be permuted. perm (tuple or list): Permutation. Note: If the input has fewer than three dimensions a copy is returned. """ if is_tens...
513164bfc6d25a82f2bfeba05427bd69c8df181c
29,770
def is_hr_between(time: int, time_range: tuple) -> bool: """ Calculate if hour is within a range of hours Example: is_hr_between(4, (24, 5)) will match hours from 24:00:00 to 04:59:59 """ if time_range[1] < time_range[0]: return time >= time_range[0] or time <= time_range[1] return time_...
70d874f0a5dee344d7638559101fc6be2bcca875
29,771
def calc_Topt(sur,obs,Tvals,objfunc='nse'): """ Function to calibrate the T parameter using a brute-force method Args: sur (pandas.Series): pandas series of the surface soil moisture obs (pandas.Series): pandas series of the soil moisture at layer x to calibrate Tvals (list,tuple,set...
39df23619ea364cbf477f02665a86e72cef86e11
29,772
def share_file(service, file_id): """Make files public For a given file-id, sets role 'reader' to 'anyone'. Returns public link to file. :param: file_id (string) :return: (string) url to shared file """ permission = { 'type': "anyone", 'role': "reader", ...
70a1132667663fa85cf7f00fd3ced2fb81b03cc4
29,773
import data def convert_image_for_visualization(image_data, mean_subtracted=True): """ Convert image data from tensorflow to displayable format """ image = image_data if mean_subtracted: image = image + np.asarray(data.IMAGE_BGR_MEAN, np.float32) if FLAGS.image_channel_order == 'BGR': image = ima...
9fe138051f7886d3c3e8e70e75f23b636a1ccd02
29,775
def mld(returns_array, scale=252): """ Maximum Loss Duration Maximum number of time steps when the returns were below 0 :param returns_array: array of investment returns :param scale: number of days required for normalization. By default in a year there are 252 trading days. :return: MLD """...
2d78d76c1456ebb4df606a9450f45e47b5e49808
29,776
from typing import Union from typing import List from typing import Dict from typing import Any def json2geodf( content: Union[List[Dict[str, Any]], Dict[str, Any]], in_crs: str = DEF_CRS, crs: str = DEF_CRS, ) -> gpd.GeoDataFrame: """Create GeoDataFrame from (Geo)JSON. Parameters ---------- ...
de9e956a79821611d6f209e9b206d3c15e24708e
29,777
from typing import Optional from typing import List from typing import Tuple from typing import Any import logging def build_block_specs( block_specs: Optional[List[Tuple[Any, ...]]] = None) -> List[BlockSpec]: """Builds the list of BlockSpec objects for SpineNet.""" if not block_specs: block_specs = SPIN...
6046b2ee33d15254ff6db989b63be4276d0bad19
29,778
def est_agb(dbh_mat, sp_list): """ Estimate above ground biomass using the allometric equation in Ishihara et al. 2015. """ # wood density wd_list = [ dict_sp[sp]["wood_density"] if sp in dict_sp and dict_sp[sp]["wood_density"] else None for sp in sp_list ] #...
ab0d80408bc9d216e387565cde3d6e758f738252
29,779
from typing import Optional def parse_json_and_match_key(line: str) -> Optional[LogType]: """Parse a line as JSON string and check if it a valid log.""" log = parse_json(line) if log: key = "logbook_type" if key not in log or log[key] != "config": log = None return log
c4efa103730ac63d2ee6c28bba2de99a450f6b8d
29,780
def nearDistance(img, centers): """ Get the blob nearest to the image center, which is probably the blob for cells, using euclidian distance. Parameters: img, image with labels defined; centers, list of label' centers of mass. Returns: nearestLabel, label nearest to the image center. ...
6414d30cb1d591b5bf6f8101c084823f92605f1e
29,781
from flask_swagger import swagger import json def create_app(config_object=ProdConfig): """This function is an application factory. As explained here: http://flask.pocoo.org/docs/patterns/appfactories/. :param config_object: The configuration object to use. """ app = Flask(__name__.split('.')[0]...
b9214ee822c8012a5273cf72daa04f33b9b99539
29,782
def get_f1_dist1(y_true, y_pred, smooth=default_smooth): """Helper to turn the F1 score into a loss""" return 1 - get_f1_score1(y_true, y_pred, smooth)
c200bbe75f7013a75b2801fbb7de4cbf588bb873
29,783
def get_date_info_for_pids_tables(project_id, client): """ Loop through tables within all datasets and determine if the table has an end_date date or a date field. Filtering out the person table and keeping only tables with PID and an upload or start/end date associated. :param project_id: bq name of p...
e75dd8176583673e8ee6e89a8c75312fe06216bc
29,784
def preprocess_sent(sentence): """input: a string containing multiple sentences; output: a list of tokenized sentences""" sentence = fill_whitespace_in_quote(sentence) output = tokenizer0(sentence) # tokens = [token.text for token in tokenizer.tokenize(sentence)] tokens = list(map(lambda x: x.te...
eddaa08e3b0a8ad43f410541793f873449101904
29,785
def average_slope_intercept(image, lines): """ This function combines line segments into one or two lane lines """ left_fit = [] # contains the coordinate of on the line in the left right_fit = [] if lines is None: return None # now loop through very line we did previously f...
b6dbd56555d5c9d71905b808db20e4f8be6de15f
29,787
def build_upper_limb_roll_jnts(main_net, roll_jnt_count=3): """Add roll jnts, count must be at least 1""" increment = 1.0/float(roll_jnt_count) def create_joints(jnt_a, jnt_b, net, lower_limb=False, up_axis='-Z'): """ :param jnt_a: Start Joint :param jnt_b: End Joint :param...
0985a33a9fac3b218042cac4d1213df13f606464
29,788
def create_one(**kwargs): """ Create a Prediction object with the given fields. Args: Named arguments. date: Date object. Date of the predicted changes. profitable_change: Decimal. Predicted profitable change in pips. instrument: Instrument object...
d71d14445c5e53c032b529652f3ed5fb12df6544
29,790
import math def get_distance_wgs84(lon1, lat1, lon2, lat2): """ 根据https://github.com/googollee/eviltransform,里面的算法:WGS - 84 :param lon1: 经度1 :param lat1: 纬度1 :param lon2: 经度2 :param lat2: 纬度2 :return: 距离,单位为 米 """ earthR = 6378137.0 pi180 = math.pi / 180 arcLatA = lat1 * p...
8da67a3a690ff0cb548dc31fb65f3b2133fa3e3f
29,792
def make_uuid(ftype, size=6): """ Unique id for a type. """ uuid = str(uuid4())[:size] return f'{ftype}-{uuid}'
3cb779431e5cb452f63f8bab639e9a437d7aa0f9
29,793
def region_of_interest(img, vertices): """ Applies an image mask. Only keeps the region of the image defined by the polygon formed from `vertices`. The rest of the image is set to black. `vertices` should be a numpy array of integer points. Args: img (image): Mas...
bd22cd8b6642dd820e786f88d54c63f4811c5221
29,794
import pytz def _adjust_utc_datetime_to_phone_datetime(value, phone_tz): """ adjust a UTC datetime so that it's comparable with a phone datetime (like timeEnd, modified_on, etc.) returns a timezone-aware date """ phone_tz = _soft_assert_tz_not_string(phone_tz) assert value.tzinfo is None...
48a875af1082d1538c6bf09905afacc411e1408c
29,795
def cache_function(length=CACHE_TIMEOUT): """ A variant of the snippet posted by Jeff Wheeler at http://www.djangosnippets.org/snippets/109/ Caches a function, using the function and its arguments as the key, and the return value as the value saved. It passes all arguments on to the function, as ...
81c2574621e81c485712e456f9b34c638f47cdf8
29,796
def plot_contour_1d(X_grid, Y_grid, data, xlabel, ylabel, xticks, yticks, metric_bars, fillblack=True): """Create contour plots and return the figure and the axes.""" n = len(metric_bars) assert data.shape == (*X_grid.shape, n), ( "data shape must be (X, Y, ...
2eb534ebe841a96386976fa477ec357b5ea07ea7
29,798
def dataset_to_rasa(dataset: JsonDict) -> JsonDict: """Convert dataset to RASA format, ignoring entities See: "https://rasa.com/docs/nlu/dataformat/" """ return { "rasa_nlu_data": { "common_examples": [ {"text": text, "intent": intent, "entities": []} ...
64a9b6291b0a2d2af297e3fb0ca214b8d65792f4
29,799
import math import tqdm def SurfacePlot(Fields,save_plot,as_video=False, Freq=None, W=None, L=None, h=None, Er=None): """Plots 3D surface plot over given theta/phi range in Fields by calculating cartesian coordinate equivalent of spherical form.""" print("Processing SurfacePlot...") fig = plt.figure() ...
23b0c3f8f569d480f3818ed970ea41adce51dacc
29,800
def resource_method_wrapper(method): """ Wrap a 0-ary resource method as a generic renderer backend. >>> @resource_method_wrapper ... def func(resource): ... print repr(resource) >>> action = "abc" >>> resource = "def" >>> func(action, resource) 'd...
e07bd139586a7b80d48c246ea831b39c3183224e
29,801
def rotation_matrix(axis_vector, angle, degrees = True): """ Return the rotation matrix corresponding to a rotation axis and angle For more information, see: https://en.wikipedia.org/wiki/Rotation_matrix#Rotation_matrix_from_axis_and_angle Parameters ---------- axis_vector : 3 x 1 numpy ar...
c48711d2b4d2bb8ca5ac01ee2c51778f4a9525fd
29,802
def select_int(sql, *args): """ 执行一个sql, 返回一个数值 :param sql: :param args: :return: """ d = _select(sql, True, *args) if d == None: raise StandardError('Result is None') if len(d) != 1: raise MultiColumnsError('Expect only one column.') return d.values()[0]
72826727a45cfa902e710371c8bf4bc9fcd07528
29,803
import logging import torch def compute_nas_score(any_plain_net, random_structure_str, gpu, args): """ compute net score :param any_plain_net: model class :param random_structure_str (str): model string :param gpu (int): gpu index :param args (list): sys.argv :return score...
6188c88151ca501c22a85cccd65bbc01d99c721f
29,805
def _dict_values_match(*args, **kwargs): """ Matcher that matches a dict where each of they keys match the matcher passed in. Similar to ``MatchesStructure``, but for dictionaries rather than python objects. """ matchers = dict(*args, **kwargs) def extract_val(key): def extract_val...
b463eb1f24117fb1c37793656632931af05f3a7c
29,806
def fib_lista(n): """ Função que retorna uma lista contendo os números da sequência de Fibonacci até o número n. """ lista = [] i, j = 0, 1 while i < n: lista.append(i) i, j = j, i + j return lista
ec307ce80ae70e5fba81d2e26b140f1b86c95619
29,807
def make_item_accessor(idx): """ Returns a property that mirrors access to the idx-th value of an object. """ @property def attr(self): return self[idx] @attr.setter def attr(self, value): self[idx] = value return attr
7cd1248b3f9402fc9be10d277dee849dc47840c0
29,810
def calc_correlation(data, data2): """ Calculate the correlations between 2 DataFrames(). Parameters: - data: The first dataframe. - data2: The second dataframe. Returns: A Series() object. """ return ( data.corrwith(data2). loc[lambda x: x.notnull()] ...
7f47592a4525efa9db2fba317d095448d5288399
29,811
def boschloo_swap(c1r1: int, c2r1: int, c1r2: int, c2r2: int) -> (int, int, int, int): """ Four contingency tables always give the same pvalue: ['abcd', 'badc', 'cdab', 'dcba'] Compute and save only one version. """ if c1r1 + c1r2 > c2r1 + c2r2: # left > right c1r1, c1r2, c2r1, c2r2 = c2r1...
4da7cccd892dcf03412509c4df79132f8ebd5ad1
29,812
def get_unit_scale(scale60, val30=1): """ Returns a function to be used in the UNIT_SCALE of a descriptor that will change the scale depending on if the 60fps flag is set or not. """ assert 0 not in (val30, scale60), ("60fps scale and default 30fps " + "value m...
36463d8e7d0cf46bce527cf9cefccdcf730b4414
29,813
def sample_ingredient(user,name = 'cinnoan'): """create and return a sample ingredient""" return Ingredient.objects.create(user=user,name=name)
3ccf096e68ed25dc4c35cf2abf68e9139c34b82c
29,814
import six def before(action): """Decorator to execute the given action function *before* the responder. Args: action: A function with a similar signature to a resource responder method, taking (req, resp, params), where params includes values for URI template field names, if any. Hoo...
d385f6b9ab45546cd2c07612528ad487ae5363d9
29,815
def commandLine(Argv): """ Method converting a list of arguments/parameter in a command line format (to include in the execution of a program for exemple). list --> str """ assert type(Argv) is list, "The argument of this method are the arguments to convert in the command line format. (type Lis...
4b27e73fd43ec914f75c22f2482271aafd0848ac
29,816
def prob(n: int, p: float) -> float: """ Parameters: - n (int): số lần thực hiện phép thử - p (float): xác suất phép thử thành công Returns: - float: xác suất hình học """ pr = p * (1 - p) ** (n - 1) return pr
fca3fab45ec852c8910619889ac19b0753f5b498
29,818
from typing import Mapping import pandas import numpy def to_overall_gpu_process_df(gpu_stats: Mapping) -> DataFrame: """ """ resulta = [] columns = [] for k2, v2 in gpu_stats.items(): device_info = v2["devices"] for device_i in device_info: processes = device_i["processes"...
7fd260b1a0d232f42958d3c073300ad6e7098c2c
29,819
from teospy import liq5_f03 def genliq5(): """Generate liq5_f03 Testers. """ funs = liq5_f03.liq_g args1 = (300.,1e5) fargs = [(der+args1) for der in _DERS2] refs = [-5265.05056073,-393.062597709,0.100345554745e-2,-13.9354762020, 0.275754520492e-6,-0.452067557155e-12] fnames = 'liq...
4051aaa831bcfb74a5e871e1619b982ad06cc859
29,820
def tridiagonalize_by_lanczos(P, m, k): """ Tridiagonalize matrix by lanczos method Parameters ---------- P : numpy array Target matrix q : numpy array Initial vector k : int Size of the tridiagonal matrix Returns ------- T : numpy array tridiagon...
0becf3801e7e486fd0a59fac95223e4d9ca68957
29,822
def Polygon(xpoints, ypoints, name="", visible=True, strfmt="{:.5f}"): """ Polygon defined by point verticies. Returns --------- :class:`lxml.etree.Element` """ polygon = Element("Polygon", name=str(name), visible=str(visible).lower()) polygon.extend( [ Element("Poin...
f2cd966a0dd536b8134ccaab4a85607e8511c60c
29,823
def fake_index_by_name(name, pattern, timezone='+08:00'): """ generate a fake index name for index template matching ATTENTION: - rollover postfix is not supported in index template pattern - timezone is not supported cause tz is not well supported in python 2.x """ if patter...
b8754ce0086409c75edba8d6bc14b7ca313d56ae
29,824
def map_code(func): """ Map v to an Ontology code """ def mapper(v): if v is None: return v else: return func(str(v)) return mapper
76eb3c6756c983fd73c180b57c1c998a348d32eb
29,825
def install_dvwa(instance, verbose: bool=True): """ Install and configure DVWA web server instance (object): This argmument define the lxc instance. verbose (bool, optional): This argument define if the function prompt some informations during his execution. Default to True. """ if update(instance,...
299bddddc06364abfe34c482fa12932f893a224c
29,826
def get(role_arn, principal_arn, assertion, duration): """Use the assertion to get an AWS STS token using Assume Role with SAML""" # We must use a session with a govcloud region for govcloud accounts if role_arn.split(':')[1] == 'aws-us-gov': session = boto3.session.Session(region_name='us-gov-west-...
f1012c71eff41bffdad6390b9353745b0e07ab0c
29,828
def find_nth(s, x, n): """ find the nth occurence in a string takes string where to search, substring, nth-occurence """ i = -1 for _ in range(n): i = s.find(x, i + len(x)) if i == -1: break return i
b54998db817272ec534e022a9f04ec8d350b08fb
29,830
from typing import Union from typing import Dict from typing import Any def parse_buffer(value: Union[Dict[str, Any], str]) -> str: """Parse value from a buffer data type.""" if isinstance(value, dict): return parse_buffer_from_dict(value) if is_json_string(value): return parse_buffer_fro...
e98cad3020fffdaef5ad71d1f59b89db83e05d03
29,831