content
stringlengths
22
815k
id
int64
0
4.91M
def create_background_consumers(count, before_start=None, target='run', *args, **kwargs): """Create new Consumer instances on background threads, starts them, and return a tuple ([consumer], [thread]). :param count: The number of Consumer instances to start. :param before_start: A callable that will be...
5,326,700
def linkGen(year): """ This function generates the download links based on user input. """ current_year = datetime.datetime.now().year try: if (int(year) >= 2016) and (int(year) <= int(current_year)): url = f"http://dev.hsl.fi/citybikes/od-trips-{year}/od-trips-{year}.zip" ...
5,326,701
def factory_dict(value_factory, *args, **kwargs): """A dict whose values are computed by `value_factory` when a `__getitem__` key is missing. Note that values retrieved by any other method will not be lazily computed; eg: via `get`. :param value_factory: :type value_factory: A function from dict key to value....
5,326,702
def squash(): """ Squash an image and remove layers """ print("[maple.image.squash] not available for singularity backend")
5,326,703
def build_or_passthrough(model, obj, signal): """Builds the obj on signal, or returns the signal if obj is None.""" return signal if obj is None else model.build(obj, signal)
5,326,704
def dump(value, filename, *, compress=("zlib", 7), protocol=HIGHEST_PROTOCOL): """Dump a Python object to disk.""" filename = os.path.abspath(filename) try: try: # sometimes the latter won't work where the externals does despite same __version__ from sklearn.externals.joblib import dump...
5,326,705
def load_generated_energy_gwh_yearly_irena(): """Returns xr.DataArray with dims=year and integer as coords, not timestamp!""" generated_energy_twh = pd.read_csv( INPUT_DIR / "energy_generation_irena" / "irena-us-generation.csv", delimiter=";", names=("year", "generation"), ) gene...
5,326,706
def warc_url(url): """ Search the WARC archived version of the URL :returns: The WARC URL if found, else None """ query = "http://archive.org/wayback/available?url={}".format(url) response = requests.get(query) if not response: raise RuntimeError() data = json.loads(response....
5,326,707
def check_gpu(): """ Check if GPUs are available on this machine """ try: cuda.gpus.lst tf = True except cuda.CudaSupportError: tf = False return tf
5,326,708
def vm_impl_avg_pool(self): """Generate vm_impl function for AvgPool""" def vm_impl(x): x = x.asnumpy() out = vm.avg_pooling(x, self.ksize[-2], self.ksize[-1], self.strides[-2]) return Tensor(out) return vm_impl
5,326,709
def daemonize(stdin=os.devnull, stdout=os.devnull, stderr=None, pidfile=None, exit=True, chdir='/'): """ Does a double-fork to daemonize the current process using the technique described at http://www.erlenstar.demon.co.uk/unix/faq_2.html#SEC16 . If exit is True (default), parent exits immediately. If...
5,326,710
def plotAllPoints(x,y,z,f,x0,con): """ Args: x- initial x points y- initial y points z- initial z points f- objective function for optimization x0- flattened initial values to be shoved into objective function con- list of dicts of constraints to be placed on the ...
5,326,711
def plot_sfr_vout_correlation_with_binning(OIII_outflow_results, OIII_outflow_error, hbeta_outflow_results, hbeta_outflow_error, hbeta_no_outflow_results, hbeta_no_outflow_error, BIC_outflow, BIC_no_outflow, statistical_results, z, radius, header, data_descriptor, plot_data_fits=False): """ Plots the SFR surfac...
5,326,712
def add_samples(request, product_id): """Adds passed samples (by request body) to product with passed id. """ parent_product = Product.objects.get(pk=product_id) for temp_id in request.POST.keys(): if temp_id.startswith("product") is False: continue temp_id = temp_id.split(...
5,326,713
def array_to_top_genes(data_array, cluster1, cluster2, is_pvals=False, num_genes=10): """ Given a data_array of shape (k, k, genes), this returns two arrays: genes and values. """ data_cluster = data_array[cluster1, cluster2, :] if is_pvals: order = data_cluster.argsort() else: ...
5,326,714
def parse_fastani_write_prophage(CRISPR_mates): """[summary] Args: CRISPR_mates ([type]): [description] Returns: [type]: [description] """ if not os.path.exists('prophageannotations'): os.system('mkdir -p prophageannotations') viral_cluster_prophages = dict() for...
5,326,715
def set_attrib(node, key, default): """ Parse XML key for a given node If key does not exist, use default value """ return node.attrib[key] if key in node.attrib else default
5,326,716
def nested_hexagon_stretched(): """A stretched, nested hexagon""" poly = [ [ (0.86603, -0.5), (0.86603, 1.5), (0.0, 2.0), (-0.86603, 1.5), (-0.86603, -0.5), (-0.0, -1.0), (0.86603, -0.5), ], [ ...
5,326,717
def _patch_dynamodb_connection(**kwargs): """:class:`boto.dynamodb2.layer1.DynamoDBConnection` patcher. It partially applies the keyword arguments to the :class:`boto.dynamodb2.layer1.DynamoDBConnection` initializer method. The common usage of this function would be patching host and port to the lo...
5,326,718
def vector(math_engine, size, dtype): """ """ if dtype != "float32" and dtype != "int32": raise ValueError('The `dtype` must be one of {`float32`, `int32`}.') if size < 1: raise ValueError('The `size` must be > 0.') shape = (size, 1, 1, 1, 1, 1, 1) return Blob(PythonWrapper.ten...
5,326,719
def images(arrays, labels=None, domain=None, width=None): """Display a list of images with optional labels. Args: arrays: A list of NumPy arrays representing images labels: A list of strings to label each image. Defaults to show index if None domain: Domain of pixel values, ...
5,326,720
def is_order_exist(context, symbol, side) -> bool: """判断同方向订单是否已经存在 :param context: :param symbol: 交易标的 :param side: 交易方向 :return: bool """ uo = context.unfinished_orders if not uo: return False else: for o in uo: if o.symbol == symbol and o.side == side:...
5,326,721
def getBestMove(board,selectedFunction = "minmax"): """find the best move Args: board (board): board object from chess Returns: UCI.move: piece movement on the board, i.e. "g2g4" """ #Get AI Movement maxWeight = 0 deplacement = None #Get movement in the polyglot ...
5,326,722
def newline_prep(target_str, do_escape_n=True, do_br_tag=True): """ Set up the newlines in a block of text so that they will be processed correctly by Reportlab and logging :param target_str: :param do_escape_n: :param do_br_tag: :return: """ newline_str = get_newline_str(do_escape_n=do_...
5,326,723
def train( seed, _log, size=100, window=5, min_count=5, epochs=5, use_fasttext=False, workers=1, vectors_only=True, save_to='vectors.txt'): """Train word2vec/fastText word vectors.""" if not FAST_VERSION: warnings.warn( ...
5,326,724
def romb_extrap(sr, der_init, expon, compute_amp = False): """ Perform Romberg extrapolation for estimates formed within derivest. Arguments: sr : Decrease ratio between successive steps. der_init : Initial derivative estimates. expon : List of orders corr...
5,326,725
def cadmin_assign_coord(course_id): """ Set someone as course coordinator """ course = Courses2.get_course(course_id) if not course: abort(404) if not "coord" in request.form: abort(400) new_uname = request.form['coord'] # TODO: Sanitize username try: new_uid = User...
5,326,726
def nativeTextOverline(self): """ TOWRITE :rtype: bool """ return self.textOverline()
5,326,727
def test_directory_without_notebooks(capsys: "CaptureFixture") -> None: """ Check sensible error message is returned if none of the directories passed have notebooks. Parameters ---------- capsys Pytest fixture to capture stdout and stderr. """ with pytest.raises(SystemExit): ...
5,326,728
def ca_(arr, l_bound=4000, guard_len=4, noise_len=8): """Perform CFAR-CA detection on the input array. Args: arr (list or ndarray): Noisy array. l_bound (int): Additive lower bound of detection threshold. guard_len (int): Left and right side guard samples for leakage protection. ...
5,326,729
def get(): """ vert notifier get """ table: object = Table(box=SQUARE) table.add_column('ID') table.add_column('Title') table.add_column('Message', justify='center') table.add_column('Hour') rows: tuple[tuple] = Routines.get() for row in rows: table.add_row('%d' % (row[...
5,326,730
def test_graph_del_node_with_edges(test_graph): """Test graph del node with edges.""" test_graph[2].add_edge('A', 'C') test_graph[2].add_edge('B', 'C') test_graph[2].add_edge('B', 'C') test_graph[2].add_edge('A', 'D') test_graph[2].del_node('C') assert sorted(test_graph[2].nodes()) == ['A', ...
5,326,731
def create_nodes_encoder(properties): """Create an one-hot encoder for node labels.""" nodes_encoder = OneHotEncoder(handle_unknown='ignore') nodes_labels = list(get_nodes_labels(properties)) nodes_encoder.fit(np.array(nodes_labels).reshape((-1, 1))) return nodes_encoder
5,326,732
def dummy(): """Placeholder function. .. warning:: This function is not implemented yet! """ raise NotImplementedError("This feature is not implemented yet.")
5,326,733
def _run_cli( input_file_path: Optional[str], molecule_smiles: Optional[str], output_file_path: str, force_field_path: Optional[str], spec_name: Optional[str], spec_file_name: Optional[str], directory: str, n_fragmenter_workers: int, n_qc_compute_workers: int, n_optimizer_workers...
5,326,734
def get_response(data_type, client_id=None, device_id=None): """Request GET from API server based on desired type, return raw response data Args: data_type (str): Type of request, 'client', 'site', 'device', 'scan' client_id (int): Active client ID number ...
5,326,735
def average_pool(inputs, masks, axis=-2, eps=1e-10): """ inputs.shape: [A, B, ..., Z, dim] masks.shape: [A, B, ..., Z] inputs.shape[:-1] (A, B, ..., Z) must be match masks.shape """ assert inputs.shape[:-1] == masks.shape, f"inputs.shape[:-1]({inputs.shape[:-1]}) must be equal to masks.shape({ma...
5,326,736
def validate_graph_without_circle(data): """ validate if a graph has not cycle return { "result": False, "message": "error message", "error_data": ["node1_id", "node2_id", "node1_id"] } """ nodes = [data["start_event"]["id"], data["end_event"]["id"]] nodes += list(d...
5,326,737
def generate_landsat_ndvi(src_info, no_data_value): """Generate Landsat NDVI Args: src_info <SourceInfo>: Information about the source data no_data_value <int>: No data (fill) value to use Returns: <numpy.2darray>: Generated NDVI band data list(<int>): Locations containing ...
5,326,738
def plot_df1D(df_slice, x_feature_axis, y_feature_name="obj", sign=+1, **kwargs): """ Plots values from data frame in 1D. Args: df_slice data frame slice with known function values (in column y_feature_name) x_feature_axis name of the feature that the plot will go along ...
5,326,739
def ordinal(string): """ Converts an ordinal word to an integer. Arguments: - string -- the word to parse. Returns: an integer if successful; otherwise None. ----------------------------------------------------------------- """ try: # Full word. ...
5,326,740
def get_tables_stats(dbs=None,tables=None,period=365*86400): """ obtains counts and frequencies stats from all data tables from all dbs """ dbs = dbs or pta.multi.get_hdbpp_databases() result = fn.defaultdict(fn.Struct) date = int(fn.clsub('[^0-9]','',fn.time2str().split()[0])) if period: ...
5,326,741
def blend(image1, image2, factor): """Blend image1 and image2 using 'factor'. A value of factor 0.0 means only image1 is used. A value of 1.0 means only image2 is used. A value between 0.0 and 1.0 means we linearly interpolate the pixel values between the two images. A value greater than 1.0 "ext...
5,326,742
def call_subprocess_Popen(command, **params): """ Calls subprocess_Popen and discards the output, returning only the exit code. """ if 'stdout' in params or 'stderr' in params: raise TypeError("don't use stderr or stdout with call_subprocess_Popen") null = open(os.devnull, 'wb') # st...
5,326,743
def _minmax_scaler(data, settings): """Normalize by min max mode.""" info = settings['model'] frag = settings['id_frag'] features = settings['input_col'] alias = settings.get('output_col', []) min_r, max_r = settings.get('feature_range', (0, 1)) remove_input = settings.get('remove', False) ...
5,326,744
def find_by_id(widget_id): """ Get a widget by its ulid. """ return db.select_single('widgets', {'widget_id':widget_id}, None, ['widget_id', 'widget_name', 'user_id', 'user_email', 'description'])
5,326,745
def sainte_lague(preliminary_divisor, data, total_available_seats): """Iterative Sainte-Lague procedure which applies core_sainte_lague Input: preliminary_divisor (float): Guess for the divisor data (pd.DateFrame): data processed with divisors (e.g. votes by party) total_available_seats (int): numb...
5,326,746
def nonchangingdims(index, ndim, axes, shape=None): """nonchanging for particular dimensions Args: index(index): object used in slicing (expanded) ndim(num): dimensions before indexings axes(array): dimensions for which you want to know the index shape(Optional(tuple)): dimensio...
5,326,747
def test_longer_random_sequence_of_queue_ops(buffer_type): """A long random sequence of added and retrieved values""" q = buffer_type(100, 80) for _ in six.moves.xrange(10000): if q.can_add(): _add_many(q, np.random.random((np.random.randint(1, 10),))) assert q.size < 100 + 10 ...
5,326,748
def get_voxels(df, center, config, rot_mat=np.eye(3, 3)): """ Generate the 3d grid from coordinate format. Args: df (pd.DataFrame): region to generate grid for. center (3x3 np.array): center of the grid. rot_mat (3x3 np.array): rotation matrix to a...
5,326,749
def dispatch_factory(msg: Result, **kwargs) -> DispatchCallOutSchema: """result_factory Generate result as expected by Daschat Examples: from daschat_base.messages import MSGS, msg_factory msg_factory(MSGS.success) msg_factory(MSGS.not_logged_in, user="abner") Args: msg (Re...
5,326,750
def local_config(config_path=FIXTURE_CONFIG_PATH): """Return an instance of the Config class as a fixture available for a module.""" return Config(config_path=config_path)
5,326,751
def ln_prior(theta, parameters_to_fit): """priors - we only reject obviously wrong models""" if theta[parameters_to_fit.index("t_E")] < 0.: return -np.inf if theta[parameters_to_fit.index("t_star")] < 0.: return -np.inf return 0.0
5,326,752
def get_axis_letter_aimed_at_child(transform): """ Returns the axis letter that is poinitng to the given transform :param transform: str, name of a transform :return: str """ vector = get_axis_aimed_at_child(transform) return get_vector_axis_letter(vector)
5,326,753
def computeLatitudePrecision(codeLength): """ Compute the latitude precision value for a given code length. Lengths <= 10 have the same precision for latitude and longitude, but lengths > 10 have different precisions due to the grid method having fewer columns than rows. """ if codeLengt...
5,326,754
def EmptyStateMat(nX,nU,nY): """ Returns state matrices with proper dimensions, filled with 0 """ Xx = np.zeros((nX,nX)) # Ac Yx = np.zeros((nY,nX)) # Gc Xu = np.zeros((nX,nU)) # Xu Yu = np.zeros((nY,nU)) # Jc return Xx,Xu,Yx,Yu
5,326,755
def update_db(): """Update all parts of the DB""" dbpopulate.ships() dbpopulate.equip() dbpopulate.items() dbpopulate.recipe_resources() dbpopulate.expeditions() try: setup() except sqlalchemy.exc.IntegrityError: pass
5,326,756
def get_market(code): """ 非常粗糙的通过代码获取交易市场的函数 :param code: :return: """ trans = { "USD": "US", "GBP": "UK", "HKD": "HK", "CNY": "CN", "CHF": "CH", "JPY": "JP", "EUR": "DE", "AUD": "AU", "INR": "IN", "SGD": "SG", ...
5,326,757
def rawPlot(): """Description. More... """ def f(t): return numpy.exp(-t) * numpy.cos(2*numpy.pi*-t) plot_x = 495 plot_y = 344 fig = plt.figure(figsize=[plot_x * 0.01, plot_y * 0.01], # Inches. dpi=100, # 100 dots per inch, so the resulting buffer is 3...
5,326,758
def CanopyHeight(strPathLAS, strPathDTM, fltCellSize, strPathBEFile, strUTMZone, strAdlSwitches = None, strParamBoss = None): """Function CanopyModel args: strPathLAS = input LAS file strPathDTM = output canopy surface/height dtm fltCellSize = cell size in ma...
5,326,759
def corrupt_single_relationship(triple: tf.Tensor, all_triples: tf.Tensor, max_range: int, name=None): """ Corrupt the relationship by __sampling from [0, max_range] :param triple: :param all_triples: :param...
5,326,760
def save_ipynb_from_py(folder: str, py_filename: str) -> str: """Save ipynb file based on python file""" full_filename = f"{folder}/{py_filename}" with open(full_filename) as pyfile: code_lines = [line.replace("\n", "\\n").replace('"', '\\"') for line in pyfile.readlines()] ...
5,326,761
def send(): """ Updates the database with the person who is responding and their busy times. """ invitee = request.args.get('invitee') busy_times = request.args.get('busy_times') meetcode = flask.session['meetcode'] # Get the record with this meet code. record = collection.find({"code":...
5,326,762
def get_plos_article_type_list(article_list=None, directory=None): """Makes a list of of all internal PLOS article types in the corpus Sorts them by frequency of occurrence :param article_list: list of articles, defaults to None :param directory: directory of articles, defaults to get_corpus_dir() ...
5,326,763
def e_coordenada(arg): """tuplo -> Boole Esta funcao verifica se o argumento que recebe e um tuplo do tipo coordenada""" return isinstance(arg,tuple) and len(arg)==2 and 1<=coordenada_linha(arg)<=4 and 1<=coordenada_coluna(arg)<=4 and isinstance(coordenada_linha(arg),int) and isinstance(coordenada_coluna...
5,326,764
def make_coro(func): """Wrap a normal function with a coroutine.""" async def wrapper(*args, **kwargs): """Run the normal function.""" return func(*args, **kwargs) return wrapper
5,326,765
def list_repos_by_owner(owner): """Print and return a list with the owner's repositories. """ repos = get_repos_by_owner(owner) x = PrettyTable(['Name', 'ID', 'Last build ID']) x.align['Name'] = 'l' x.align['Description'] = 'l' for r in repos: ...
5,326,766
def eliminate(values): """Apply the eliminate strategy to a Sudoku puzzle The eliminate strategy says that if a box has a value assigned, then none of the peers of that box can have the same value. Parameters ---------- values(dict) a dictionary of the form {'box_name': '123456789', ...} Returns ------- d...
5,326,767
def cli( connection, path, all, table, skip, redact, sql, output, pk, index_fks, progress ): """ Load data from any database into SQLite. PATH is a path to the SQLite file to create, e.c. /tmp/my_database.db CONNECTION is a SQLAlchemy connection string, for example: postgresql://localhost...
5,326,768
def test_mg_i019_mg_i019_v(mode, save_output, output_format): """ TEST :model groups (ALL) : choice: with children 4 any, 4 elements """ assert_bindings( schema="msData/modelGroups/mgI019.xsd", instance="msData/modelGroups/mgI019.xml", class_name="Doc", version="1.1", ...
5,326,769
def set_new_shortcut(name, command, binding): """Creates a new shortcuts. Creates a new custom shortcut in Gnome's settings. The new identifier of this shortcut is `/org/gnome/settings-daemon/plugins/media-keys/custom-keybindings/<name>/`. Parameters ---------- name: str Name referring...
5,326,770
def sqlpool_blob_auditing_policy_update( cmd, instance, workspace_name, resource_group_name, sql_pool_name, state=None, blob_storage_target_state=None, storage_account=None, storage_endpoint=None, storage_account_access_key=None, st...
5,326,771
def load_plugins(ginga): """Load the ``stginga`` plugins. Parameters ---------- ginga The ginga app object that is provided to ``pre_gui_config`` in ``ginga_config.py``. """ stglobal_plugins, stlocal_plugins = _get_stginga_plugins() # Add custom global plugins for gplg...
5,326,772
def find_unique_ID(list_of_input_smpls): """Attempt to determine a unique ID shared among all input sample names/IDs, via a largest substring function performed combinatorially exhaustively pairwise among the input list. Parameters ---------- list_of_input_smpls : list Returns ------- ...
5,326,773
def cartesian_to_polar(xy): """Convert :class:`np.ndarray` `xy` to polar coordinates `r` and `theta`. Args: xy (:class:`np.ndarray`): x,y coordinates Returns: r, theta (tuple of float): step-length and angle """ assert xy.ndim == 2, f"Dimensions are {xy.ndim}, expecting 2" x, y ...
5,326,774
def savefiles(linklist, outputflag, args): """Using links collected by getlinks() and parsed by bs4, this function saves file(s) of the html contents of the <body> tag of web pages in one of three ways: as separate html files, as separate PDF files (using the pdfkit package and wkhtmltopdf), or by ...
5,326,775
def return_manifold(name): """ Returns a list of possible manifolds with name 'name'. Args: name: manifold name, str. Returns: list of manifolds, name, metrics, retractions """ m_list = [] descr_list = [] if name == 'ChoiMatrix': list_of_metrics = ['euc...
5,326,776
def change_to_rgba_array(image, dtype="uint8"): """Converts an RGB array into RGBA with the alpha value opacity maxed.""" pa = image if len(pa.shape) == 2: pa = pa.reshape(list(pa.shape) + [1]) if pa.shape[2] == 1: pa = pa.repeat(3, axis=2) if pa.shape[2] == 3: alphas = 255 *...
5,326,777
def spacetime_lookup(ra,dec,time=None,buffer=0,print_table=True): """ Check for overlapping TESS ovservations for a transient. Uses the Open SNe Catalog for discovery/max times and coordinates. ------ Inputs ------ ra : float or str ra of object dec : float or str dec of object time : float reference t...
5,326,778
def main(): """ Main function. """ # First Specify all parameters domain_vars = [{'name': 'rw', 'type': 'float', 'min': 0.05, 'max': 0.15, 'dim': 1}, {'name': 'L_Kw', 'type': 'float', 'min': 0, 'max': 1, 'dim': 2}, {'name': 'Tu', 'type': 'int', 'min': 63070, 'max': 115600, 'dim...
5,326,779
def utc2local(utc: Union[date, datetime]) -> Union[datetime, date]: """Returns the local datetime Args: utc: UTC type date or datetime. Returns: Local datetime. """ epoch = time.mktime(utc.timetuple()) offset = datetime.fromtimestamp(epoch) - datetime.utcfromtimestamp(epoch) ...
5,326,780
def getAsDateTimeStr(value, offset=0,fmt=_formatTimeStr()): """ return time as 2004-01-10T00:13:50.000Z """ import sys,time import types from datetime import datetime if (not isinstance(offset,str)): if isinstance(value, (tuple, time.struct_time,)): return time.strftime(fmt, val...
5,326,781
def gvisc(P, T, Z, grav): """Function to Calculate Gas Viscosity in cp""" #P pressure, psia #T temperature, °R #Z gas compressibility factor #grav gas specific gravity M = 28.964 * grav x = 3.448 + 986.4 / T + 0.01009 * M Y = 2.447 - 0.2224 * x rho =...
5,326,782
def drawTime2avgFlow(df4time2flow: pd.DataFrame, save: bool = True) -> NoReturn: """生成车站-时段图(采用七天平均值) Args: df4time2flow (pd.DataFrame): 经generateTime2FlowDf函数生成的数据集 save (bool, optional): 是否将图像进行保存而非显示. Defaults to True. """ # 绘制车站-时段图(采用七天平均值) plt.figure(figsize=(13, 9)) fig =...
5,326,783
def get_closest_mesh_normal_to_pt(mesh, pt): """ Finds the closest vertex normal to the point. Parameters ---------- mesh: :class: 'compas.datastructures.Mesh' pt: :class: 'compas.geometry.Point' Returns ---------- :class: 'compas.geometry.Vector' The closest normal of the ...
5,326,784
async def apiDiscordAssignrolesDelete(cls:"PhaazebotWeb", WebRequest:ExtendedRequest) -> Response: """ Default url: /api/discord/assignroles/delete """ Data:WebRequestContent = WebRequestContent(WebRequest) await Data.load() # get required vars guild_id:str = Data.getStr("guild_id", UNDEFINED, must_be_digit=Tru...
5,326,785
def handle_new_application(sender, instance, created, **kwargs): """ Send welcome message to learner introducing them to their facilitator """ if not created: return application = instance # get a random piece of advice # TODO only supported in English atm advice = None if applicat...
5,326,786
def plot_water_levels(station, dates, levels): """ displays a plot of the water level data against time for a station """ plt.plot(dates, levels, label="Fetched Data") plt.hlines( station.typical_range, min(dates, default=0), max(dates, default=0), linestyles="dashed"...
5,326,787
def algo_reg_deco(func): """ Decorator for making registry of functions """ algorithms[str(func.__name__)] = func return func
5,326,788
def find_top_slices(metrics: List[metrics_for_slice_pb2.MetricsForSlice], metric_key: Text, statistics: statistics_pb2.DatasetFeatureStatisticsList, comparison_type: Text = 'HIGHER', min_num_examples: int = 10, num_top_s...
5,326,789
def parse_texts(texts): """ Create a set of parsed documents from a set of texts. Parsed documents are sequences of tokens whose embedding vectors can be looked up. :param texts: text documents to parse :type texts: sequence of strings :return: parsed documents :rtype: sequence of spacy.Do...
5,326,790
def dict_to_string(d): """Return the passed dict of items converted to a json string. All items should have the same type Args: d (dict): Dictionary to convert Returns: str: JSON version of dict """ j = {} for key, value in d.items(): if value is None: ...
5,326,791
def domains(request): """ A page with number of services and layers faceted on domains. """ url = '' query = '*:*&facet=true&facet.limit=-1&facet.pivot=domain_name,service_id&wt=json&indent=true&rows=0' if settings.SEARCH_TYPE == 'elasticsearch': url = '%s/select?q=%s' % (settings.SEARCH...
5,326,792
def load_test_data(path, var, years=slice('2017', '2018')): """ Args: path: Path to nc files var: variable. Geopotential = 'z', Temperature = 't' years: slice for time window Returns: dataset: Concatenated dataset for 2017 and 2018 """ assert var in ['z', 't'], 'Test...
5,326,793
def measure_of_dispersion(type_, df, col): """Calculate the measure of dispersion. This function accepts the measure of dispersion to be calculated, the data frame and the required column(s). It returns the calculated measure. Keyword arguments: type_ -- type of central tendency to be calc...
5,326,794
def encode(state, b=None): """ Encode a base-*b* array of integers into a single integer. This function uses a `big-endian`__ encoding scheme. That is, the most significant bits of the encoded integer are determined by the left-most end of the unencoded state. >>> from pyinform.uti...
5,326,795
def get_equivalent(curie: str, cutoff: Optional[int] = None) -> Set[str]: """Get equivalent CURIEs.""" canonicalizer = Canonicalizer.get_default() r = canonicalizer.single_source_shortest_path(curie=curie, cutoff=cutoff) return set(r or [])
5,326,796
def _standardize_input(y_true, y_pred, multioutput): """ This function check the validation of the input input should be one of list/tuple/ndarray with same shape and not be None input will be changed to corresponding 2-dim ndarray """ if y_true is None or y_pred is None: raise ValueErro...
5,326,797
def warning_si_demora(limite_segs, mensaje): """ Context manager para chequear la duración de algo, y si demora demasiado, disparar un warning. """ inicio = datetime.now() yield fin = datetime.now() duracion_segs = int((fin - inicio).total_seconds()) if limite_segs is not None and dur...
5,326,798
def disk_detach(vmdk_path, vm): """detach disk (by full path) from a vm and return None or err(msg)""" device = findDeviceByPath(vmdk_path, vm) if not device: # Could happen if the disk attached to a different VM - attach fails # and docker will insist to sending "unmount/detach" which also ...
5,326,799