content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import traceback import itertools import operator def build_missing_wheels( packages_and_envts, build_remotely=False, with_deps=False, dest_dir=THIRDPARTY_DIR, ): """ Build all wheels in a list of tuple (Package, Environment) and save in `dest_dir`. Return a list of tuple (Package, Environ...
261433deb7bc691f92d995d606e108a807201b97
24,809
def str_to_bool(string): """ Parses string into boolean """ string = string.lower() return True if string == "true" or string == "yes" else False
e7c1645ab3ba59fc4721872df76f406c571cab8f
24,812
def rerotateExtremaPoints(minSepPoints_x, minSepPoints_y, maxSepPoints_x, maxSepPoints_y,\ lminSepPoints_x, lminSepPoints_y, lmaxSepPoints_x, lmaxSepPoints_y,\ Phi, Op, yrealAllRealInds): """ Rotate the extrema points from (the projected ellipse centered at the origin and x-axis aligned with semi-major ...
b656116d73cd98903fae0f54e3d575a59ae4b102
24,813
import glob def does_name_exist(name): """ check if a file with that name already exists """ return len(glob.glob('./photos/'+name+'.*')) > 0
c377f5fdb15d1d88ba6082c9be0e0400f5a8094d
24,814
def cont_hires(npoints, elecs, start_timestamp=0): """ Retrieve hires data (sampled at 2 kHz). Parameters and outputs are the same as the `cont_raw` function. Args: npoints: number of datapoints to retrieve elecs: list of electrodes to sample start_timestamp: NIP timestamp to s...
6d420e19e0de94f83992c0945e0f9a994b1e5483
24,815
import torch def batch_grid_subsampling_kpconv_gpu(points, batches_len, features=None, labels=None, sampleDl=0.1, max_p=0): """ Same as batch_grid_subsampling, but implemented in GPU. This is a hack by using Minkowski engine's sparse quantization functions Note: This function is not deterministic and ...
9d4eb2b0d5ad7d36199cc6ff6ba567c49dccff4b
24,816
import configparser import re def hot_word_detection(lang='en'): """ Hot word (wake word / background listen) detection What is Hot word detection? ANSWER: Hot word listens for specific key words chosen to activate the “OK Google” voice interface. ... Voice interfaces use speech recognition techno...
d982c33dc9b8af0e1592a88438664342fb25b8cc
24,817
def parse_ph5_length(length): """ Method for parsing length argument. :param length: length :type: str, numeric, or None :returns: length value as a float :type: float or None """ err_msg = "Invalid length value. %s" % (length) return str_to_pos_float(length, err_msg)
f5f669bdcd28611e45bbefa80fce6f2bf16a663f
24,818
from typing import Tuple def check_proper_torsion( torsion: Tuple[int, int, int, int], molecule: "Ligand" ) -> bool: """ Check that the given torsion is valid for the molecule graph. """ for i in range(3): try: _ = molecule.get_bond_between( atom1_index=torsion[...
7b43e4838bf65ebb4505d1660819ace98bdbd038
24,820
def find_all_occurrences_and_indexes(seq): """ seq: array-like of pretty_midi Note Finds all patterns and indexes of those patterns. """ list_patterns = list() list_indexes = list() res = list() seq_x = seq while res!=None: seq_x, res, indexes = find_occurrences_and_inde...
ab85dca7f30768d75e28ab76b974e50364e8746a
24,821
def get_uas_volume_admin(volume_id): """Get volume info for volume ID Get volume info for volume_id :param volume_id: :type volume_id: str :rtype: AdminVolume """ if not volume_id: return "Must provide volume_id to get." return UasManager().get_volume(volume_id=volume_id)
55cd59c8e7c116f8a975ef4f14f808c07700d955
24,823
def cyclic_learning_rate(global_step, learning_rate=0.01, max_lr=0.1, step_size=50000., gamma=0.99994, max_steps=100000., scale_rate=0.9, mode='t...
cae33d6b167c4356dec52c0511d36fd23ca68434
24,824
def getElementsOnFirstLevelExceptTag(parent, element): """Return all elements below *parent* except for the ones tagged *element*. :param parent: the parent dom object :param elemnt: the tag-name of elements **not** to return """ elements = [] children = getElements(parent) for c in childre...
7ce5b578090d7079cf6bc3905d0d25fecf06461a
24,825
def get_first_child_element(node, tag_name): """Get the first child element node with a given tag name. :param node: Parent node. :type node: xml.dom.Node :returns: the first child element node with the given tag name. :rtype: xml.dom.Node :raises NodeNotFoundError: if no child node wit...
479b311ec52814b9276e401361bbb1b040527d23
24,826
import re def parse_iso(filename='iso.log'): """ parse the isotropy output file Args: filename: the isotropy output file name Returns: lname: list of irreps lpt: list of atom coordinate lpv: list of distortion vectors, might be multi-dimensional """ #read in the ...
f0331c7a0c962d9763f1b3a15c997dda5a3c951c
24,827
def revoke_database(cursor: Cursor, user: str, db: str) -> Result: """ Remove any permissions for the user to create, manage and delete this database. """ db = db.replace("%", "%%") return Result(_truthy(query(cursor, _format("REVOKE ALL ON {}.* FROM %s@'%%'", db), user)))
9cb496ffde12fbbed4750a9442572a6bbd74497a
24,828
def get_ex1(): """Loads array A for example 1 and its TruncatedSVD with top 10 components Uk, Sk, Vk = argmin || A - Uk*diag(Sk)*Vk|| Over; Uk, Sk, Vk Where; Uk is a Orthonormal Matrix of size (20000, 10) Sk is a 10 dimensional non-negative vector Vk is a Orthonormal Matrix of size (1...
9afab6220acd28eedcfed1eee9920da97c1ff207
24,829
from typing import Any def render_variable(context: 'Context', raw: Any): """ Render the raw input. Does recursion with dict and list inputs, otherwise renders string. :param raw: The value to be rendered. :return: The rendered value as literal type. """ if raw is None: return Non...
36b6148589a447c8c9397f2b199a0c9da025fd50
24,830
def is_p2wpkh_output(cscript: CScript) -> bool: """Checks if the output script if of the form: OP_0 <pubkey hash> :param script: Script to be analyzed. :type script: CScript :return: True if the passed in bitcoin CScript is a p2wpkh output script. :rtype: bool """ if len(cscript...
1efec498daa89c1b345538d4e976aaa9ac9dd6cd
24,833
def check_update_needed(db_table_object, repository_name, pushed_at): """ Returns True if there is a need to clone the github repository """ logger.info(f"This is the repo name from check_update <<{repository_name}>> and db_table <<{db_table_object}>>") result = get_single_repository(db_table_object...
1ab5b3e29e504b60deb928f634a0e8d11cf71d3b
24,834
def return_one(result): """return one statement""" return " return " + result
94298fd5811877fa9e6a84cb061fc6244f3fda3b
24,835
def inv(a): """The inverse rotation""" return -a
dbf88fc5f8f2f289f0132a19e0d0af0e82f232bd
24,836
from App import Proxys def wrapCopy(object): """Wrap a copy of the object.""" return eval( serialize(object), Proxys.__dict__ )
ece99c49d9e5cd3603ee91f6614e5f63bc122751
24,837
def pi_eq_func(ylag,pilag,v,s,slag,alpha,h,b,phi,gamma): """ equilibrium value for inflation Args: ylag (float): lagged output pilag (float): lagged inflation v (float): demand disturbance s (float): supply disturbance slag (float): lagged supply disturbance alp...
fca249f970e2d97b32d0f8a8b03602370c19b36d
24,839
import time def set_mode(vehicle, mode): """ Set the vehicle's flight modes. 200ms period state validation. Args: vehicle(dronekit.Vehicle): the vehicle to be controlled. mode(str): flight mode string, supported by the firmware. Returns: bool: True if success, Fal...
7c8590989ce7d7c0ffbc9910c8f8cf7018090e95
24,840
def _setdoc(super): # @ReservedAssignment """This inherits the docs on the current class. Not really needed for Python 3.5, due to new behavior of inspect.getdoc, but still doesn't hurt.""" def deco(func): func.__doc__ = getattr(getattr(super, func.__name__, None), "__doc__", None) return ...
47da03ae9951e18fccaaa2cf891d39dfdcc324c9
24,842
def test_module(client: Client) -> str: """Tests API connectivity and authentication' Returning 'ok' indicates that the integration works like it is supposed to. Connection to the service is successful. Raises exceptions if something goes wrong. :type client: ``Client`` :param Client: client t...
d3bd13ee0b928d9ffb14a93efb4738f484979dfc
24,843
import functools import warnings def warns(message, category=None): """警告装饰器 :param message: 警告信息 :param category: 警告类型:默认是None :return: 装饰函数的对象 """ def _(func): @functools.wraps(func) def warp(*args, **kwargs): warnings.warn(message, category, stacklevel=2) ...
4c481dc7eeb42751aef07d87ab9da34b04c573f4
24,844
import urllib def handle_exceptions(func) -> object: """ This is needed since pytube current version is quite unstable and can raise some unexpected errors. """ def wrapper(*args, **kwargs): try: return func(*args, **kwargs) except KeyError as e: window.s_...
ef162302186b5da5c86cec67286dcfecefd1ddd0
24,845
def templated_sequence_component(location_descriptor_tpm3): """Create test fixture for templated sequence component""" params = { "component_type": "templated_sequence", "region": location_descriptor_tpm3.dict(exclude_none=True), "strand": "+" } return TemplatedSequenceComponent(...
c92cfd2e0691c097898d82d7ff2d9eb16e5e2023
24,846
def joint_probability(people, one_gene, two_genes, have_trait): """ Compute and return a joint probability. The probability returned should be the probability that * everyone in set `one_gene` has one copy of the gene, and * everyone in set `two_genes` has two copies of the gene, and ...
c2e8d5d617220d44f625c80f9474ab7327800b6f
24,847
def rf_predict_img_win(win_arr, trained_classifier, prob=True): """Predict image window using input trained classifier. Args: win_arr (numpy.arr): In rasterio order (channels, y, x) trained_classifier (sklearn.model): Trained sklearn model to use for predictions. prob (bool, optional): ...
29b79fb4bcc909cce18889bdd624d6db17eb2d29
24,849
def ShowIPC(cmd_args=None): """ Routine to print data for the given IPC space Usage: showipc <address of ipc space> """ if not cmd_args: print "No arguments passed" print ShowIPC.__doc__ return False ipc = kern.GetValueFromAddress(cmd_args[0], 'ipc_space *') if not...
4511c0aa1315fe594ee8e1209b6bc2e26d633ad9
24,851
def get_mesh_faces(edge_array): """ Uses an edge array of mesh to generate the faces of the mesh. For each triangle in the mesh this returns the list of indices contained in it as a tuple (index1, index2, index3) """ triangles = [] neibs = neibs_from_edges(edge_array) for edge in ...
e1f555985e3e55c2d0fbc3d0fd92befc6eb2c878
24,853
def _make_attribution_from_nodes(mol: Mol, nodes: np.ndarray, global_vec: np.ndarray) -> GraphsTuple: """Makes an attribution from node information.""" senders, receivers = _get_mol_sender_receivers(mol) data_dict = { 'nodes': nodes.astype(np.float32), 'sende...
dcf3f82c0634afa8ba6ea97694ea36e9fd62c563
24,854
def subrepo(repo, subset, x): """Changesets that add, modify or remove the given subrepo. If no subrepo pattern is named, any subrepo changes are returned. """ # i18n: "subrepo" is a keyword args = getargs(x, 0, 1, _('subrepo takes at most one argument')) pat = None if len(args) != 0: ...
c95cdb08671ca1800ffbc0df94833cdb29ba534a
24,855
def format_output(item, show_url=False): """ takes a voat post and returns a formatted string """ if not item["Title"]: item["Title"] = formatting.truncate(item["Linkdescription"], 70) else: item["Title"] = formatting.truncate(item["Title"], 70) item["link"] = voat_fill_url.format(item["...
1b730507fbff1ab2deadeaaefcfbcd23356ee437
24,856
def get_compiled_table_name(engine, schema, table_name): """Returns a table name quoted in the manner that SQLAlchemy would use to query the table Args: engine (sqlalchemy.engine.Engine): schema (str, optional): The schema name for the table table_name (str): The name of the table ...
91234bbfea2ff55d9d3e14b1ad70eb81ff09fc5d
24,857
def build(filepath): """Returns the window with the popup content.""" ttitlebar = titlebar.build() hheading = heading.build(HEADING_TITLE) top_txt_filler = fillers.horizontal_filler(2, colors.BACKGROUND) message = sg.Text( text=MESSAGE_TEXT + filepath, font=MESSAGE_FONT, te...
b5bfd7f46955351a94763360fb44cc59eeccbb39
24,858
def format_float(digit=0, is_pct=False): """ Number display format for pandas Args: digit: number of digits to keep if negative, add one space in front of positive pct is_pct: % display Returns: lambda function to format floats Examples: >>> format_f...
9f719b7e1609744d673226eb32f0395b50b34f51
24,859
def get_overexpressed_genes( matrix: ExpMatrix, cell_labels: pd.Series, exp_thresh: float = 0.05, ignore_outliers: bool = True, num_genes: int = 20) -> pd.DataFrame: """Determine most over-expressed genes for each cluster.""" # make sure matrix and cell_labels are aligned matrix = m...
44c02d2a9be936cee582c750c680925024604f64
24,860
def heat_degree_day(Tcolumn): """ Returns a list of the heating degree day from an outdoor temperature list params: df is a pandas dataframe with datetime index and field named 'outT' which contains outdoor temperature in Fahrenheit base -- temperature base for the heating degree day va...
60cb58520f5451b25b3e8a42bb35c262018bb902
24,861
def quantile_loss(y_true, y_pred, taus): """ The quantiles loss for a list of quantiles. Sums up the error contribution from the each of the quantile loss functions. """ e = skewed_absolute_error( K.flatten(y_true), K.flatten(y_pred[:, 0]), taus[0]) for i, tau in enumerate(taus[1:]): ...
1d06085b0939cf8307d1ceb2bd65a8f7bbde53e0
24,862
from typing import Tuple from typing import Sequence import string def parse_a3m(a3m_string: str) -> Tuple[Sequence[str], DeletionMatrix]: """Parses sequences and deletion matrix from a3m format alignment. Args: a3m_string: The string contents of a a3m file. The first sequence in the file should be the...
5b1f5f9cfc54cd55602e1d73b92460fbc99b3594
24,863
def build_sub_lattice(lattice, symbol): """Generate a sub-lattice of the lattice based on equivalent atomic species. Args: lattice (ASE crystal class): Input lattice symbol (string): Symbol of species identifying sub-lattice Returns: list of lists: sub_lattice: Cartesia...
7e7748c31f7f082b2e5ec6f21d0a56f60d5ec06c
24,864
def make_url(connection_str): """ """ return _parse_rfc1738_args(connection_str)
2927b541399df8ab134688ae3a3a7274e0efb648
24,865
from typing import Union from typing import Tuple def get_graphs_within_cutoff(structure: Union[Structure, MEGNetMolecule, Molecule], cutoff: float = 5.0, numerical_tol: float = 1e-8) -> Tuple[np.ndarray]: """ Get graph representations from structure within cutoff Args: ...
a745808938160148ddaa345f0e5f8aa11b4a3a5f
24,866
def add_cals1(): """ Add nutrients to daily intake for products. """ if 'username' in session: food = request.form.get("keyword") pr = Product(food) lst = pr.get_products() for i in lst: lyst.append(i) if len(lst) != 0: return render_templa...
acdda46ad1fdce23baee8bae2018cf5e6510895f
24,867
def format_percent(percentage, pos): """ Formats percentages for the 'x' axis of a plot. :param percentage: The fraction between 0.0 and 1.0 :type percentage: float :param pos: The position argument :type pos: int :return: A formatted percentage string :rtype: str """ # pylint: ...
d8566ce36b21adb351141ac72413b927e0f02c11
24,868
import inspect def simple_repr(obj, attrs: tp.Optional[tp.Sequence[str]] = None, overrides: dict = {}): """ Return a simple representation string for `obj`. If `attrs` is not None, it should be a list of attributes to include. """ params = inspect.signature(obj.__class__).parameter...
4aaa3090a2a0fbb282cfc8403d365c562ae6c5d9
24,869
import torch def Gaussian_RadialBasis(basis_size: int, max_radius: float, min_radius=0., num_layers: int = 0, num_units: int = 0, activation_function='relu'): """ Note: based on e3nn.radial.GaussianRadialModel. :param basis_size: :param max_radius: :param min_radius: ...
f518e2706dcb672bf65f0ed9299c1579fec411a3
24,870
def _get_column_outliers_std(column, m=3): """ given a pandas Series representing a column in a dataframe returns pandas Series without the values which are further than m*std :param column: pandas Series representing a column in a dataframe :param m: num of std as of to remove outliers :return:...
b55dd119ce36cdae7f17bb91aae4257b2dfca29e
24,871
def set_filters(request, query, result, static_items=None): """ Sets filters in the query """ query_filters = query['filter']['and']['filters'] used_filters = {} if static_items is None: static_items = [] # Get query string items plus any static items, then extract all the fields ...
fcd4fdb6b804fdcf0dce6dac3d19f1945d858a12
24,873
def generate_random_initial_population(population_size, n_nodes, al): """ Randomly create an initial population :param population_size: population size :type population_size: int :param n_nodes: number of nodes :type n_nodes: int :param al: adjacency list :type al: list of lists :re...
0a219ee6de88f97fa099d5fbc0698cc6712c525f
24,874
def import_mlp_args(hyperparameters): """ Returns parsed config for MultiLayerPerceptron classifier from provided settings *Grid-search friendly """ types = { 'hidden_layer_sizes': make_tuple, 'activation': str, 'solver': str, 'alpha': float, 'batch_size': int...
0bfe7cdd4d85b8cfeee32d82f3dd189d60359690
24,875
import torch def getLayers(model): """ get each layer's name and its module :param model: :return: each layer's name and its module """ layers = [] def unfoldLayer(model): """ unfold each layer :param model: the given model or a single layer :param root: ro...
22565e786eb95e2b8996fad99778068ba15273ea
24,877
def get_config_pdf_version(config_version: str, max_input_version: str) -> str: """ From the PDF version as set in the configuration and the maximum version of all input files, checks for the best PDF output version. Logs a warning, if the version set in the configuration is lower than any of the input ...
6bb98c455a2b701d89c90576a958348f84344cb8
24,878
def threshold_otsu(hist): """Return threshold value based on Otsu's method. hist : array, or 2-tuple of arrays, optional Histogram from which to determine the threshold, and optionally a corresponding array of bin center intensities. An alternative use of this function is to pass it onl...
ea55dd483b0b60f8428240a62720fb53d4e0e80c
24,879
def filter_options(v): """Disable option v""" iris = dataframe() return [ {"label": col, "value": col, "disabled": col == v} for col in iris.columns ]
54277b38d30389b302f1f962667bbb91f0999b4f
24,880
def scatter(x): """ matrix x x^t """ x1 = np.atleast_2d(x) xt = np.transpose(x1) s = np.dot(xt,x1) assert np.array_equal( np.shape(s), [len(x),len(x)] ) return s
9d68eba6d3ffde7fb15d21a5a0d09a775bef96e7
24,881
def get_owned_object_or_40x(klass, owner, include_staff=False, include_superuser=True, *args, **kwargs): """ Returns an object if it can be found (using get_object_or_404). If the object is not owned by the supplied owner a 403 will be raised. """ obj = get_object_or_404(...
7535aa0ce7c77c41823f45c89885b5e2c32ed252
24,882
def ampMeritFunction2(voltages,**kwargs): """Simple merit function calculator. voltages is 1D array of weights for the influence functions distortion is 2D array of distortion map ifuncs is 4D array of influence functions shade is 2D array shade mask Simply compute sum(ifuncs*voltages-distortion...
4443369f5424f536e839439c8deb479d09339e90
24,883
def get_transpose_graph(graph): """Get the transpose graph""" transpose = {node: set() for node in graph.keys()} for node, target_nodes in graph.items(): for target_node in target_nodes: transpose[target_node].add(node) return transpose
f7f8e083659e4214d79472961c7240778f37268d
24,884
def inventory_to_kml_string( inventory, icon_url="https://maps.google.com/mapfiles/kml/shapes/triangle.png", icon_size=1.5, label_size=1.0, cmap="Paired", encoding="UTF-8", timespans=True, strip_far_future_end_times=True): """ Convert an :class:`~obspy.core.inventory.inventory.In...
3b10decafe34b006a41be01e44a5073c2d2d13fb
24,887
def extract_yelp_data(term, categories, price, location, limit, sort_by, attributes, yelp_api_key=yelp): """ This function takes search results (a dictionary) and obtains the name, zip code, address of the possible restaurant matches in the form of a pandas dataframe. Inputs:...
e57ca05265944a3971dfb0af7715e9764dd3112e
24,889
def collect_photo_info(api_key, tag, max_count): """Collects some interesting info about some photos from Flickr.com for a given tag """ photo_collection = [] url = "http://api.flickr.com/services/rest/?method=flickr.photos.search&tags=%s&format=json&nojsoncallback=1&api_key=%s" %(tag, api_key) resp = ...
26e9525639da658f9c9920b5356dd9af4753a1c5
24,890
def yolo_eval(yolo_outputs, image_shape=(720., 1280.), max_boxes=10, score_threshold=.6, iou_threshold=.5): """ Converts the output of YOLO encoding (a lot of boxes) to your predicted boxes along with their scores, box coordinates and classes. Arguments: yolo_outputs -- output of the encoding model (fo...
119524a2f850abba7ff9e1c1c1ca669e44f0a181
24,891
import re def check_date_mention(tweet): """Check the tweet to see if there is a valid date mention for the three dates of pyconopenspaces: 5/11, 5/12, 5/13. Quick fix to override SUTime defaulting to today's date and missing numeric info about event's date """ date_pat = re.compile("([5]{1}\/\d...
67c0de3beac5036d8b7aefa161b82a15257da04f
24,894
def make_nointer_beta(): """Make two random non-intersecting triangles in R^3 that pass the beta test.""" # Corners of triangle B. b1, b2, b3 = np.random.random(3), np.random.random(3), np.random.random(3) # Two edges of B. p1 = b2 - b1 p2 = b3 - b1 n = np.cross(p1, p2) n /= np.linalg....
6502e5992f4fe959ec1fe87f3c5e849bfc428d30
24,896
def get_all_with_given_response(rdd, response='404'): """ Return a rdd only with those requests that received the response code entered. Default set to '404'. return type: pyspark.rdd.PipelinedRDD """ def status_iterator(ln): try: status = ln.split(' '...
8268095938bbc35a6418f557af033a458f041c89
24,897
def get_refl_weight(value, source_node): """Returns the reflection weight for Redshift Material :param value: :param source_node: :return: """ refl_color_map = source_node.ParameterBlock.texmap_reflection.Value refl_color_map_name = None try: refl_color_map_name = refl_color_map...
601f4be49c536e9efdac4873dddbc76726dc63ba
24,899
def createSMAbasis(delta, pistonMode, pistonProj): """ Input args: <delta> is the geometric covariance matrix of actuators, it is computed elsewhere. It is a square, symmetric matrix 60x60 <pistonMode> : piston mode (will be used in sparta) This will create a basis orthogonal to pi...
216e0cd5e36ab9ea437f47b349ccffc670d3a898
24,900
def s3_put_bucket_website(s3_obj, bucketname, website_config): """ Boto3 client based Put bucket website function Args: s3_obj (obj): MCG or OBC object bucketname (str): Name of the bucket website_config (dict): Website configuration info Returns: dict : PutBucketWebsit...
a60d95ef43e5a3643edeb6dacb2b149fef1892d9
24,901
from typing import List from typing import Tuple def check_assignment(tokenlist : List[str], current_line : int) -> Tuple[bool, List[Token.Token]]: """Checks if the given construction is of the type 'assignment'. If it is, the first value will return True and the second value will return a list of tokens. If...
2faa56afe89c7d89ff4ec6f4443d8542073bcdaa
24,903
def load_nifc_fires(): """load nifc data for 2020/2021 fire season NB this is a bit of an undocumented NIFC feature -- the data supposedly only cover 2021 but there are definitely 2020 fires included at the endpoint. This might not be true in the future. https://data-nifc.opendata.arcgis.com/datas...
97767eb2bf850e7753cab5fc945efa7b4e235b85
24,904
from datetime import datetime from unittest.mock import call from unittest.mock import patch def test_api_query_paginated_trades_pagination(mock_bitstamp): """Test pagination logic for trades works as expected. First request: 2 results, 1 valid trade (id 2) Second request: 2 results, no trades Third ...
f1bb9cd15c0b595bb9fc1bbfb7e6ce87042ff087
24,905
def eigenvalue_nonunitary_entanglement_infidelity(a, b, mx_basis): """ Returns (d^2 - 1)/d^2 * (1 - sqrt(U)), where U is the eigenvalue-unitarity of a*b^{-1} Parameters ---------- a : numpy.ndarray The first process (transfer) matrix. b : numpy.ndarray The second process (trans...
754717a951868bdc498f4f3a7bc0013c9ffe662f
24,906
def morph(word, rootlist, Indo = False, n = 5): """ Bagi sesuatu perkataan ("word"), kembalikan n analisis morphologi yang paling mungkin berdasarkan senarai akar ("rootlist"). Format output: akar, perkataan, proklitik/awalan, akhiran/enklitik, apitan, reduplikasi @param Indo: Jika benar, awalan N-...
320ee4767b87ee336df4c132fb282d2a6a987412
24,908
def get_logger(name): """ Returns a logger from the registry Parameters ---------- name : str the name indicating the logger to return Returns ------- :class:`delira.logging.base_logger.Logger` the specified logger object """ return _AVAILABLE_LOGGERS[name]
3228e2e0bff57795c590868a06276a0ec57ea985
24,909
from typing import Union from pathlib import Path import yaml def load_yaml(path: Union[str, Path], pure: bool = False) -> dict: """config.yaml file loader. This function converts the config.yaml file to `dict` object. Args: path: .yaml configuration filepath pure: If True, just load the ....
163f48dc48e8dff998ce35dd5f9f1dcfce94eeee
24,910
def InterpolatedCurveOnSurfaceUV1(thisSurface, points, tolerance, closed, closedSurfaceHandling, multiple=False): """ Returns a curve that interpolates points on a surface. The interpolant lies on the surface. Args: points (System.Collections.Generic.IEnumerable<Point2d>): List of at least two UV p...
84ef7894b7d2f3aba43d494212f900ddb683bb92
24,911
def show(request, url, alias_model, template): """List all vouched users with this group.""" group_alias = get_object_or_404(alias_model, url=url) if group_alias.alias.url != url: return redirect('groups:show_group', url=group_alias.alias.url) group = group_alias.alias in_group = group.memb...
f2fccbc267ac8ce589182ff9bdf520c0d91cf294
24,912
import re def index(): """ Home page. Displays subscription info and smart-sorted episodes. """ client = JsonClient(session["username"], session["password"]) subs = get_subscriptions(client, session["username"]) recent_episodes = smart_sort(client, session["username"]) for ep in recent_episodes: ...
5596198aa8e8f257f0f2531dd4e76d4f3ec9d23a
24,913
from typing import Optional def range( lower: int, upper: int, step: Optional[int] = None, name: Optional[str] = None ) -> Series: """ Create a Series that ranges from lower bound to upper bound. Parameters ---------- lower Lower bound value. upper Upper bound value. st...
849cb808495d89294768d8d98d7444f03eade593
24,914
import bisect def ticks_lt(exact_price): """ Returns a generator for all the ticks below the given price. >>> list(ticks_lt(Decimal('0.35'))) [Decimal('0.34'), Decimal('0.33'), Decimal('0.20'), Decimal('0.10'), Decimal('0.01')] >>> list(ticks_lt(Decimal('0.20'))) [Decimal('0.10'), Decimal('0....
aa291f00021e4b3bfe78c7fb406aa81beb9d3467
24,916
def _decode_to_string(to_decode): """ This function is needed for Python 3, because a subprocess can return bytes instead of a string. """ try: return to_decode.decode("utf-8") except AttributeError: # bytesToDecode was of type string before return to_decode
3a9f4ef2719f74e259e119dc1e43a9cbdd655dd5
24,917
def nn(x_dict): """ Implementation of a shallow neural network.""" # Extract Input. x = x_dict["images"] # First Hidden Layer. layer_1 = tf.layers.dense(x, 256) # Second Hidden Layer. layer_2 = tf.layers.dense(layer_1, 256) # Output Layer. output_layer = tf.layers.dense(layer_2, 10)...
6e47efcd03c335137f0ce30665978a9d38c7df3f
24,918
def find_negamax_move_alphabeta(game_state, valid_moves, depth, alpha, beta, turn_multiplier): """ NegaMax algorithm with alpha beta pruning. Alpha beta pruning eliminates the need to check all moves within the game_state tree when a better branch has been found or a branch has too low of a score. ...
de245eaa7a675af7348348d84e61972138663270
24,919
def sum_kernel(X, Y, kernels = None): """ Meta Kernel for summing multiple kernels. """ _sum = 0 for kernel in kernels: print("Doing", kernel["class"], "with parameters:", kernel["parameters"]) _sum = _sum + globals()[kernel["class"]](X, Y, **kernel["parameters"]) return _sum
a2b042b08026e4c87f028687c4521cc1e81c4af5
24,920
def pretvori_v_sekunde(niz): """ Pretvori niz, ki predstavlja dolžino skladbe v formatu hh:mm:ss v število sekund. """ h, m, s = map(int, niz.split(":")) return s + m*60 + h*3600
db0cc5872109b15e635b2b1e8731a5343d63f518
24,921
import logging def _get_profiling_data(filename): """Read a given file and parse its content for profiling data.""" data, timestamps = [], [] try: with open(filename, "r") as f: file_data = f.readlines() except Exception: logging.error("Could not read profiling data.", exc...
85f434c9aa22d60bae06205162623cde83e5a716
24,922
def parse_dataset_name(dataset_name: str) -> (str, str): """ Split the string of the dataset name into two parts: dataset source name (e.g., cnc_in_domain) and dataset part (e.g., train). :param dataset_name: :return: dataset source name (e.g., cnc_in_domain) and dataset part (e.g., train). """ ...
e308d3f29e37b5453d47a36ef2baf94454ac90d3
24,923
def plot_pq(df_pq, df_pq_std=None, columns=('mae', 'r2s'), title='Performance-Quantile'): """Plot the quantile performance plot from the prepared metrics table. Args: df_pq (pd.DataFrame): The QP table information with mean values. df_pq_std (pd.DataFrame): The QP table information ...
3bd02080c74b1bf05f9f6a8cda3b0d22ac847e9f
24,925
def protoToOpenAPISchemaRecursive(lines, schemas, schemaPrefix, basename): """ Recursively create a schema from lines read from a proto file. This method is recursive because proto messages can contain internal messages and enums. If this is the case the method will call itself recursively. :param...
c011a37ddc3fa9fea7c141f24f60a178ac0f7032
24,926
import typing def to_binary(s: typing.Union[str, bytes], encoding='utf8') -> bytes: """Cast function. :param s: object to be converted to bytes. """ return s if isinstance(s, bytes) else bytes(s, encoding=encoding)
ddc442a8124b7d55618cdc06081e496930d292a5
24,927
import gzip def load_numpy(data_path, save_disk_flag=True): """Load numpy.""" if save_disk_flag: # Save space but slow f_data = gzip.GzipFile(f'{data_path}.gz', "r") data = np.load(f_data) else: data = np.load(data_path) return data
9979e2e232fcc96d5fe865ba01a4ba5d36fd1b11
24,928
def mock_weather_for_coordinates(*args, **kwargs): # noqa: F841 """Return mock data for request weather product type.""" if args[2] == aiohere.WeatherProductType[MODE_ASTRONOMY]: return astronomy_response if args[2] == aiohere.WeatherProductType[MODE_HOURLY]: return hourly_response if a...
527bd91866984cc966ff6ad2e1b438591bc7f9d2
24,929
def get_user(request, project_key): """Return the ID of the current user for the given project""" projects = request.cookies.get('projects') if projects is None: return None try: projects = json.loads(projects) except (ValueError, KeyError, TypeError): print "JSON format erro...
4edb40eb0ccece32bd1c0fc3f44ab42e97b9770c
24,930
def extract_month(cube, month): """ Slice cube to get only the data belonging to a specific month. Parameters ---------- cube: iris.cube.Cube Original data month: int Month to extract as a number from 1 to 12 Returns ------- iris.cube.Cube data cube for spec...
31e51654875abb08f727ecf6eb226a3b3b008657
24,931
def is_insert_grad_of_statement(node): """Check whether a context manager calls `insert_grad_of`. Args: node: The context manager node. Returns: Whether or not this node contains `insert_grad_of` calls. Raises: ValueError: If the `insert_grad_of` calls are mixed with other calls. """ tangent_...
f1a8494716577f349b780880210d80cc4a941c1e
24,932