content
stringlengths
22
815k
id
int64
0
4.91M
def get_car_changing_properties(car): """ Gets cars properties that change during a trip :param car: car info in original system JSON-dict format :return: dict with keys mapped to common electric2go format """ result = {mapped_key: car.get(original_key, None) for mapped_key, origi...
5,336,300
def get_metadata(record): """ Calls DNZ's API to retrieve the metadata for a given record. """ id = record['id'] url = DNZ_URL + '{id}.json?api_key={key}'.format(id=id, key=DNZ_KEY) try: metadata = get(url).json()['record'] metadata['hash'] = record['hash'] except KeyError...
5,336,301
def client(): """Yield client fixture. See <http://flask.pocoo.org/docs/1.0/testing/#the-testing-skeleton> for ideas to expand this. """ yield backend.PLATEYPUS.test_client()
5,336,302
def _expand_one_dict(cfg, shared): """expand a piece of config Parameters ---------- cfg : dict Configuration shared : dict A dict of shared objects Returns ------- dict, list Expanded configuration """ if shared['default_config_key'] is not None: ...
5,336,303
def _api_decrypt(): """ Return the response dictionary from the KMS decrypt API call. """ kms = _kms() data_key = _cfg_data_key() try: return kms.decrypt(CiphertextBlob=data_key) except botocore.exceptions.ClientError as orig_exc: error_code = orig_exc.response.get("Error", {...
5,336,304
def hide_panel(panel_name, base_url=DEFAULT_BASE_URL): """Hide a panel in the UI of Cytoscape. Other panels will expand into the space. Args: panel_name (str): Name of the panel. Multiple ways of referencing panels is supported: (WEST == control panel, control, c), (SOUTH == table panel...
5,336,305
def test_medicationdispense_10(base_settings): """No. 10 tests collection for MedicationDispense. Test File: medicationdispense0328.json """ filename = base_settings["unittest_data_dir"] / "medicationdispense0328.json" inst = medicationdispense.MedicationDispense.parse_file( filename, conten...
5,336,306
def user_tickets(raffle_prize, user): """return the allocate ticket for user""" return raffle_prize.allocated_tickets(user)
5,336,307
def body_part(ent): """Enrich a body part span.""" data = {} parts = [REPLACE.get(t.lower_, t.lower_) for t in ent] text = ' '.join(parts) if MISSING_RE.search(ent.text.lower()) is not None: data['missing'] = True data['body_part'] = text ent._.data = data
5,336,308
def build(c): """ Clean and build Sphinx docs """ make(c, 'html')
5,336,309
def db_add(src_path, db, new_entry): """Adds a string entry to a database file and the given set variable. If it already exists in the set, do not take any action. """ if new_entry not in db: with open(src_path, "r+") as f: f.seek(0, 2) f.write(str(new_entry) + ...
5,336,310
def init_container(self, **kwargs): """Initialise a container with a dictionary of inputs """ for k, v in kwargs.iteritems(): try: setattr(self, k, v) except Exception as e: # Deal with the array -> list issue if isinstance(getattr(self, k), list) and isin...
5,336,311
def optimize(nn_last_layer, correct_label, learning_rate, num_classes): """ Build the TensorFLow loss and optimizer operations. :param nn_last_layer: TF Tensor of the last layer in the neural network :param correct_label: TF Placeholder for the correct label image :param learning_rate: TF Placeholde...
5,336,312
def setIamPolicy(asset_id, policy): """Sets ACL info for an asset. Args: asset_id: The asset to set the ACL policy on. policy: The new Policy to apply to the asset. This replaces the current Policy. Returns: The new ACL, as an IAM Policy. """ return _execute_cloud_call( _get_cloud_ap...
5,336,313
def get_corners(n): """Returns corner numbers of layer n""" end = end = (2*n + 1) * (2*n + 1) return [end-m*n for m in range(0,8,2)]
5,336,314
def plot_single_hist(histvals, edges, legend=None, **kwds): """ Bokeh-based plotting of a single histogram with legend and tooltips. **Parameters**\n histvals: 1D array Histogram counts (e.g. vertical axis). edges: 1D array Histogram edge values (e.g. horizontal axis). legen...
5,336,315
def resnet50(alpha, beta,**kwargs): """Constructs a ResNet-50 based model. """ model = ResNet(Bottleneck, [3, 4, 6, 3], alpha, beta, **kwargs) checkpoint = torch.load(model_dirs['resnet50']) layer_name = list(checkpoint.keys()) for ln in layer_name: if 'conv' in ln or 'downsample.0.weight' in ln: checkpoint[...
5,336,316
def raise_sql_error(_req): """Raise a sql error""" raise IntegrityError(ERROR_MESSAGE_2)
5,336,317
def get_datetimefromnctime(ds,time,time_units): """ Purpose: Create a series of datetime objects from the time read from a netCDF file. Usage: footprint_utils.get_datetimefromnctime(ds,time,time_units) Side effects: Creates a Python datetime series in the data structure Author: PRI ...
5,336,318
def datetime_to_timestamp(dt, epoch=datetime(1970,1,1)): """takes a python datetime object and converts it to a Unix timestamp. This is a non-timezone-aware function. :param dt: datetime to convert to timestamp :param epoch: datetime, option specification of start of epoch [default: 1/1/1970] :ret...
5,336,319
def connectivity_dict_builder(edge_list, as_edges=False): """Builds connectivity dictionary for each vertex (node) - a list of connected nodes for each node. Args: edge_list (list): a list describing the connectivity e.g. [('E7', 'N3', 'N6'), ('E2', 'N9', 'N4'), ...] as_edges (b...
5,336,320
def get_confusion_matrix(*, labels, logits, batch_mask): """Computes the confusion matrix that is necessary for global mIoU.""" if labels.ndim == logits.ndim: # One-hot targets. y_true = jnp.argmax(labels, axis=-1) else: y_true = labels # Set excluded pixels (label -1) to zero, because the confusion ...
5,336,321
def init_socket(): """Returns a fresh socket""" return socket.socket()
5,336,322
def randomize_cycles(): """Randomize the cycles renderer seed.""" bpy.data.scenes["Scene"].cycles.seed = random.randint(1, 10000000)
5,336,323
def schedule(sched): """Helper function to run the scheduler.""" def _schedule(): """Run the scheduler, output some stats.""" new_placement = 0 evicted = 0 for event in sched.schedule(): if event.node: new_placement = new_placement + 1 els...
5,336,324
def semitone_frequencies(fmin, fmax, fref=A4): """ Returns frequencies separated by semitones. Parameters ---------- fmin : float Minimum frequency [Hz]. fmax : float Maximum frequency [Hz]. fref : float, optional Tuning frequency of A4 [Hz]. Returns -------...
5,336,325
def write_model(output_directory: OutputDirectory, k: float): """Write "our model" (which happens to be a single value). In real life it can be a neural network we obtained, or matrices, or whatever we want to save.""" output_file = os.path.join(output_directory, 'model.json') with open(outpu...
5,336,326
def check_binary_task(cls, method): """Raise an error if the task is invalid.""" if not cls.task.startswith("bin"): raise PermissionError( f"The {method} method is only available for binary classification tasks!" )
5,336,327
def inplace_m_arcsinh_derivative(Z, delta): """Apply the derivative of the hyperbolic m-arcsinh function. It exploits the fact that the derivative is a relatively simple function of the output value from hyperbolic m-arcsinh. Further details on this function are available at: https://arxiv.o...
5,336,328
def dict_get_value(dict: Mapping, name: str) -> Any: """Gets data from a dictionary using a dotted accessor-string :param dict: source dictionary :param name: dotted value name """ current_data = dict for chunk in name.split('.'): if not isinstance(current_data, (Mapping, Sequence)): ...
5,336,329
def get_files_from_split(split): """ " Get filenames for real and fake samples Parameters ---------- split : pandas.DataFrame DataFrame containing filenames """ files_1 = split[0].astype(str).str.cat(split[1].astype(str), sep="_") files_2 = split[1].astype(str).str.cat...
5,336,330
def test_partial_overlap_multiple_ranges( empty_range_stream_fresh, initial_ranges, overlapping_range ): """ Partial overlap with termini of the centred range [3,7) covered on multiple ranges (both termini are contained) but `in` does not report True as the entirety of this interval is not within th...
5,336,331
def main(args): """ args[0] ... dir to place no binaries in args[1] ... log file to parse args[2] ... for longer files lower line number limit args[3] ... for longer files upper line number limit """ with open(args[1], 'r') as f: lines = f.readlines() lower_l = 0...
5,336,332
def dedupBiblioReferences(doc): """ SpecRef has checks in its database preventing multiple references from having the same URL. Shepherd, while it doesn't have an explicit check for this, should also generally have unique URLs. But these aren't uniqued against each other. So, if you explicitly b...
5,336,333
def check_percent(mask_arr, row, col, sz, percent): """ :param mask_arr: mask数组 :param row: :param col: :param sz: :param percent: 有效百分比 :return: """ upper_bound = mask_arr.max() area = np.sum(mask_arr[row:row + sz, col:col + sz]) / upper_bound if area / (sz ** 2) > percent:...
5,336,334
def find_center_pc(proj1, proj2, tol=0.5, rotc_guess=None): """ Find rotation axis location by finding the offset between the first projection and a mirrored projection 180 degrees apart using phase correlation in Fourier space. The ``register_translation`` function uses cross-correlation in Fourier...
5,336,335
def emce_comparison(nus, n_reps=100): """Simulation comparing ECME algorithm with M-estimates. We compare the estimates obtained by the ECME algorithm against two Huber M-estimates with tuning parameters 1 and 4. Args: nus, iter: Iterator of values for the degrees of freedom. n_reps, i...
5,336,336
def usage(): """ Display how to use the Server. """ print """ If you are seeing this message, Congratulations! You ignored the README.md and felt like you knew what you were doing. Good job at that. In all seriousness, most of what you need to know is in the README.md, so check it out to get an...
5,336,337
async def setup_light(hass, count, light_config): """Do setup of light integration.""" await async_setup_light(hass, count, light_config)
5,336,338
def _merge_tables_interactions( key_join, max_num_negatives, ): """Joins the interactions and multiple similar table id by question id. Args: key_join: Input to merge max_num_negatives: Max similar tables to add. None means no limit. Yields: Merged interactions. """ _, join = key_join ...
5,336,339
def to_dot(g, stream=sys.stdout, options=None): """ Args: - g (rdflib.graph): RDF graph to transform into `dot` representation - stream (default: sys.stdout | file): Where to write the output Returns: - (graph): `dot` representation of the graph """ digraph = produce_graph.p...
5,336,340
def seconds(seconds_since_epoch: int) -> date: """Converts a seconds offset from epoch to a date Args: seconds_since_epoch (int): The second offset from epoch Returns: date: The date the offset represents """ return EPOCH + timedelta(seconds=seconds_since_epoch)
5,336,341
def check_presence(user): """ Gets user presence information from Slack ("active" or "away") :param user: The identifier of the specified user :return: True if user is currently active, False if user is away """ if not settings.SLACK_TOKEN: return None client = WebClient(token=set...
5,336,342
def plot_confusion_matrix(truth, predictions, classes, normalize=False, save=False, cmap=plt.cm.Oranges, path="confusion_matrix.png"): """ This function plo...
5,336,343
def insertTagEventRead(handler, event_id, tag_id, data, stable_start, stable_end): """Insert tag event read. Args: handler: Database handler. event_id: Event ID. tag_id: Tag ID. seg_data: Tag segment data (per-antenna RSSI time series) """ name = inspect.stack()[0][3...
5,336,344
def get_candidates(obsid,name_par_list,zmax,f1,f2): """ Getting pulsation candidates within some frequency range. If I want the full frequency range, just do f1 = 0, f2 = some large number. obsid - Observation ID of the object of interest (10-digit str) name_par_list - list of parameters specifying...
5,336,345
def serialize_system(context, system, integrator): """Save context info.""" _write_to_file('system.xml', mm.XmlSerializer.serialize(system)) _write_to_file('integrator.xml', mm.XmlSerializer.serialize(integrator)) # pylint: disable=unexpected-keyword-arg, no-value-for-parameter state = context.getSt...
5,336,346
def FindUpwardParent(start_dir, *desired_list): """Finds the desired object's parent, searching upward from the start_dir. Searches within start_dir and within all its parents looking for the desired directory or file, which may be given in one or more path components. Returns the first directory in which the ...
5,336,347
def _add_position_arguments(parser: argparse.ArgumentParser): """Add the lat and lng attributes to the parser.""" parser.add_argument('lat', type=float, nargs='?', const=0.0, help='(optional) Your current GPS latitude (as float)') parser.add_argument('lng', type=float, nargs='?', con...
5,336,348
def adjust_position_to_boundaries(positions, bounds, tolerance=DEFAULT_TOLERANCE): """ Function to update boid position if crossing a boundary (toroid boundary condition) :param positions: vector of (x,y) positions :param bounds: (xmin,xmax,ymin,ymax) boundaries :param tolerance: optional tolerance ...
5,336,349
def residual_mlp_layer(x_flat, intermediate_size, initializer_range=0.02, hidden_dropout_prob=0.1): """ :param x_flat: The attention output. It should be [batch_size*seq_length, dim] :param intermediate_size: the hidden projection. By default this is the input_dim * 4. in the original GPT we would retu...
5,336,350
def _delete_project_repo(repo_name): """Deletes the specified repo from AWS.""" client = boto3.client('codecommit') response = client.delete_repository(repositoryName=repo_name) return response
5,336,351
def score_items(X, U, mu, scoremethod='lowhigh', missingmethod='none', feature_weights=[]): """score_items(X, U, scoremethod, missingmethod, feature_weights) Calculate the score (reconstruction error) for every item in X, with respect to the SVD model in U and ...
5,336,352
def get_output_specs(output): """ Get the OpenAPI specifications of a SED output Args: output (:obj:`Output`): output Returns: :obj:`dict` with schema `SedOutput` """ if isinstance(output, Report): specs = { '_type': 'SedReport', 'id': output.id, ...
5,336,353
def logggnfw_exact(x, x0, y0, m1, m2, alpha): """ exact form, inspired by gNFW potential OverFlow warning is easily raised by somewhat large values of m1, m2, and base """ base = 1. + np.exp(alpha) x = x - x0 return np.log((base ** x) ** m1 * (1 + base ** x) ** (m2 - m1...
5,336,354
def get_file_size(path: str): """ Return the size of a file, reported by os.stat(). Args: path: File path. """ return os.path.getsize(path)
5,336,355
def is_lepton(pdgid): """Does this PDG ID correspond to a lepton?""" if _extra_bits(pdgid) > 0: return False if _fundamental_id(pdgid) >= 11 and _fundamental_id(pdgid) <= 18: return True return False
5,336,356
def process_data(): """process data""" # prepare cur batch data image_names, labels = get_labels_from_txt( os.path.join(IMAGE_PATH, 'image_label.txt')) if len(labels) < CALIBRATION_SIZE: raise RuntimeError( 'num of image in {} is less than total_num{}' .format(IMA...
5,336,357
def setConfig(): """ Function to create or receive program settings by a .json file. """ filename = "config.json" indent = 4 # Dicionário com as configurações padrões do programa. default_config = { "Colors":{ "Final_scoreboard_background_color":App.FINAL_SCOREBOARD_BA...
5,336,358
def complex_fields_container(real_field, imaginary_field, server = None): """Create a fields container with two fields (real and imaginary) and only one time set. Parameters ---------- real_fields : Field Real :class:`ansys.dpf.core.Field` entity to add to the fields container. imaginary_fi...
5,336,359
def get_time_slots(s : pd.Series, time_interval : str = 'daily'): """Convert timestamps to time slots""" if time_interval.lower() not in ( 'hourly', 'daily', 'weekly', 'monthly', 'quarterly', 'yearly'): raise ValueError return pd.to_datetime(s)\ .dt.to_period(time_interval[0]...
5,336,360
def __setup_conditional_formatting(sheet): """ Add conditional formatting to sheet rows depending on status Parameters ---------- sheet: Sheet sheet to setup conditional formatting for """ start_cell = f'{ascii_uppercase[0]}2' end_cell = f'{ascii_uppercase[len(__headers)-1]}{Sp...
5,336,361
def build_optimising_metaclass( builtins=None, builtin_only=False, stoplist=(), constant_fold=True, verbose=False ): """Return a automatically optimising metaclass for use as __metaclass__.""" class _OptimisingMetaclass(type): def __init__(cls, name, bases, dict): super(_Optimis...
5,336,362
def update(save=True): """Update local `players.csv <https://raw.githubusercontent.com/ryan-byrne/pycobb/main/pycobb/utils/players.csv>`_ file using data from the `Chadwick Baseball Bureau <https://github.com/chadwickbureau>`_ :param save: (optional) Chose to save the update locally Usage:: ...
5,336,363
def get_ensembl_id(hgnc_id): """Return the Ensembl ID corresponding to the given HGNC ID. Parameters ---------- hgnc_id : str The HGNC ID to be converted. Note that the HGNC ID is a number that is passed as a string. It is not the same as the HGNC gene symbol. Returns ------- ...
5,336,364
def predict(model, dataloader): """Returns: numpy arrays of true labels and predicted probabilities.""" device = torch.device("cuda" if torch.cuda.is_available() else "cpu") model.to(device) model.eval() labels = [] probs = [] for batch_idx, batch in enumerate(dataloader): inputs, ...
5,336,365
def _ProcessMemoryAccess(instruction, operands): """Make sure that memory access is valid and return precondition required. (only makes sense for 64-bit instructions) Args: instruction: Instruction tuple operands: list of instruction operands as strings, for example ['%eax', '(%r15,%rbx,1)...
5,336,366
def minimizeMeshDimensions(obj, direction, step, epsilon): """ Args: obj: direction: step: epsilon: Returns: """ stepsum = 0 while True: before, after = compareOrientation(obj, direction * step) if before < after: # bpy.ops.transform.rot...
5,336,367
def zip_and_move(source, destination): """Zip a directory and move to `destination` Args: - source (str): Directory to zip and move to destination. - destination (str): Destination file path to zip file. """ os.chdir(os.path.dirname(source)) shutil.make_archive(os.path.basename(sour...
5,336,368
def gimme_dj(mystery_val: int, secret_val: int) -> str: """Play that funky music.""" # If youre worried about what this is doing, and NEED TO KNOW. Check this gist: # https://gist.github.com/SalomonSmeke/2dfef1f714851ae8c6933c71dad701ba # its nothing evil. just an inside joke for my good buddy Brian. ...
5,336,369
def pluecker_from_verts(A,B): """ See Hartley & Zisserman (2003) p. 70 """ if len(A)==3: A = A[0], A[1], A[2], 1.0 if len(B)==3: B = B[0], B[1], B[2], 1.0 A=nx.reshape(A,(4,1)) B=nx.reshape(B,(4,1)) L = nx.dot(A,nx.transpose(B)) - nx.dot(B,nx.transpose(A)) return Lmat...
5,336,370
def _send_tcp_ssl_file(sdc_executor): """Sends a file through tcp using ssl""" hostname = sdc_executor.server_host context = ssl.create_default_context() context.check_hostname = False context.verify_mode = ssl.CERT_NONE with socket.create_connection((hostname, TCP_PORT)) as sock: with ...
5,336,371
def setup_module(): """Check we have a recent enough version of sphinx installed. """ ret = call([sys.executable, '-msphinx', '--help'], stdout=PIPE, stderr=PIPE) if ret != 0: raise RuntimeError( "'{} -msphinx' does not return 0".format(sys.executable))
5,336,372
def MAP_score(source_id, target_labels, prediction): """ Function to compute the Mean Average Precision score of a given ranking. Args: source_id (array): Array containing the source_id of our given queries. target_labels (array): Array containing the target labels of our query-docu...
5,336,373
def get_model_config(model): """Returns hyper-parameters for given mode""" if model == 'maml': return 0.1, 0.5, 5 if model == 'fomaml': return 0.1, 0.5, 100 return 0.1, 0.1, 100
5,336,374
def split_train_test_cresus_data(tables, outfold, ratio=0.20, fLOG=fLOG): # pylint: disable=W0621 """ Splits the tables into two sets for tables (based on users). @param tables dictionary of tables, @see fn prepare_cresus_data @param outfold i...
5,336,375
def update_draw(attr, old, new): """ Updates :any:`Opt_w`, :any:`Opt_SPLoverX_dict` and :any:`SPLoverX_optreg`, when :any:`optimal_SPLoverX` function was triggered. This happens if the target slope weighting is chosen and the user changes the target slope. Triggered by data change of :any:`Opt_SPLov...
5,336,376
def classify_images(): """ Creates classifier labels with classifier function, compares labels, and creates a dictionary containing both labels and comparison of them to be returned. PLEASE NOTE: This function uses the classifier() function defined in classifier.py within this function. The ...
5,336,377
def find_longest_substring(s: str, k: int) -> str: """ Speed: ~O(N) Memory: ~O(1) :param s: :param k: :return: """ # longest substring (found) lss = "" # current longest substring c_lss = "" # current list of characters for the current longest substring c_c = [] ...
5,336,378
def _fixTool2(scModel,gopLoader): """ :param scModel: :param gopLoader: :return: @type scModel: ImageProjectModel """ def replace_tool(tool): return 'jtui' if 'MaskGenUI' in tool else tool modifier_tools = scModel.getGraph().getDataItem('modifier_tools') if modifier_tools ...
5,336,379
def gen_non_ca_cert(filename, dirname, days, ip_list, dns_list, ca_crt, ca_key, silent=False): """ generate a non CA key and certificate key pair signed by the private CA key and crt. :param filename: prefix for the key and cert file :param dirname: name of the directory :par...
5,336,380
def test_stream_decompresser(compression_algorithm): """Test the stream decompresser.""" StreamDecompresser = utils.get_stream_decompresser( # pylint: disable=invalid-name compression_algorithm ) # A short binary string (1025 bytes, an odd number to avoid possible alignments with the chunk siz...
5,336,381
def mol_view(request): """Function to view a 2D depiction of a molecule -> as PNG""" my_choice = request.GET['choice'].split("_")[0] try: mol = Chem.MolFromSmiles(str(InternalIDLink.objects.filter(internal_id=my_choice)[0].mol_id.smiles)) except IndexError: mol = Chem.MolFromSmiles(str(M...
5,336,382
def rotation_matrix_about(axis, theta): """Return the rotation matrix associated with counterclockwise rotation about the given axis by theta radians. Taken from: https://stackoverflow.com/a/6802723 """ if np.shape(axis) != (3,): raise ValueError("Shape of `axis` must be (3,)!") scala...
5,336,383
def main(argv): """ Read the seed URL and Keyword from the command line arguments """ startingDepth=1 seedURLS=Stack() if len(argv)==2: pageResourceURI=re.sub(urlPrefixRegex, '', argv[0]) pageURLAnchorText=("SeedURLForCrawler",pageResourceURI) seedURLS.push(pageU...
5,336,384
def run_gui(): """Run under GUI and non-verbose mode.""" # sys.settrace(util.trace_calls_and_returns) root = ui.build_script_launcher( title=_basename, app_dir=_script_dir, progress_queue=_progress_queue, handlers={ 'OnQuit': _RTPC.quit, 'OnSubmit': _R...
5,336,385
def zc_rules(): """catch issues with zero copy streaming""" return ( case("SSTableReader"), rule( capture( r"Could not recreate or deserialize existing bloom filter, continuing with a pass-through bloom filter but this will significantly impact reads performance" ...
5,336,386
def name_convert_to_camel(name: str) -> str: """下划线转驼峰""" contents = re.findall('_[a-z]+', name) for content in set(contents): name = name.replace(content, content[1:].title()) return name
5,336,387
def triangle_as_polynomial(nodes, degree): """Convert ``nodes`` into a SymPy polynomial array :math:`B(s, t)`. Args: nodes (numpy.ndarray): Nodes defining a B |eacute| zier triangle. degree (int): The degree of the triangle. This is assumed to correctly correspond to the number of `...
5,336,388
def configure(name, key, value): """Add an environment variable to a Heroku application""" # Get Heroku application app = get(name) # Set environment variable app.config()[key] = value
5,336,389
def retrieve_docs( collection_cache: KeyValueStore, errors: List, missing: List, stats: Dict, ) -> None: # pylint: disable=too-many-locals """Extract the docs from the plugins. :param collection_cache: The key value interface to a sqlite database :param errors: Previous errors encounter...
5,336,390
def as_decimal(dct): """Decodes the Decimal datatype.""" if '__Decimal__' in dct: return decimal.Decimal(dct['__Decimal__']) return dct
5,336,391
def input_layer(features, feature_columns, weight_collections=None, trainable=True, cols_to_vars=None, cols_to_output_tensors=None): """Returns a dense `Tensor` as input layer based on given `feature_columns`. Generally a single exampl...
5,336,392
def test_s3_3_4v29_s3_3_4v29i(mode, save_output, output_format): """ Multiple attributes of type ID with default value """ assert_bindings( schema="ibmData/valid/S3_3_4/s3_3_4v29.xsd", instance="ibmData/valid/S3_3_4/s3_3_4v29.xml", class_name="Root", version="1.1", ...
5,336,393
def log_sum_exp(x): """Utility function for computing log_sum_exp while determining This will be used to determine unaveraged confidence loss across all examples in a batch. Args: x (Variable(tensor)): conf_preds from conf layers """ log_reduce_sum = P.ReduceSum() log = P.Log() e...
5,336,394
def data_dir(): """ :return: data directory in the filesystem for storage, for example when downloading models """ return os.getenv('CNOCR_HOME', data_dir_default())
5,336,395
def validate_user_alert_incident(incidents): """ internal method used in test_fetch_user_alert_incident_success_with_param_alerts """ assert len(incidents) == 3 for incident in incidents: assert incident['name'] assert incident['rawJSON'] raw_json = json.loads(incident['rawJS...
5,336,396
def prepareRepoCharts(url, name, auths): """ NOTE: currently not support git """ charts_info, charts_info_hash = _prepareHelmRepoPath(url, name, auths) return charts_info, charts_info_hash
5,336,397
def num_ini_spaces(s): """Return the number of initial spaces in a string. Note that tabs are counted as a single space. For now, we do *not* support mixing of tabs and spaces in the user's input. Parameters ---------- s : string Returns ------- n : int """ ini_spaces = ...
5,336,398
def make_filename_template(schema, **kwargs): """Create codeblocks containing example filename patterns for a given datatype. Parameters ---------- schema : dict The schema object, which is a dictionary with nested dictionaries and lists stored within it. kwargs : dict K...
5,336,399