content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def manhattan_distance(problem_: rules.EightPuzzle) -> int: """:returns: Sum of Manhattan distances for each misplaced tile.""" rv = 0 for k, v in problem_.state.items(): if v is None: v = (problem_.height - 1, problem_.width - 1) rv += _manhattan_distance(k, v) return rv
2055e8077f516e06edcf49e3a590a5e0603d5c8d
3,609,636
def geo_x(arg: ir.GeoSpatialValue) -> ir.FloatingValue: """Return the X coordinate of `arg`, or NULL if not available. Input must be a point. Parameters ---------- arg Geometry expression Returns ------- FloatingValue X coordinate of `arg` """ op = ops.GeoX(arg...
f1b0ecdc7d90feb6328870a8ca98c649109bf98d
3,609,637
def extract_tags(signature_def, graph): """.""" output = dict() for key in signature_def: output[key] = dict() output[key]['inputs'] = extract_tensors(signature_def[key].inputs, graph) output[key]['outputs'] = extract_tensors(signature_def[key].outputs, graph) return output
0129f84d6229cf6a3d3ddd2e6a5652c87279a529
3,609,638
def otsu(gray_image): """ h:图像的宽度 w:图像的高度 (h*w 得到图像的像素数量) threshold_t :灰度阈值(我们要求的值,大于这个值的像素我们将它的灰度设置为255,小于的设置为0) n0:小于阈值的像素数量,前景 n1:大于等于阈值的像素数量,背景 n0 + n1 == h * w w0:前景像素数量占总像素数量的比例 w0 = n0 / (h * w) w1:背景像素数量占总像素数量的比例 w1 = n1...
0217bddfb58bdef9b7474379fdb09f526a88d132
3,609,639
def load_report(report): """Splits the report from a string into a list of list of "bits" """ return [list(c for c in code) for code in report.split("\n") if len(code)]
18de97d81b174e03a760b1a051433bb23dd0fe7f
3,609,641
import math def standardized_euclidean_distance_0(x_list, data_list): """ :param x_list: [(x0, y0), (x1, y1), (x2, y2), ..., (xn-2, yn-2), (xn-1, yn-1)] data_list: [x_list_0 (same data structure as x_list), x_list_1, x_list_2, ..., x_list_n-2, x_list_n-1] :return: ...
40b71d342d4dbedd6fba2a7764555eccca0b18ea
3,609,642
import re def get_airport_details(airport_name: str = Query(..., min_length=1, description="Name of the airport you are trying to " + "find, can be its full name or just a phrase", example="Heathrow")): """ Find ...
06d302d044b3d90270139a85822f424fbb5d6435
3,609,643
def attr_visitor_name(attr_name: str) -> str: """ Returns the visitor_method name for `attr_name`, e.g.:: >>> attr_visitor_name('class') 'attr_class' """ # assert re.match(r'\w+$', node_name) return 'attr_' + attr_name
5fb31f9ea9d563ba05b4a80046c0b48ace35e9b5
3,609,644
def permutation_test_cv(X, y, n_permutations=1000, C=None, Cs=np.logspace(-7, 1, 9), seed=0, n_jobs=1, verbose=1): """Cross-validated permutation test shuffling the target Parameters ----------- X : ndarray, shape (n_samples, n_features) Data. ...
4d92095914ccdbfd765309484795f2830634fe69
3,609,645
def compile_akg_kernel_parallel(json_infos, process, waitime): """ compile kernel use multi processes Parameters: json_infos: list. list contain kernel info(task id and json str) process: int. processes num waittime: int. max time the function blocked Returns: True for ...
2d62da437ccd74d9eb9c059fdecb52729afe5a84
3,609,646
from typing import List def mk_string(strings: List[str], separator: str) -> str: """ Creates a string from a list of strings, with a separator in between elements. :param strings: the list of strings. :param separator: the separator. :return: the string of elements separated by the separator. ...
0230022eb3168c3dae92b6edb1cc0cdf252158d6
3,609,647
import json def radtherm_set_float(what, value, trace): """Set the value of a piece of floating point data from the thermostat""" try: if what != "t_heat": wg_error_print("radtherm_set_float", " Invalid 'what' argument " + what) return RADTHERM_FLOAT_ERROR pman = PoolMa...
c1a6825fb71fc8cad9975a808d7d2674809392dd
3,609,648
def subsets(x, L): """Return all subsets of length 1, 2, ..., min(l, len(x)) from x""" return chain.from_iterable([x[s:s+l+1] for s in range(len(x)-l)] for l in range(min(len(x),L)))
b0562cd3470bea94a329cf96448270785ed7a09e
3,609,649
def pic_in_db(hash_val): """ Args: hash_val(bytes obj): Hash value of uploaded pic Returns: Boolean true if pic in db, o.w. false """ if imagePost.query.filter_by(hash_val=hash_val).count() > 1: return True return False
205972218a7bceabf1577c7dc6f10e17950efe3e
3,609,650
def get_dev_risk(weight, error): """ :param weight: shape [N, 1], the importance weight for N source samples in the validation set :param error: shape [N, 1], the error value for each source sample in the validation set (typically 0 for correct classification and 1 for wrong classification) """ ...
1bb7bef768bb1e0012f8f61be3a1f7a92f5d1d00
3,609,651
def unflatten_list(flat_dict, separator='_'): """ Unflattens a dictionary, first assuming no lists exist and then tries to identify lists and replaces them This is probably not very efficient and has not been tested extensively Feel free to add test cases or rewrite the logic Issues that stand o...
bbf8eb33ce47a75ab84eb1667a4e9d7dcc95ce28
3,609,653
def notes(filters=None): """Retrieve all Note objects. Args: filters (list, optional): A list of additional filters to apply to the query. """ filter_list = FilterSet(filters) filter_list.add(Filter('type', '=', 'note')) return query(filter_list)
91e663afef3fd74fe56ae1d55879a0eab81a0209
3,609,654
def Normalize(df): """ This function takes a pandas dataframe and normalize it Arguments ---------- - df: pandas dataframe Return ---------- - df: pandas dataframe The initial dataframe normalized """ df = (df - df.min())/(df.max() - df.min()) return df
b16a196ea14c93d2100d8030ef1417a7112560c7
3,609,655
def _filter_featured_downloads(lst): """Filter out the list keeping only Featured files.""" ret = [] for item in lst: if 'Featured' in item['labels']: ret.append(item) return ret
d722fdd01966f1650575912715f8a6f07d793dda
3,609,657
def shifted_conv2d(input, out_channels, kernel_size, spatial_shift, strides=(1, 1), channels_last=True, conv_fn=conv2d, name=None, scope=None, **kwar...
bfc6063b338a17202e939aca0cfff7c29b22cf5b
3,609,658
def alphabet_index(text: str) -> str: """Replaces each letter with its appropriate position in the alphabet.""" return " ".join([str(ord(x.lower())-96) for x in text if ord(x.lower())-96 >= 1 and ord(x.lower())-96 < 27])
1221477a924121f50abc79c6afc55fc09ebc88b9
3,609,659
def AddJetID(proc, jetName="", jetSrc="", jetTableName="", jetSequenceName=""): """ Setup modules to calculate PF jet ID """ isPUPPIJet = True if "Puppi" in jetName else False looseJetId = "looseJetId{}".format(jetName) setattr(proc, looseJetId, proc.looseJetId.clone( src = jetSrc, filterPa...
f19a56e3eedaa37479644b7005dca5078bb25029
3,609,660
def hds_builder( project_id, table_id, dataset_id, landing_zone_dataset, landing_zone_table_name_override, column_mapping, column_casting, new_column_udfs, surrogate_keys, ingestion_type, hds_table_config, partition_expiration, location, dag, cluster_fields=No...
53c1fc8535b151e24b6c09d18076c39b2c26a09a
3,609,661
from typing import Optional def _should_use_gp(search_space: SearchSpace, num_trials: Optional[int] = None) -> bool: """We should use only Sobol and not GPEI if: 1. there are less continuous parameters in the search space than the sum of options for the choice parameters, 2. the number of total iterat...
8c0fed84876673a0aafa3461584f57b1ab74d05f
3,609,662
def k_means_extraction(arr, height, width, palette_size): """ Extracts a color palette using KMeans. :param arr: pixel array (height, width, 3) :param height: height :param width: width :param palette_size: number of colors :return: a palette of colors sorted by frequency """ arr = n...
49e3f8c665d9806680f02b998ed711efa6bdc6d2
3,609,663
def check(rule, target, creds, *args, **kwargs): """A shortcut for policy.Enforcer.enforce() Checks authorization of a rule against the target and credentials and returns True or False. """ enforcer = get_enforcer() return enforcer.enforce(rule, target, creds, *args, **kwargs)
201d598fa46bbb16cfecce84f084b8e3ab9339c2
3,609,664
def logout(): """ Logout current user from session """ # remove user from session session.pop("user_id", None) flash("Logged Out", "success") return redirect(url_for("index"))
777d16b9f1e049d896950dd0703268df4f2ab1f0
3,609,666
def print_snd(expr): """ Arguments: - `expr`: """ return color.cyan + "snd" + color.reset + "({0!s})".format(expr.expr)
e0de5ce197848087d5e64e169d766f949868140f
3,609,668
def detect_edge(image_array, sigma=1.0, low_threshold=None, high_threshold=None): """ Detect the edges in an image using the Canny filter Parameters ---------- image_array Returns ------- array with edges identified Side Effects ------------ None """ ...
8b488bb768e4a081d9dcf64df7f3e31beb702ad3
3,609,670
def remove_duplicate(id_list, class_target_id, return_type, check): """ Check duplication in class member and return a new user id list that is not duplicate in class. This function mainly use in add_member_to_class function. :param id_list: A user id list as a string. :type id_list: str :para...
2c420d705ecb52fa0e89f0fc6820069b5d9773cd
3,609,671
from typing import Optional def wait_selector( gen: PQGen[RV], fileno: int, timeout: Optional[float] = None ) -> RV: """ Wait for a generator using the best strategy available. :param gen: a generator performing database operations and yielding `Ready` values when it would block. :param f...
71d43e4a16f23b9538d2d89840c5bc12a3d387cc
3,609,672
def field_has_type(needle: BaseType, field: BaseType) -> bool: # pylint: disable=too-many-return-statements, too-many-branches """ Return True if field haystack contains a field of type needle. :param needle: A schematics field class to search for. :param haystack: An instance of a schematics field wi...
fca952bf63f4b42b8ee8f823afbf248b8098845c
3,609,673
def get_max_batch_size(model, tile_size, device, classes): """get max possible batch_size based on GPU memory This function calculates the maximum possible batch size based on the available GPU memory. Args: model (pytorch model): model to train tile_size (int): size of the input image...
a5b76b9dc180223d8c4248c1bec35d30b85da9f3
3,609,674
def authorize(func): """ User needs to be logged in """ @wraps(func) def wrapper(*args, **kwargs): if app.current_user is not None: return func(*args, **kwargs) app.flash('Login to view this page') redirect('/login?back=' + request.path) return wrapper
500787de037775de68f042c777cdd33375335a47
3,609,676
def handle_no_range(node): """Returns stl_node with range set to [0,0] if not previously set""" if node.range_start==None or node.range_end==None: node.range_start = 0 node.range_end = 0 return node
1baad2869cf769d6caac73e52d2799d04b1fc16d
3,609,677
def PageRankResponseStartValuesVector(builder, numElems): """This method is deprecated. Please switch to Start.""" return StartValuesVector(builder, numElems)
b54e7659266c9c3802e9f3621758e1099aa19c92
3,609,678
def normdiff(p, q) -> float: """ Alias to the 2-norm of a difference between two vectors Parameters ---------- p : iterable q : iterable Returns ------- float Norm discrepancy. """ return np.linalg.norm(p - q)
de279fd51528781d7cf0fe339e87b9594626defb
3,609,679
def build_frequency_case(mt): """ Bin frequencies. Output refers to bin floor :param MatrixTable mt: Input MatrixTable with .freq annotation :return: Binned frequencies :rtype: FloatExpression """ return (hl.case() .when(mt.freq[0].AF >= 0.2, 0.2) .when(mt.freq[0].AF...
cd07427c4cadceb2d7a959b7e47ffd4724d59a0a
3,609,680
import logging def transform_architecture(model, pretrained_model_file=None): """Transform architecture.""" if not hasattr(model, "_arch_params") or not model._arch_params or \ PipeStepConfig.pipe_step.get("type") == "TrainPipeStep": return model model._apply_names() logging.info("...
997020421fca590db8cfee9cc9844104f203cfd7
3,609,681
def merge_kwargs(kwargs, defaults): """Helper function to merge ``kwargs`` into ``defaults``. Args: kwargs: Keyword arguments. defaults: Default keyword arguments. Returns: Merged keyword arguments (``kwargs`` overrides ``defaults``). """ if defaults is not None: kw...
09a887bbcefdd2e0795fee043354d4bdf8e806a8
3,609,682
def f84a(): """Return a unit-distance embedding of the F84A graph - not degenerate despite its looks. The graph is notable in having the simple PSL(2,8) as its automorphism group.""" t0 = findroot(lambda *t: f84a_vertices(*t)[1], (-0.46, -1.44, 0.25, 0.75)) return all_unit_distances(f84a_vertices(*t...
1799a079dbc403ec076665658904b0a9c3c7fd07
3,609,683
def plot_metrics(couplings, cost_func, cost_func_name, epsilons, log = False, points=False, scale=1.0, label_font_size=18, tick_font_size=12): """ Plots cost_func evaluated as a function of epsilon """ zero_offset = epsilons[0]/2 all_ys = [] if "lineageOT" in couplings.keys(): ys = np.ar...
50acb7a5faf58b37a0a45d553a4be9cce5852996
3,609,684
import functools def translateUpdate(q, base=None, initNs=None): """ Returns a list of SPARQL Update Algebra expressions """ res = [] prologue = None if not q.request: return res for p, u in zip(q.prologue, q.request): prologue = translatePrologue(p, base, initNs, prologue...
313acac54ea8409656282a0be97436a2e4daa8b8
3,609,685
def format_decimal(value): """Format value to 2 decimal places""" formatter = "{0:.2f}" return float(formatter.format(value))
694efd34d7e36d493a66ef25ab5a552f93eac087
3,609,686
import re def rename_pretrained(name: str): """ Matches the name of a variable saved in the pre-trained MobileNet networks with the name of the corresponding variable in this network. https://github.com/tensorflow/models/blob/master/research/slim/nets/mobilenet_v1.md Parameters ---------- na...
6913159aef0d9b4019af34dcd72984d3dd6870e9
3,609,688
def do_ldap_search(conn, query): """ Search Yale LDAP for a particular netid. On the command line this would be something like the following: ldapsearch \ -H ldaps://ad.its.yale.edu:3269 \ -D cn=s_klj39,OU=Non-Netids,OU=Users-OU,dc=yu,dc=yale,dc=edu \ -w $LDAP_PAS...
183d126b3dda117a42d1a8a93a5a90fbd752eb92
3,609,689
def BrokerFeaturesAddEventHistory(builder, eventHistory): """This method is deprecated. Please switch to AddEventHistory.""" return AddEventHistory(builder, eventHistory)
57e3729762f079af9c32dd28f71bee455cf9bce0
3,609,690
def _forwarder(func): """Returns a function that applies func to all given images.""" def fwd(*images): _apply_images(func, images) fwd.__doc__ = "Forward to Canvas." + func.__doc__ return fwd
7e24c394ce273f38a2e6175bc24f8702b17df3eb
3,609,691
import copy def clip_norm(g, c, n): """Clip the gradient `g` if the L2 norm `n` exceeds `c`. # Arguments g: Tensor, the gradient tensor c: float >= 0. Gradients will be clipped when their L2 norm exceeds this value. n: Tensor, actual norm of `g`. # Returns Ten...
05204e2a06f18da71be44aa15ddabeafed794e9a
3,609,692
def update_action(body): """ Updates an action :param body: Updated action instance :type body: list | bytes :rtype: None """ if connexion.request.is_json: body = [Action.from_dict(d) for d in connexion.request.get_json()] return 'do some magic!'
c73cac1bcc973ceaf9555e7ddf87acca19225ad9
3,609,693
def anagram(word1, word2): """Determines if two words are anagram of each other NOTE: This solutoin does not work for all test cases. """ # if the strings are not equal length they can't be anagram if len(word1) != len(word2): return False s1 = 0 s2 = 0 # add up the ascii valu...
d90d58723986da8fdab4c01433d074cb2f0151b2
3,609,694
def build_table_def(table_name, keys, additional_attributes=None, global_secondary_indices=None): """ Creates a minimal dynamodb definition suitable for use with localstack. Args: table_name: The full name of the test table keys: The key definitions to use - a list of 4-tuples (<name>, <key...
84b124ac0a084f05685ed4e636fb8eda78317c07
3,609,695
import logging async def delete_config(key: str, type: str, response: Response, id: str = ""): """Delete a config from the database Attributes: key (str): key to be deleted type (str): global/package/node id (str): package or node id as per type response (Response): Starlette...
8c04f65d3fa39a88d3487242ac09ba95bbb018c1
3,609,696
def reauth(): """ Reauthenticates a user """ if not login_fresh(): form = ReauthForm(request.form) if form.validate_on_submit(): confirm_login() flash(("Reauthenticated"), "success") return redirect(request.args.get("next") or ...
7fdf19ddb0e9c076f3c7fa82dae400defd5e6c0a
3,609,698
def execution_has_failures(playbook_results): """Return value 2 means failure in ansible-playbook""" if type(playbook_results) != list: playbook_results = [playbook_results] return 2 in playbook_results
1c8ea2767a78ca72147f65f3ca5fa90018f8c141
3,609,699
from functools import reduce def overlay(xss): """ Interleave two playlists by overlaying unique elements. Elements from YS are only picked if they are unique. Non-unique YS elements are ignored, and an element from XS is picked instead. Thus, the unique elements of YS are "overlaid" onto XS. ...
9b00f6b11c4e148c05b16553d092bcb304fdb828
3,609,700
def UpdateName(new_name): """ Method for the dApp owner to update the dapp name :param new_name: new name of the dapp :type new_name: str :return: whether the update succeeded :rtype: bool """ if not CheckWitness(OWNER): Log("Must be owner to update name") return False...
6e083bdb27439f86cc1250e59ac242c4dae65263
3,609,702
def get_entrez_df( force: bool = False, ) -> pd.DataFrame: """Get the Entrez mappings dataframe.""" return ensure_df( PREFIX, url=ENTREZ_XREFS_URL, sep="\t", names=[ "mgi_id", "symbol", "status", "name", "position", ...
b37da140e085fe126cb4902130b0d013b32f1a44
3,609,703
def ks_unif_pelz_good(samples, statistic): """ Approximates the statistic distribution by a transformed Li-Chien formula. This ought to be a bit more accurate than using the Kolmogorov limit, but should only be used with large squared sample count times statistic. See: doi:10.18637/jss.v039.i11 and...
aa774a88f4720694ad3c801e70ef829a96181f7c
3,609,704
def tm_team_transfers(club, season, position_group='All', main_position='All', window='All', currency='EUR'): """ Extracts basic player information for each player in a squad including basic player information, market value, and contract expiration Parameters: club (string): club name season (strin...
04f277d2ff957f274eef91fb9102c376e7404e07
3,609,705
def Month(year, month): """Define an smv.panel.Month Month extends smv.panel.PartialTime base class Args: year (int): month (int): Example: >>> m = Month(2012, 5) >>> m.smvTime() u'M201205' >>> m.timeIndex() ...
4d92e668caf08b8db81553b78d719c978a180e80
3,609,706
def single_threaded_session(): """Returns a session which will only use a single CPU""" return make_session(1)
1ce0f094ae26e178a9588f4fb87a97588a159af6
3,609,707
def buoyancy(sig0, rho0=1025.0): """Calculate buoyancy [m/s^2] based on potential density. Inputs ------ sig0: DataArray, ndarray Potential density [kg/m^3] rho0: int, float, optional Reference density [kg/m^3]. Returns ------- DataArray or ndarray of calculated buoyanc...
0c7500601d365a847235edcbb265db16ddcc678e
3,609,708
import signal def shrink_mask(mask, kernel): """Shrink mask wrt to a kernel Parameters ---------- mask : 2D boolean array_like the mask to be shrinked by... kernel : 2D float array_like ... the corresponding array Returns ------- 2D boolean array the correspon...
f43e760a3442651c50d0ee6a7d56d35b8450a659
3,609,709
import platform def host_clang(xcrun_toolchain): """ Return a Toolchain for the host platform. If no appropriate compilers can be found, return None. """ if platform.system() == 'FreeBSD': # See: https://github.com/apple/swift/pull/169 # Building Swift from source requires a recent...
fb7c19fa6941d680444ca9282eb87b91dbd43f26
3,609,710
def bootstrap(a, nboot=1000, summary_fn=np.mean): """ Calc vectorised bootstrap sample of array of observations By default return the mean value of the observations per sample I.e if len(a)=20 and nboot=100, this returns 100 bootstrap resampled mean estimates of those 20 observations ""...
ebd7379c1b3b6d078175601683fe22dc50d71d9c
3,609,711
def element2obs(obs, allow_null=False): """ Remaps the old format to new api Observation model for a single observation. Returns a dictionary, not an observation instance. """ # Should only be one _obs = {} #For now we require non-empty strings if obs['answer']: _obs['value']...
49dd82639b5099eed9b7251ddde903429c0fff38
3,609,712
from resources.lib.kodi import ui import base64 import json def _get_authentication_key_data(file_path, pin): """Open the auth key file""" try: file_content = load_file(file_path) iv = '\x00' * 16 cipher = AES.new((pin + pin + pin + pin).encode("utf-8"), AES.MODE_CBC, iv.encode("utf-8"...
3268324ad452a9844b930c1c62bf6ff3bed213cd
3,609,713
def mark(label, func=None): """Mark the function/class with the given label. This may be used as a decorator. """ if func is None: def decorator(func): return mark(label, func) return decorator if isinstance(func, type): cls = func apply_to_test_methods(c...
960360545f01ed17c27b8045fadebd92a70b0e9b
3,609,714
def managerSpecificKey(key): """ Produces a manager-localised key for persistent options, etc.. """ manager = FnAssetAPI.SessionManager.currentManager() if not manager: return key identifier = manager.getIdentifier() # Hiero doesn't seem to like dots in tag names safeIdentifier = identifier.replace...
35bcaf7bd390608bb8cffb2f1d9518b99ab88bc3
3,609,715
def parse_load_balancer_name(load_balancer_arn): """ Parse name out from load balancer ARN Example: ARN of load balancer: 'arn:aws:elasticloadbalancing:us-east-1:881508045124:loadbalancer/app/alb-1/72074d479748b405', Load balancer name: 'alb-1' return: load balancer name """ return load_...
c64e4545d30c18bca2c05df3433958e012f0ed47
3,609,716
def unsupervised_labels(y, yp, n_classes, n_clusters): """Linear assignment algorithm Arguments: y (tensor): Ground truth labels yp (tensor): Predicted clusters n_classes (int): Number of classes n_clusters (int): Number of clusters """ assert n_classes == n_clusters...
71d4f98492b4b289353be0d139b5fba0da2a76a7
3,609,717
def process_and_validate_ref(ref, paper_database): """Takes a reference and database. First tests if the reference is an alias in the database. Then attempts to extract arxiv id from the reference (which might be a whole url). Then returns the processed reference or throws an error if it is not a valid ...
305a54ae561724a965fbbe8a67e360d7057796d5
3,609,718
def taggifier(tag: str, **kwargs) -> Macro: """ Create a Builder Modifier that wraps the text in HTML tags. The tag name is mandatory. Attributes can be added as keyword arguments. All attributes are forced to be lowercase so you can avoid name collisions by capitalizing words like "class". """...
2660310c82dc7607fde4c7a67cbfe1c9578bb57e
3,609,719
import uuid import logging def _AddTask( queue_name, payload, target=None, name=None, eta=None, transactional=False): """Add a task using a selected task scheduler implementation. Args: queue_name: a queue name. payload: a task payload. target: a target module name. name: a task name. eta...
43212dfa518f53882d4529e9b2bdedd6c49aa084
3,609,720
def adjust_course_account(): """ This api adjusts the course credit account for a student. """ student_id = request.json.get('student_id', None) course_id = request.json.get('course_id', None) transaction_type = request.json.get('transaction_type', None) amount = request.json.get('amount', N...
669a1499a69b3ef60687bc835d26140813d25108
3,609,721
from typing import Optional def get_gateway(gateway_id: Optional[str] = None, opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetGatewayResult: """ Resource schema for AWS::IoTSiteWise::Gateway :param str gateway_id: The ID of the gateway device. """ __args__ = dict() ...
0f0cbbd7fee198941fb58f3bcfb37b8e6c6c2593
3,609,722
import json def __get_categorical(self, sock=None): """ Transform column to numpy array Args: sock: Socket connecting the Python API with the getML engine. """ # ------------------------------------------- # Build command string cmd = dict() cmd["name_"] = self....
c7c84d90c622470eaf0ff6cb2d61bbd2ae16eb80
3,609,723
def getUnicodeIndexGroup(name): """ Return a group letter for `name`, which must be a unicode string. Currently supported: Hangul Syllables (U+AC00 - U+D7AF) @param name: a string @rtype: string @return: group letter or None """ c = name[0] if u'\uAC00' <= c <= u'\uD7AF': # Hangul S...
9a7c53619781acd606d8f823012c6e9a0030cd71
3,609,724
import json import time import requests def job_run(jobId): """ Run a saved job RouteParams: jobId: the id of a job GetParams: account: an account user: a user Returns: a json representation of a job """ account = request.form['account'] user = request...
c418774bee6b7d1967ae4de756ff2183e6cb4d72
3,609,725
def plot_confusion_matrix(cm, class_names, title='Confusion matrix'): """ This function prints and plots the confusion matrix. """ cm = cm.round(decimals=2) figure = plt.figure(figsize=(30, 25)) df_cm = pd.DataFrame(cm) # , index=class_names, columns=class_names sn.set(font_scale=4) # for...
32a800ff3810fb52106ae7958eb08502bc90b088
3,609,728
def iint(number): """This method behaves in the same way as the **INT()** function described by Meeus in his book: Greatest integer which is not greater than number. :param number: Number or expresion :type number: int, float :returns: Greatest integer which is not greater than number :rtype: ...
ca5f4a288d7063d70695dee221cc875407745d8f
3,609,729
def init_xena(api, logger, owner, ip=None, port=57911): """ Create XenaApp object. :param api: cli/rest :param logger: python logger :param owner: owner of the scripting session :param ip: rest server IP :param port: rest server TCP port :return: Xena object :rtype: XenaApp """ ...
e62640b7a0449f29311f171e806d55916c9c21d7
3,609,730
from pathlib import Path def get_paths(dir_name, glob): """ returns a generator of the recursive paths on input glob """ return Path(f'./{dir_name}').rglob(glob)
6803981e40397d000900dd0a8fc8ee32eddc6bc4
3,609,731
def priceVector(A: np.matrix, rho: float, a: int | float, c: int | float, alpha) -> np.matrix: """ Parameters ---------- A : Network rho : network strength a : stand alone util c : marginal cost. Should be less than a Returns ------- Vector reprsenting what price to charge indiv...
f6d42670cd1e987169244c3c579783fa64f9dc46
3,609,732
def batch_local_dist(x, y, min_val): """ Compute local distance for batch Args: x: pytorch Variable, with shape [N, m, d] y: pytorch Variable, with shape [N, n, d] min_val: Minimal distance (for preventing division by zero) Returns: dist: pytorch Variable, with shape [N] """ ...
c0b444ce708907e06dc72510338339059e02dda8
3,609,734
def get_title_block(txt): """ Get the general doc of the cmake code. Should be at the top of the file, from the first '#!' to the next text block """ res = "" in_title = False for line in txt.splitlines(): if line.startswith("#!"): in_title = True res += c...
928f4623172711b7116772183299a1034aecac2a
3,609,735
import math def cudasolve(A, b, tol=1e-3, normal=False, regA = 1.0, regI = 0.0): """ Conjugate gradient solver for dense system of linear equations. Ax = b Returns: x = A^(-1)b If the system is normal, then it solves (regA*A'A +regI*I)x= b Returns: x = (A'A +reg*I)^(-1...
7519a656fadf3bb8c99eed28b4ace9f228a296c7
3,609,736
def inverse_relation(dst, rel): """ Similar to :meth:``forwards_relation`` but selects the source nodes instead, given a destination node. :param dst: The destination node. :param rel: The relation. """ statement = 'SELECT src FROM %s WHERE dst = ?' return statement % rel, (dst,)
f3dd3ab848ccad4d5594710659fc342ad584e6b7
3,609,738
def PyUnicode_AsUnicodeEscapeString(space, pyobj): """Encode a Unicode object using Unicode-Escape and return the result as Python string object. Error handling is "strict". Return NULL if an exception was raised by the codec.""" if not pyunicode_check(pyobj): PyErr_BadArgument(space) w_un...
53cd2fb958e0935b70180f10d4484acf1c4506df
3,609,739
def normalize_bridge_id(bridge_id: str): """Normalize a bridge identifier.""" bridge_id = bridge_id.upper() # discovery: contains 4 extra characters in the middle: "FFFF" if len(bridge_id) == 16 and bridge_id[6:10] == "FFFF": return bridge_id[0:6] + bridge_id[-6:] # deCONZ config API conta...
be5230a4678f404613975ffc348fd5f9b8d1c631
3,609,740
def vdcorput(n, base=2): """[summary] Arguments: n ([type]): [description] Keyword Arguments: base (int): [description] (default: {2}) Returns: [type]: [description] """ return [vdc(i, base) for i in range(n)]
96e55e00a6801f4376a6b1b1e45a395b76f99ae4
3,609,741
def load_nib(fpath): """ Load nifti image :param fpath: path of nifti file """ im = nib.load(fpath) return im
16015584bd0a87dff19647fcebc559c0c55f82ec
3,609,742
def list_of_exchanges(test_mode: bool = False) -> list: """Get List of Exchanges available""" try: return ListOfExchanges(test_mode=test_mode) except Exception as exception: logger.error('Oops! An error Occurred ⚠️') raise exception
45048c97bb8078f33e541ef0f38d9ecafd508ee3
3,609,743
def Min(a, axis, keep_dims): """ Min reduction op. """ return np.amin(a, axis=axis if not isinstance(axis, np.ndarray) else tuple(axis), keepdims=keep_dims),
22b62410f8360c0a2be9febcaa2fe8c87c8a7383
3,609,744
def rmflvec(self, **kwargs): """Writes eigenvectors of fluid nodes to a file for use in damping APDL Command: RMFLVEC parameter extraction. Notes ----- RMFLVEC extracts the modal information from the modal results file for all nodes specified in a node component called 'FLUN'. This compone...
cd4f63f2e9a3addcbf6f711ee80133392c6d7d2a
3,609,747
from typing import OrderedDict def group_by_until(self, key_mapper, element_mapper, duration_mapper) -> ObservableBase: """Groups the elements of an observable sequence according to a specified key mapper function. A duration mapper function is used to control the lifetime of groups. When a group expires,...
5cafd38378a312f271cd65cd9e4cf3313b933f1c
3,609,748
def createIniFile(name, subdir=None): """ Returns the path to the named configuration file. Deprecated: Use createSettingsFile() instead. """ return createSettingsFile(name, subdir)
d68fd24457f603cb261759f18ba68376ff2beb4e
3,609,749
def _nose_2eyes(landmarks): """ :param landmarks: :return: nose, right eye corner, left eye corner """ return np.array([_centroid_nose(landmarks), _centroid_right_eye(landmarks), _centroid_left_eye(landmarks)], dtype=np.double)
55a4ac088dffaafc39e296c2fd4d19d4bbe013b0
3,609,750
import pickle def load_model(model_path): """Loads existing model Parameters: model_path - path to the model file Returns: loaded model """ with open(model_path, 'rb') as f: return pickle.load(f)
a9bf3abd5717e05a381bbaf7228a02217b8bccc5
3,609,751