content
stringlengths
22
815k
id
int64
0
4.91M
def test_include_via_python_module_name(tmpdir): """Check if an include can be a Python module name""" settings_file = tmpdir.join("settings.toml") settings_file.write( """ [default] default_var = 'default' """ ) dummy_folder = tmpdir.mkdir("dummy") dummy_folder.join("...
33,300
def download_table_dbf(file_name, cache=True): """ Realiza o download de um arquivo auxiliar de dados do SINAN em formato "dbf" ou de uma pasta "zip" que o contém (se a pasta "zip" já não foi baixada), em seguida o lê como um objeto pandas DataFrame e por fim o elimina Parâmetros ---------- ...
33,301
def test_one_core_fail(cache_mode): """ title: Test if OpenCAS correctly handles failure of one of multiple core devices. description: | When one core device fails in a single cache instance all blocks previously occupied should be available to other core devices. Test ...
33,302
def aq_name(path_to_shp_file): """ Computes the name of a given aquifer given it's shape file :param path_to_shp_file: path to the .shp file for the given aquifer :return: a string (name of the aquifer) """ str_ags = path_to_shp_file.split('/') str_aq = "" if len(str_ags) >= 2: ...
33,303
def check_dbtable(dbname, tablename): """ Check tablename exists in database""" LOGGER.info(f"Checking {tablename} exits in: {dbname}") # Connect to DB con = sqlite3.connect(dbname) # Create the table create_table = """ CREATE TABLE IF NOT EXISTS {tablename} ( {statement} ) """.f...
33,304
def execution_start(): """Code to execute after the config files and command line flags have been parsedself. This setuptools hook is the earliest that will be able to use custom command line flags. """ # Add to the search patterns used by modules if "ALFA" not in config.sp: config....
33,305
def clear_old_snapshots(): """ Remove any old snapshots to minimize disk space usage locally. """ logging.info('Removing old Cassandra snapshots...') try: subprocess.check_call([NODE_TOOL, 'clearsnapshot']) except CalledProcessError as error: logging.error('Error while deleting old Cassandra snapshots. ...
33,306
def enable_host_logger(): """Enable host logger for logging stdout from remote commands as it becomes available. """ enable_logger(host_logger)
33,307
def validate_json(): """validates if input is in JSON format""" if not request.is_json: abort(400, "request should be in JSON format")
33,308
def gini(arr, mode='all'): """Calculate the Gini coefficient(s) of a matrix or vector. Parameters ---------- arr : array-like Array or matrix on which to compute the Gini coefficient(s). mode : string, optional One of ['row-wise', 'col-wise', 'all']. Default is 'all'. Returns ...
33,309
def build_future_index(): """ 编制指数数据:期货加权指数,主力合约指数,远月主力合约,交割主力合约 对应的symbol-xx00:持仓量加权,xx11:成交量加权,xx88:主力合约,x99:远月合约,xx77:交割月合约 按成交量对同一天的交易合约进行排序,取排名前三的交易合约,成交量最大的为主力合约 最接近当月的合约为交割主力合约,在主力合约后交割的为远月主力合约 :return: """ # 更新数据库行情数据 独立运行,不在此处更新数据 # insert_hq_to_mongo() # 连接数据库 # co...
33,310
def getIndex(): """ Retrieves index value. """ headers = { 'accept': 'application/json', } indexData = requests.get( APIUrls.lnapi+APIUrls.indexUrl, headers=headers, ) if indexData.status_code == 200: return indexData.json() else: raise Runti...
33,311
def add_formflow_to_graph(graph, formflow): """Add a formflow object and its edges to the graph Also iterates through tasks (formflow steps) and adds form displays, formflow jump, run command rules as well as any referenced conditions """ graph.add_node(formflow.guid, formflow.map()) FORMFL...
33,312
def getDataFile(fname): """Return complete path to datafile fname. Data files are in the directory skeleton/skeleton/data """ return os.path.join(getDataPath(),fname)
33,313
def input_as_string(filename:str) -> str: """returns the content of the input file as a string""" with open(filename, encoding="utf-8") as file: return file.read().rstrip("\n")
33,314
def channame_to_python_format_string(node, succgen=None): """See channame_str_to_python_format_string @succgen is optional, if given will check that identifiers can be found. """ if not node: #empty AST return (True, "") if node.type == 'Identifier': # and len(node.children) >= 1: ...
33,315
def write_colorama(typ: str, name: str, msg: str, encoding: str) -> None: """if we're writing to the screen""" try: _write_colorama_screen(typ, name + msg) except IOError: sys.stdout.write(f'error writing line...encoding={encoding!r}\n') sys.stdout.write(msg)
33,316
def clean_import(): """Create a somewhat clean import base for lazy import tests""" du_modules = { mod_name: mod for mod_name, mod in sys.modules.items() if mod_name.startswith("bs_dateutil") } other_modules = {mod_name for mod_name in sys.modules if mod_name not in du_modules} ...
33,317
def is_bad(x): """ for numeric vector x, return logical vector of positions that are null, NaN, infinite""" if can_convert_v_to_numeric(x): x = safe_to_numeric_array(x) return numpy.logical_or( pandas.isnull(x), numpy.logical_or(numpy.isnan(x), numpy.isinf(x)) ) return pa...
33,318
def psf_generator(cmap='hot', savebin=False, savetif=False, savevol=False, plot=False, display=False, psfvol=False, psftype=0, expsf=False, empsf=False, realshape=(0,0), **kwargs): """Calculate and save point spread functions.""" args = { 'shape': (50, 50), # number of samples in z and r direction 'dims': (5.0,...
33,319
def test_populate_extra_data_square_day(): """ If we have found a 'square' day, the description and square value is added """ value = 7 week_data = {'mon': {'value': value}} description = '__DESCRIPTION__' populate_extra_data(week_data, description) assert week_data == { 'mon':...
33,320
def evaluate_model(model, X_test, y_test, category_names): """Predict data based on the test set of the input variables Args: model (sklearn.model_selection): Model X_test (numpy.ndarray): Test set of the input variables y_test (pandas.DataFrame): Test set of the output variables ...
33,321
def test_errors(): """ Test error. :return: """ with raises(PyboticsError): raise PyboticsError() assert str(PyboticsError()) == PyboticsError().message assert str(PyboticsError("test")) == "test"
33,322
def save_team_images(column='team_wordmark'): """Function will loop through a dataframe column and save URL images locally""" df = pd.read_csv(r'https://github.com/guga31bb/nflfastR-data/raw/master/teams_colors_logos.csv') my_series = df[column] my_list = my_series.to_list() for im_url in my_list: ...
33,323
def correct_format(): """ This method will be called by iolite when the user selects a file to import. Typically, it uses the provided name (stored in plugin.fileName) and parses as much of it as necessary to determine if this importer is appropriate to import the data. For example, although X S...
33,324
def move_channel_down(midiout): """ """ activate_pattern_window(midiout) keyboard.send('alt', True, False) keyboard.send('down', True, False) keyboard.send('down', False, True) keyboard.send('alt', False, True)
33,325
def T0_T0star(M, gamma): """Total temperature ratio for flow with heat addition (eq. 3.89) :param <float> M: Initial Mach # :param <float> gamma: Specific heat ratio :return <float> Total temperature ratio T0/T0star """ t1 = (gamma + 1) * M ** 2 t2 = (1.0 + gamma * M ** 2) ** 2 t3 = 2...
33,326
def remount_as( ip: Optional[str] = None, writeable: bool = False, folder: str = "/system" ) -> bool: """ Mount/Remount file-system. Requires root :param folder: folder to mount :param writeable: mount as writeable or readable-only :param ip: device ip :rtype:...
33,327
def cli(ctx): """list create modify addtovolumeaccessgroup removefromvolumeaccessgroup delete """
33,328
def flip_channels(img): """Flips the order of channels in an image; eg, BGR <-> RGB. This function assumes the image is a numpy.array (what's returned by cv2 function calls) and uses the numpy re-ordering methods. The number of channels does not matter. If the image array is strictly 2D, no re-orde...
33,329
def autodiscover_datafiles(varmap): """Return list of (dist directory, data file list) 2-tuples. The ``data_dirs`` setup var is used to give a list of subdirectories in your source distro that contain data files. It is assumed that all such files will go in the ``share`` subdirectory of the pre...
33,330
def dict_to_hdf5(dic, endpoint): """Dump a dict to an HDF5 file. """ filename = gen_filename(endpoint) with h5py.File(filename, 'w') as handler: walk_dict_to_hdf5(dic, handler) print('dumped to', filename)
33,331
def parse_main(index): """Parse a main function containing block items. Ex: int main() { return 4; } """ err = "expected main function starting" index = match_token(index, token_kinds.int_kw, ParserError.AT, err) index = match_token(index, token_kinds.main, ParserError.AT, err) index = mat...
33,332
def elist2tensor(elist, idtype): """Function to convert an edge list to edge tensors. Parameters ---------- elist : iterable of int pairs List of (src, dst) node ID pairs. idtype : int32, int64, optional Integer ID type. Must be int32 or int64. Returns ------- (Tensor, ...
33,333
def _term_to_xapian_value(term, field_type): """ Converts a term to a serialized Xapian value based on the field_type. """ assert field_type in FIELD_TYPES def strf(dt): """ Equivalent to datetime.datetime.strptime(dt, DATETIME_FORMAT) but accepts years below 1900 (see h...
33,334
def printname(name): """ Print whatever is given for name Parameters ---------- name : object Any printable object Returns ------- no return : print statement """ print(name)
33,335
def pop_stl1(osurls, radiourls, splitos): """ Replace STL100-1 links in 10.3.3+. :param osurls: List of OS platforms. :type osurls: list(str) :param radiourls: List of radio platforms. :type radiourls: list(str) :param splitos: OS version, split and cast to int: [10, 3, 3, 2205] :type...
33,336
def process_map_model_validation_error(self, exception_map, exception): """ Processes the exception map for the given exception. This process method includes the specific information of this exception into the exception map. :type exception_map: Dictionary :param exception_map: The map c...
33,337
def processAlert(p_json): """ create pyFireEyeAlert Instance of the json and makes all the mapping :param p_json: :type p_json: """ logger.debug(p_json) fireinstance = pyFireEyeAlert(p_json) # This comment will be added to every attribute for reference auto_comment = "Auto genera...
33,338
def empty_search(): """ :return: json response of empty list, meaning empty search result """ return jsonify(results=[])
33,339
def clip_raster_mean(raster_path, feature, var_nam): """ Opens a raster file from raster_path and applies a mask based on a polygon (feature). It then extracts the percentage of every class with respects to the total number of pixels contained in the mask. :param raster_path: raster path (ras...
33,340
def problem475(): """ 12n musicians participate at a music festival. On the first day, they form 3n quartets and practice all day. It is a disaster. At the end of the day, all musicians decide they will never again agree to play with any member of their quartet. On the second day...
33,341
def load_data(in_file): """load json file from seqcluster cluster""" with open(in_file) as in_handle: return json.load(in_handle)
33,342
def main(inargs): """Run the program.""" cube = iris.load_cube(inargs.infile, 'sea_water_salinity') cube = gio.salinity_unit_check(cube) outfile_metadata = {inargs.infile: cube.attributes['history'],} cube.attributes['history'] = gio.write_metadata(file_info=outfile_metadata) iris.save(cub...
33,343
def test_setitem(atom_dict): """Test setting items. """ atom_dict.untyped[''] = 1 atom_dict.keytyped[1] = '' with pytest.raises(TypeError): atom_dict.keytyped[''] = 1 atom_dict.valuetyped[1] = 1 with pytest.raises(TypeError): atom_dict.valuetyped[''] = '' atom_dict.fu...
33,344
def test_multichannel(): """Test adding multichannel image.""" viewer = ViewerModel() np.random.seed(0) data = np.random.random((15, 10, 5)) viewer.add_image(data, channel_axis=-1) assert len(viewer.layers) == data.shape[-1] for i in range(data.shape[-1]): assert np.all(viewer.layers...
33,345
def applyPatch(sourceDir, f, patchLevel='0'): """apply single patch""" if os.path.isdir(f): # apply a whole dir of patches out = True with os.scandir(f) as scan: for patch in scan: if patch.is_file() and not patch.name.startswith("."): out ...
33,346
def run_script(script: Script, options: CliOptions) -> None: """ Run the script with the given (command line) options. """ template_ctx = build_template_context(script, options) verbose = RunContext().get('verbose') pretend = RunContext().get('pretend') if verbose >= 3: log.info('Compiling ...
33,347
def expand_at_linestart(P, tablen): """只扩展行开头的制表符号""" import re def exp(m): return m.group().expandtabs(tablen) return ''.join([ re.sub(r'^\s+', exp, s) for s in P.splitlines(True) ])
33,348
def print_full_dataframe(df): """ Helper function to print a pandas dataframe with NO truncation of rows/columns This will reset the defaults after, so it can be useful for inspection without annoying side effects in a script (pulled from a stack overflow example). """ pd.set_option('display.max...
33,349
def configs(): """Create a mock Configuration object with sentinel values Eg. Configuration( base_jar=sentinel.base_jar, config_file=sentinel.config_file, ... ) """ return Configuration(**dict( (k, getattr(sentinel, k)) for k in DEFAU...
33,350
def svn_fs_revision_root_revision(root): """svn_fs_revision_root_revision(svn_fs_root_t * root) -> svn_revnum_t""" return _fs.svn_fs_revision_root_revision(root)
33,351
def config_ospf_interface( tgen, topo=None, input_dict=None, build=False, load_config=True ): """ API to configure ospf on router. Parameters ---------- * `tgen` : Topogen object * `topo` : json file data * `input_dict` : Input dict data, required when configuring from testcase * `b...
33,352
def is_floatscalar(x: Any) -> bool: """Check whether `x` is a float scalar. Parameters: ---------- x: A python object to check. Returns: ---------- `True` iff `x` is a float scalar (built-in or Numpy float). """ return isinstance(x, ( float, np.float16, ...
33,353
async def start_handler(event, channel_layer, msg_data): """ Handler for "/start" """ current_bot = await bot_client.get_me() user_details = await bot_client.get_entity(event.message.peer_id.user_id) bot = Bot.objects.get(id=current_bot.id) individual, i_created = IndividualChat.objects.ge...
33,354
def http_header_control_cache(request): """ Tipo de control de cache url: direccion de la pagina web""" print "--------------- Obteniendo cache control -------------------" try: cabecera = request.headers cache_control = cabecera.get("cache-control") except Exception: cache_c...
33,355
def summation(limit): """ Returns the summation of all natural numbers from 0 to limit Uses short form summation formula natural summation :param limit: {int} :return: {int} """ return (limit * (limit + 1)) // 2 if limit >= 0 else 0
33,356
def reportoutputfiles(tasklistlist): """ report on what files will be output by the tasks input: list of list of tasks output: none (prints to screen) """ print print "listing output files" pathlist = [] for tasklist in tasklistlist: for task in tasklist: ...
33,357
def main(): """Main operational flow""" # Set target locations and specific filename local_data_folder = './../input-data' target_def_blob_store_path = '/blob-input-data/' input_filename = 'HPI_master_cleansed.csv' # Get input data files from local data_file_paths = data_filepaths(data_fold...
33,358
def load_and_initialize_hub_module(module_path, signature='default'): """Loads graph of a TF-Hub module and initializes it into a session. Args: module_path: string Path to TF-Hub module. signature: string Signature to use when creating the apply graph. Return: graph: tf.Graph Graph of the m...
33,359
def application(): """An application for testing""" yield create_test_application()
33,360
def j_index(true_labels, predicts): """ j_index Computes the Jaccard Index of the given set, which is also called the 'intersection over union' in multi-label settings. It's defined as the intersection between the true label's set and the prediction's set, divided by the sum, or union, of th...
33,361
def mkdir_p(path): """Make a directory if it doesn't already exist""" try: os.makedirs(path) except OSError as exc: # Python >2.5 if exc.errno == errno.EEXIST and os.path.isdir(path): pass else: raise
33,362
def odefun(x, t, net, alph=[1.0,1.0,1.0]): """ neural ODE combining the characteristics and log-determinant (see Eq. (2)), the transport costs (see Eq. (5)), and the HJB regularizer (see Eq. (7)). d_t [x ; l ; v ; r] = odefun( [x ; l ; v ; r] , t ) x - particle position l - log determinant ...
33,363
def create_transform(num_flow_steps, param_dim, context_dim, base_transform_kwargs): """Build a sequence of NSF transforms, which maps parameters x into the base distribution u (noise). Transforms are conditioned on strain data y. Note that the...
33,364
def filterUniques(tar, to_filter, score, ns): """ Filters unique psms/peptides/proteins from (multiple) Percolator output XML files. Takes a tarred set of XML files, a filtering query (e.g. psms), a score to filter on and a namespace. Outputs an ElementTree. """ for tf in to_filter: ...
33,365
def test_normal_double(): """Exercise the EndpointHandler functionality.""" handler = TwoEndpointHandler() # Receiver handler.to_receive(('int', 1)) assert handler.has_receive() received = list(handler.receive_all()) assert len(received) == 1 assert received[0].data == 2 assert not ...
33,366
def for_in_pyiter(it): """ >>> for_in_pyiter(Iterable(5)) [0, 1, 2, 3, 4] """ l = [] for item in it: l.append(item) return l
33,367
def train_test_split_with_none(X, y=None, sample_weight=None, random_state=0): """ Splits into train and test data even if they are None. @param X X @param y y @param sample_weight sample weight @param random_state random state @return ...
33,368
def plot_by_gene_and_domain(name, seqs, tax, id2name): """ plot insertions for each gene and domain """ for gene in set([seq[0] for seq in list(seqs.values())]): for domain in set([seq[1] for seq in list(seqs.values())]): plot_insertions(name, seqs, gene, domain, tax, id2name)
33,369
def measure_time(func, repeat=1000): """ Repeatedly executes a function and records lowest time. """ def wrapper(*args, **kwargs): min_time = 1000 for _ in range(repeat): start = timer() result = func(*args, **kwargs) curr_time = timer() - start ...
33,370
def initialise_players(frame_data, params): """ initialise_players(team,teamname,params) create a list of player objects that holds their positions and velocities from the tracking data dataframe Parameters ----------- team: row (i.e. instant) of either the home or away team tracking Datafram...
33,371
def filter_access_token(interaction, current_cassette): """Add Betamax placeholder to filter access token.""" request_uri = interaction.data["request"]["uri"] response = interaction.data["response"] if "api/v1/access_token" not in request_uri or response["status"]["code"] != 200: return body...
33,372
def read_edgelist(f, directed=True, sep=r"\s+", header=None, keep_default_na=False, **readcsvkwargs): """ Creates a csrgraph from an edgelist. The edgelist should be in the form [source destination] or [source destination edge_weight] The first column needs to be the source,...
33,373
def is_comment(txt_row): """ Tries to determine if the current line of text is a comment line. Args: txt_row (string): text line to check. Returns: True when the text line is considered a comment line, False if not. """ if (len(txt_row) < 1): return True if ((txt_row...
33,374
def updateBillingPlanPaymentDefinition(pk, paypal_payment_definition): """Update an existing payment definition of a billing plan :param pk: the primary key of the payment definition (associated with a billing plan) :type pk: integer :param paypal_payment_definition: Paypal billing plan payment d...
33,375
def format_float_list(array: List[float], precision: int = 4) -> List[str]: """ Formats a list of float values to a specific precision. :param array: A list of float values to format. :param precision: The number of decimal places to use. :return: A list of strings containing the formatted floats. ...
33,376
def counts_card() -> html.Div: """Return the div that contains the overall count of patients/studies/images.""" return html.Div( className="row", children=[ html.Div( className="four columns", children=[ html.Div( ...
33,377
def validate_est(est: EstData, include_elster_responses: bool = False): """ Data for a Est is validated using ERiC. If the validation is successful then this should return a 200 HTTP response with {'success': bool, 'est': est}. Otherwise this should return a 400 response if the validation failed with {‘...
33,378
async def list_solver_releases( solver_key: SolverKeyId, user_id: int = Depends(get_current_user_id), catalog_client: CatalogApi = Depends(get_api_client(CatalogApi)), url_for: Callable = Depends(get_reverse_url_mapper), ): """ Lists all releases of a given solver """ releases: List[Solver] = aw...
33,379
def read_silicon_data(tool, target: Target): """ Reads silicon data from device :param tool: Programming/debugging tool used for communication :param target: The target object. :return: Device response """ logger.debug('Read silicon data') tool.reset(ResetType.HW) passed, response = ...
33,380
def offset_perimeter(geometry, offset, side='left', plot_offset=False): """Offsets the perimeter of a geometry of a :class:`~sectionproperties.pre.sections.Geometry` object by a certain distance. Note that the perimeter facet list must be entered in a consecutive order. :param geometry: Cross-section g...
33,381
def WalterComposition(F,P): """ Calculates the melt composition generated as a function of F and P, using the parameterisation of Duncan et al. (2017). Parameters ----- F: float Melt fraction P: float Pressure in GPa Returns ----- MeltComposition: series ...
33,382
def fetch_study_metadata( data_dir: Path, version: int = 7, verbose: int = 1 ) -> pd.DataFrame: """ Download if needed the `metadata.tsv.gz` file from Neurosynth and load it into a pandas DataFrame. The metadata table contains the metadata for each study. Each study (ID) is stored on its own li...
33,383
def proveFormula(formula: str) -> Union[int, str]: """ Implements proveFormula according to grader.py >>> proveFormula('p') 1 >>> proveFormula('(NOT (NOT (NOT (NOT not)) )\t)') 1 >>> proveFormula('(NOT (NOT (NOT (NOT not)) )') 'E' >>> proveFormula('(IF p p)') 'T' >>> proveF...
33,384
def read_config(): """Read configuration file.""" config_file = os.getenv('CONFIG_FILE_PATH') if not config_file: config_file = os.path.join( os.path.dirname(os.path.realpath(__file__)), 'config.json') with open(config_file) as file: return json.load(file)
33,385
def add_and_check(database, table_name, episode, expected=1): """ utility to add episode and ensure there is a single episode for that podcast """ assert database.add_new_episode_data(table_name, episode) eps = database.find_episodes_to_download(table_name) assert len(eps) == expected eps = data...
33,386
def sendSingleCommand(server, user, password, command): """Wrapper function to open a connection and execute a single command. Args: server (str): The IP address of the server to connect to. username (str): The username to be used in the connection. password (str): The password asso...
33,387
def test_piecewise_fermidirac(precision): """Creates a Chebyshev approximation of the Fermi-Dirac distribution within the interval (-3, 3), and tests its accuracy for scalars, matrices, and distributed matrices. """ mu = 0.0 beta = 10.0 def f(x): return 1 / (np.exp(beta * (x - mu)) + 1) is_vectori...
33,388
def load_img(flist): """ Loads images in a list of arrays Args : list of files Returns list of all the ndimage arrays """ rgb_imgs = [] for i in flist: rgb_imgs.append(cv2.imread(i, -1)) # flag <0 to return img as is print "\t> Batch import of N frames\t", len(rgb_imgs) size_var = ...
33,389
def makesimpleheader(headerin,naxis=2,radesys=None,equinox=None,pywcsdirect=False): """ Function to make a new 'simple header' from the WCS information in the input header. Parameters ---------- headerin : astropy.io.fits.header Header object naxis : int Specifies how man...
33,390
def _callcatch(ui, func): """like scmutil.callcatch but handles more high-level exceptions about config parsing and commands. besides, use handlecommandexception to handle uncaught exceptions. """ detailed_exit_code = -1 try: return scmutil.callcatch(ui, func) except error.AmbiguousC...
33,391
def _determ_estim_update(new_bit, counts): """Beliefs only a sequence of all ones or zeros. """ new_counts = counts[:] new_counts[new_bit] += 1 if new_counts[0] > 0 and new_counts[1] > 0: return LOG_ZERO log_p_new = _determ_log_p(new_counts) log_p_old = _determ_log_p(counts) ret...
33,392
def get_projects(config): """Find all XNAT projects and the list of scan sites uploaded to each one. Args: config (:obj:`datman.config.config`): The config for a study Returns: dict: A map of XNAT project names to the URL(s) of the server holding that project. """ proje...
33,393
def load_jsonrpc_method(name): """Load a method based on the file naming conventions for the JSON-RPC. """ base_path = (repo_root() / "doc" / "schemas").resolve() req_file = base_path / f"{name.lower()}.request.json" resp_file = base_path / f"{name.lower()}.schema.json" request = CompositeField....
33,394
def download_missing_namespace(network_id: int, namespace: str): """Output a namespace built from the missing names in the given namespace. --- tags: - network parameters: - name: network_id in: path description: The database network identifier required: true ...
33,395
def client_decrypt_hello_reply(ciphertext, iv1, key1): """ Decrypt the server's reply using the IV and key we sent to it. Returns iv2, key2, salt2 (8 bytes), and the original salt1. The pair iv2/key2 are to be used in future communications. Salt1 is returned to help confirm the integrity of the oper...
33,396
def load_labeled_data(filename): """ Loads data from a csv, where the last column is the label of the data in that row :param filename: name of the file to load :return: data frames and labels in separate arrays """ dataframe = pandas.read_csv(filename, header=None) dataset = dataframe.values ...
33,397
def get_logger(name, level='debug', log_file='log.txt'): """ Retrieve the logger for SWIFLow with coloredlogs installed in the right format """ # Setup logging log_level = level.upper() level = logging.getLevelName(log_level) # Add a custom format for logging fmt = "%(levelname)s: %...
33,398
def filesystem_move( source_path, source_type, destination_path, destination_type, backup_ending, ): """ Moves a file from the source to the destination. Arguments --------- source_path: path to the source source_type: Type of the source (a direct...
33,399