content
stringlengths
22
815k
id
int64
0
4.91M
def entry_point(): """dbf_light command line utilities."""
16,200
def apply_flags_all_variables(station, all_variables, flag_col, logfile, test_name, plots = False, diagnostics = False): """ Apply these flags to all variables :param object station: the station object to be processed :param list all_variables: the variables where the flags are to be applied :param...
16,201
def exportSDFVisual(visualobj, linkobj, visualdata, indentation, modelname): """Simple wrapper for visual data of links. The visual object is required to determine the position (pose) of the object. If relative poses are used the data found in visualdata (key pose) is used. Otherwise the pose of the...
16,202
def register_module(): """Callback for module registration. Sets up URL routes.""" global custom_module # pylint: disable=global-statement permissions = [ roles.Permission(EDIT_STUDENT_GROUPS_PERMISSION, messages.EDIT_STUDENT_GROUPS_PERMISSION_DESCRIPTION), ] ...
16,203
def build_texttable(events): """ value['date'], value["target"], value['module_name'], value['scan_unique_id'], value['options'], value['event'] build a text table with generated event related to the scan :param events: all events :return: ...
16,204
def for_all_regions(get_client_func, catalog_entry, action_func, parsed_args): """ Run the provided function on all the available regions. Available regions are determined based on the user service catalog entries. """ result = [] cache_key = 'todo' cache_item = CACHE.get(cache_key, None...
16,205
def copy_file_from_worker(request, context): """Copy file from worker to host.""" path = request.path if not os.path.isfile(path): context.set_trailing_metadata([('result', 'invalid-path')]) return with open(path) as f: for chunk in file_utils.file_chunk_generator(f): yield chunk context.se...
16,206
def migrate(source_config,target_config,migration_config): """ Migrate data from the source database to the target database. The target database and schema must already exist. Args: source_config (dict): Settings for source database. target_config (dict): Settings for target database. ...
16,207
def KL_distance(image1, image2): """ Given two images, calculate the KL divergence between the two 2d array is not supported, so we have to flatten the array and compare each pixel in the image1 to the corresponding pixel in the image2. """ return scipy.stats.entropy(image1.ravel(), image2.ravel())
16,208
def stop_all_bots(): """ This function address RestAPI call to stop polling for all bots which have ever started polling. :return: """ bots_stopped = procedures.stop_all() # Stop all bots. botapi_logger.info('Successfully stopped {count} bots for polling in ' 's...
16,209
def load_word_embedding_dict(embedding, embedding_path, normalize_digits=True): """ load word embeddings from file :param embedding: :param embedding_path: :return: embedding dict, embedding dimention, caseless """ print "loading embedding: %s from %s" % (embedding, embedding_path) if em...
16,210
def fibonacci(n: int) -> int: """Returns nth fib number, fib_0 = 0, fib_1 = 1, ...""" print(sys.platform) return nfibonacci(n + 1)[-1]
16,211
def random_exponential(shape=(40,60), a0=100, dtype=float) : """Returns numpy array of requested shape and type filled with exponential distribution for width a0. """ a = a0*np.random.standard_exponential(size=shape) return a.astype(dtype)
16,212
def get_mpi_components_from_files(fileList, threads=False): """ Given a list of files to read input data from, gets a percentage of time spent in MPI, and a breakdown of that time in MPI """ percentDict = dict() timeDict = dict() for filename in fileList: filename = filename.str...
16,213
def get_character_url(name): """Gets a character's tibia.com URL""" return url_character + urllib.parse.quote(name.encode('iso-8859-1'))
16,214
def setup_temp_data(): """ resource for memory mapped files :return: """ temp_folder = os.getcwd()+'/temp' if not os.path.isdir(temp_folder): os.mkdir(temp_folder) print("\nsetting up temp folder") # setup files, provide memmap type img = np.random.random((2048, 2048)) ...
16,215
def parse_input(lines): """Parse the input document, which contains validity rules for the various ticket fields, a representation of my ticket, and representations of a number of other observed tickets. Return a tuple of (rules, ticket, nearby_tickets) """ section = parse_sections(lines) ru...
16,216
def _call(retaddr=None): """Push a new stack frame with retaddr in cell 0 of it""" ##debug("call, will return to addr:%s" % str(retaddr)) stack.append([retaddr])
16,217
def main(): """Main function""" y = [1, 0, 1, 1, 0, 1, 1, 1, 0, 0, 1, 0, 1, 0, 1, 0, 1, 1, 1, 0] pred = [1, 0, 1, 1, 0, 1, 0, 1, 0, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1] print_confusion_matrix(y, pred) mx_ = get_confusion_matrix(y, pred) print("\n") print("Mcc: ", get_MCC(mx_)) pr...
16,218
def _cnv_prioritize(data): """Perform confidence interval based prioritization for CNVs. """ supported = {"cnvkit": {"inputs": ["call_file", "segmetrics"], "fn": _cnvkit_prioritize}} pcall = None priority_files = None for call in data.get("sv", []): if call["variantcaller"] in supported:...
16,219
def add_meta_files(tarfile, meta_files_dir): """Adds the meta files to the specified tarfile. Args: tarfile: The tarfile object where the files needs to be added. meta_files_dir: The directory containing the meta files. """ tarfile.add(os.path.join(meta_files_dir, 'TIMESTAMP'), arcname=...
16,220
def maximum( left_node: NodeInput, right_node: NodeInput, auto_broadcast: str = "NUMPY", name: Optional[str] = None, ) -> Node: """Return node which applies the maximum operation to input nodes elementwise.""" return _get_node_factory_opset1().create( "Maximum", [left_node, right_node], ...
16,221
def write_csv(file_name, upload_name, is_local, header, body): """ Write a CSV to the relevant location. Args: file_name: pathless file name upload_name: file name to be used as S3 key is_local: True if in local development, False otherwise header: value to w...
16,222
def create_template_error(): """ Создает заготовку для генерации ошибок """ return {'response': False}
16,223
def set_ball(x_dir=(random.randrange(0,2) == 0)): """ Resets ball to centre of screen """ global ball_vel, ball_pos ball_vel = [random.randrange(2,4), random.randrange(1,3)] if random.randrange(0,2) == 0: ball_vel[y] *= -1 if x_dir: ball_vel[x] *= -1 ball_pos = [win_width//2, wi...
16,224
def download_and_extract_index(storage_bucket: Any, extract_destination_path: str) -> Tuple[str, Any, int]: """Downloads and extracts index zip from cloud storage. Args: storage_bucket (google.cloud.storage.bucket.Bucket): google storage bucket where index.zip is stored. extract_destination_pat...
16,225
def MenuPersonnalise(contenu): #py:MakeCustomMenu """ À l'intention des éducateurs. Permet de créer des menus de monde personalisés. Voir la documentation pour plus de détails.""" RUR._MakeCustomMenu_(contenu)
16,226
def e_qest(model, m): """ Calculation of photocounting statistics estimation from photon-number statistics estimation Parameters ---------- model : InvPBaseModel m : int Photocount number. """ return quicksum(model.T[m, n] * model.PEST[n] for n in model....
16,227
def load_input(fname): """Read in the data, return as a list.""" data = [""] with open(fname, "r") as f: for line in f.readlines(): if line.strip("\n"): data[-1] += line.strip("\n") + " " else: data[-1] = data[-1].strip(" ") dat...
16,228
def parse_repo_layout_from_json(file_): """Parse the repo layout from a JSON file. Args: file_ (File): The source file. Returns: RepoLayout Raises: InvalidConfigFileError: The configuration file is invalid. """ def encode_dict(data): new_data = {} for ...
16,229
def SizeArray(input_matrix): """ Return the size of an array """ nrows=input_matrix.shape[0] ncolumns=input_matrix.shape[1] return nrows,ncolumns
16,230
def show_fun_elem_state_machine(fun_elem_str, xml_state_list, xml_transition_list, xml_fun_elem_list): """Creates lists with desired objects for <functional_element> state, send them to plantuml_adapter.py then returns url_diagram""" new_fun_elem_list = set() main_fun_el...
16,231
def get_bank_account_rows(*args, **kwargs): """ 获取列表 :param args: :param kwargs: :return: """ return db_instance.get_rows(BankAccount, *args, **kwargs)
16,232
def load_class(class_name, module_name): """Dynamically load a class from strings or raise a helpful error.""" # TODO remove this nasty python 2 hack try: ModuleNotFoundError except NameError: ModuleNotFoundError = ImportError try: loaded_module = importlib.import_module(mo...
16,233
def pybo_mod(tokens, tag_codes=[]): """extract text/pos tuples from Token objects""" txt_tags = [] for token in tokens: tags = [] tags.append(token.text) # Select and order the tags for tag_code in tag_codes: tags.append(get_tag(token, tag_code)) txt_tags....
16,234
def test_string_value(): """ Test string values. """ lib.backup_and_restore( lambda context: put_values(lib.SET, "key", STRING_VALUES), None, lambda context: check_values(lib.SET, "key", STRING_VALUES) )
16,235
def acf( da: xr.DataArray, *, lag: int = 1, group: str | Grouper = "time.season" ) -> xr.DataArray: """Autocorrelation function. Autocorrelation with a lag over a time resolution and averaged over all years. Parameters ---------- da : xr.DataArray Variable on which to calculate the diagn...
16,236
def username(UID: str) -> str: """ Get a users username from their user ID. >>> username("zx7gd1yx") '1' >>> username("7j477kvj") 'AnInternetTroll' >>> username("Sesame Street") Traceback (most recent call last): ... utils.UserError: User with uid 'Sesame Street' not found. """ R: dict = requests.get(f...
16,237
def handle_exceptions(func): """Exception handler helper function.""" import logging logging.basicConfig(level = logging.INFO) def wrapper_func(*args, **kwargs): try: return func(*args, **kwargs) except Exception as e: logging.error(f'{func.__name__} raised an err...
16,238
def wflow_eqv(eqv_folder="eqv", jobname="NbTiVZr", latname="bcc", queue_type="pbs", emtopath="./", sws0=3.0, sws_percent=10.0, sws_step=11, concs=[[0.25, 0.25, 0.25, 0.25]], species=[['Nb','Ti','V','Zr']]): """ Workflow for equialium volume Parameter eqv_folder: str The folder n...
16,239
def apply_hamming_window(image): """Cross correlate after applying hamming window to compensate side effects""" window_h = np.hamming(image.shape[0]) window_v = np.hamming(image.shape[1]) image = np.multiply(image.T, window_h).T return np.multiply(image, window_v)
16,240
def calc_ewald_sum(dielectric_tensor: np.ndarray, real_lattice_set: np.ndarray, reciprocal_lattice_set: np.ndarray, mod_ewald_param: float, root_det_epsilon: float, volume: float, ) -> Tuple[float, float]: ...
16,241
def proximal_descent( x0, grad, prox, step_size, momentum='fista', restarting=None, max_iter=100, early_stopping=True, eps=np.finfo(np.float64).eps, obj=None, benchmark=False): """ Proximal descent algorithm. Parameters ---------- x0 : array, shape (n_length, ), init...
16,242
def reducer(): """ Pairs reducer function Reads pairs of words separated by a space and a count and calculates P """ # Empty dict for our output n = dict() sigma_n = dict() # Precompiled regex to match our input parse = re.compile('(\w+)\s+(\w+):\s+(\d+)') # Read STDIN and get...
16,243
def sign_tx(path, multisig_address, redeemscript, utxo_file, output_file, testnet=False): """ Sign a spend of a bitcoin 2-of-3 P2SH-multisig address using a Trezor One Hardware Wallet Args: path: BIP32 path of key with whic...
16,244
def wrap_atari_dqn(env): """ wrap the environment in atari wrappers for DQN :param env: (Gym Environment) the environment :return: (Gym Environment) the wrapped environment """ from stable_baselines_custom.common.atari_wrappers import wrap_deepmind return wrap_deepmind(env, frame_stack=True...
16,245
def get_Theta_CR_i_d_t(pv_setup, Theta_A_d_t, I_s_i_d_t): """加重平均太陽電池モジュール温度 (6) Args: pv_setup(str): 太陽電池アレイ設置方式 Theta_A_d_t(ndarray): 日付dの時刻tにおける外気温度(℃) I_s_i_d_t(ndarray): 日付dの時刻tにおける太陽電池アレイiの設置面の単位面積当たりの日射量(W/m2) Returns: ndarray: 日付dの時刻tにおける太陽電池アレイiの加重平均太陽電池モジュール温度 """ ...
16,246
def or_equality(input_1: Variable, input_2: Variable, output: Variable) -> Set[Clause]: """ Encode an OR-Gate into a CNF. :param input_1: variable representing the first input of the OR-Gate :param input_2: variable representing the second input of the OR-Gate :param output: variable represen...
16,247
def keyPosition_to_keyIndex(key_position: int, key: int) -> int: """ キーポジションからどのキーのノーツなのかを変換します 引数 ---- key_position : int -> キーポジション key : int -> 全体のキー数、4Kなら4と入力 戻り値 ------ int -> キーインデックス、指定したキーの0~キー-1の間の数 """ return math.floor(key_position * key / 512)
16,248
def main(args): """ Convert a TSV file with the following columns: * icd11 - the URI of the ICD 11 resource * icdrubric - the name associated with the rubric * expression - a compositional grammar expression that fully or partially defines the ICD 11 resource * maptype - "A" means the definition bel...
16,249
def rebuild_index(): """ Rebuild the K-nearest neighbors index based on 50000 of the most active users (ignoring the top 500 most active). """ pipe = get_pipeline() usernames = pipe.zrevrange(format_key("user"), 500, 50500).execute()[0] for user in usernames: get_vector(user, pipe=...
16,250
def load_file_recipes(fh, enabled_only=False, expensive=False, logger=logger): """ Load all the recipes from a given file handle. :param enabled_only: Set True to limit to only enabled recipes. :param expensive: Set True to use 'expensive' configurations. :return: dict(name -> {recipe}) """ ...
16,251
def assert_euler_xyz_equal(e_xyz1, e_xyz2, *args, **kwargs): """Raise an assertion if two xyz Euler angles are not approximately equal. Note that Euler angles are only unique if we limit them to the intervals [-pi, pi], [-pi/2, pi/2], and [-pi, pi] respectively. See numpy.testing.assert_array_almost_eq...
16,252
def load_model_data(m, d, data_portal, scenario_directory, subproblem, stage): """ :param m: :param data_portal: :param scenario_directory: :param subproblem: :param stage: :return: """ # TODO: once we align param names and column names, we will have conflict # because binary...
16,253
def send_record(agg_record): """Send the input aggregated record to Kinesis via the PutRecord API. Args: agg_record - The aggregated record to send to Kinesis. (AggRecord)""" global kinesis_client, stream_name if agg_record is None: return partition_key, explicit_...
16,254
def patch(url, controller): """Shortcut for Patch HTTP class. Arguments: url {string} -- The url you want to use for the route controller {string|object} -- This can be a string controller or a normal object controller Returns: masonite.routes.Patch -- The Masonite Patch class. ...
16,255
def get_user(message: discord.Message, username: str): """ Get member by discord username or osu username. """ member = utils.find_member(guild=message.guild, name=username) if not member: for key, value in osu_tracking.items(): if value["new"]["username"].lower() == username.lower(): ...
16,256
def ensure_dirs(filename): """Make sure the directories exist for `filename`.""" dirname = os.path.dirname(filename) if dirname and not os.path.exists(dirname): os.makedirs(dirname)
16,257
def resaturate_color(color, amount=0.5): """ Saturates the given color by setting saturation to the given amount. Input can be matplotlib color string, hex string, or RGB tuple. """ if not isinstance(color, np.ndarray) and color in matplotlib.colors.cnames: color = matplotlib.colors.cnames[...
16,258
def create_reach_segment(upstream_point, downstream_point, polyline, identifier="HA", junctionID=0, isEnd=False): """Returns a polyline based on two bounding vertices found on the line. """ part = polyline.getPart (0) total_length = polyline.length lineArray = arcpy.Array (...
16,259
def sample_recipe(user, **params): """ Helper function for creating recipes """ """ for not writing every single time this fields """ defaults = { 'title': 'Sample recipe', 'time_minutes': 10, 'price': 5.00 } """ Override any field of the defaults dictionary. Updati...
16,260
def _unary_geo(op, left, *args, **kwargs): # type: (str, np.array[geoms]) -> np.array[geoms] """Unary operation that returns new geometries""" # ensure 1D output, see note above data = np.empty(len(left), dtype=object) data[:] = [getattr(geom, op, None) for geom in left] return data
16,261
def map_func(h, configs, args): """Polygons command line in parallel. """ if args.verbose: cmd = "python {} -i {}/threshold{}.tif -o {}/threshold{}.shp -v".format( configs["path"]["polygons"], configs["path"]["output"], h, configs["path"]["output"], h ) print cmd else: cmd = "python {} -i {}/...
16,262
def _runopenssl(pem, *args): """ Run the command line openssl tool with the given arguments and write the given PEM to its stdin. Not safe for quotes. """ if os.name == 'posix': command = "openssl " + " ".join(["'%s'" % (arg.replace("'", "'\\''"),) for arg in args]) else: comman...
16,263
def check_health(request: HttpRequest) -> bool: """Check app health.""" return True
16,264
def test_timeout_not_set_in_config(): """ Creating a CkanAuthTktCookiePlugin instance without setting timeout in config sets correct values in CkanAuthTktCookiePlugin instance. """ plugin = make_plugin(secret="sosecret") assert plugin.timeout is None assert plugin.reissue_time is None
16,265
def return_galo_tarsilo(message): """Middle function for returning "gaucho" vídeo. Parameters ---------- message : telebot.types.Message The message object. Returns ------- msg : str User/Chat alert list addition/removal. """ return 'https://www.youtube.com/watch?v...
16,266
def test_exception(client, recorder): """ Test handling an exception :param test_client: AioHttp test client fixture :param loop: Eventloop fixture :param recorder: X-Ray recorder fixture """ exc = None try: client.get("/exception") except Exception as e: exc = e ...
16,267
def register_scheduler(name, scheduler): """ Registers a new scheduler. Attempting to register a scheduler with a name that is already taken will raise a ``SystemSetupError``. :param name: The name under which to register the scheduler. :param scheduler: Either a unary function ``float`` -> ``float...
16,268
def preimage_func(f, x): """Pre-image a funcation at a set of input points. Parameters ---------- f : typing.Callable The function we would like to pre-image. The output type must be hashable. x : typing.Iterable Input points we would like to evaluate `f`. `x` must be of a type acce...
16,269
def get_spec_id(mat_quality, mat_faction=None): """ Get the material_spec id corresponding to the material quality and faction. Args: mat_quality (str): A material quality like Basic, Fine, Choice etc... mat_faction (str): A material faction like Matis, Zoraï etc... Returns: in...
16,270
def pytest_configure(config): """Add pytest new configurations.""" config.addinivalue_line('markers', 'web: validate web link') config.addinivalue_line('markers', 'rapidtest: rapid test')
16,271
def print_raw_data(raw_data, start_index=0, limit=200, flavor='fei4b', index_offset=0, select=None, tdc_trig_dist=False, trigger_data_mode=0): """Printing FEI4 raw data array for debugging. """ if not select: select = ['DH', 'TW', "AR", "VR", "SR", "DR", 'TDC', 'UNKNOWN FE WORD', 'UNKNOWN WORD'] ...
16,272
def test_fit_raise_error(classifier): """Test raising an error on the wrong classifier type.""" with pytest.raises( TypeError, match='`ClassifierBettor` requires a classifier. ' f'Instead {type(classifier)} is given.', ): ClassifierBettor(classifier).fit(X, Y)
16,273
def test_md034_good_with_leading_character(): """ Test to make sure this rule does not trigger with a document that contains http urls with non-whitespace directly before it. """ # Arrange scanner = MarkdownScanner() supplied_arguments = [ "scan", "test/resources/rules/md034...
16,274
def load_tree(tree,fmt=None): """ Load a tree into an ete3 tree data structure. tree: some sort of tree. can be an ete3.Tree (returns self), a dendropy Tree (converts to newick and drops root), a newick file or a newick string. fmt: format for reading tree from newick. 0-9 or 100. ...
16,275
def load_extract(context, extract: Dict) -> str: """ Upload extract to Google Cloud Storage. Return GCS file path of uploaded file. """ return context.resources.data_lake.upload_df( folder_name="nwea_map", file_name=extract["filename"], df=extract["value"] )
16,276
def _make_default_colormap(): """Return the default colormap, with custom first colors.""" colormap = np.array(cc.glasbey_bw_minc_20_minl_30) # Reorder first colors. colormap[[0, 1, 2, 3, 4, 5]] = colormap[[3, 0, 4, 5, 2, 1]] # Replace first two colors. colormap[0] = [0.03137, 0.5725, 0.9882] ...
16,277
def poly_to_box(poly): """Convert a polygon into an array of tight bounding box.""" box = np.zeros(4, dtype=np.float32) box[0] = min(poly[:, 0]) box[2] = max(poly[:, 0]) box[1] = min(poly[:, 1]) box[3] = max(poly[:, 1]) return box
16,278
def default_collate(batch): """Puts each data field into a tensor with outer dimension batch size""" error_msg = "batch must contain tensors, numbers, dicts or lists; found {}" elem_type = type(batch[0]) if isinstance(batch[0], torch.Tensor): return torch.stack(batch, 0) elif ( elem...
16,279
def updatestatus(requestdata, authinfo, acldata, supportchan, session): """Update the /Status page of a user.""" if requestdata[2] in acldata['wikis']: wikiurl = str('https://' + acldata['wikis'][requestdata[2]]['url'] + '/w/api.php') sulgroup = acldata['wikis'][requestdata[2]]['sulgroup'] e...
16,280
def sortByTimeStamps(paths): """Sorts the given list of file paths by their time-stamp :paths: The file paths to sort by time-stamp :returns: A sorted list of file paths """ sortedPaths = [] timeStamps = [] # Extract the YYYYMMDD & HHMMSS timestamps from the file paths for p in paths:...
16,281
def get_xml_nk_bands(xml_tree): """ Function to specifically get kpoint (cartesian) coordinates and corresponding eigenvalues (in Hartree) """ k_points_car = [] k_eigenvalues = [] k_occupations = [] for ks_energies in xml_tree.iter(tag='ks_energies'): k_points_car.append( get_x...
16,282
def enumerate(server, directory_list, filenames): """ Enumerate directories and files on the web server. """ print('\n[*] Enumerating resources.') to_search = [server] directories = [] resources = [] print('[*] Recursively searching for directories.') while len(to_search) != 0: ...
16,283
def deep_equals(x, y): """Test two objects for equality in value. Correct if x/y are one of the following valid types: types compatible with != comparison pd.Series, pd.DataFrame, np.ndarray lists, tuples, or dicts of a valid type (recursive) Important note: this function w...
16,284
def get_local_log(date, which="completed", safeout=False): """ """ filein = get_log_filepath(date, which=which) if not os.path.isfile(filein): if safeout: return None raise IOError(f"No {which}_log locally stored for {date}. see download_log()") return pandas.read_csv(fi...
16,285
def get_asan_options(redzone_size, malloc_context_size, quarantine_size_mb, bot_platform, leaks): """Generates default ASAN options.""" asan_options = {} # Default options needed for all cases. asan_options['alloc_dealloc_mismatch'] = 0 asan_options['print_scariness'] = 1 asan_options[...
16,286
def get_onelinepred_results(pred_file, thred=0.1): """"from pred_file parse pred_results Args: # TODO save format of pred_file still unknown pred_file (str): pred_file path thred: pred_box's score less than it could be ignored Return: pred_dict (dict(list)) : output predict...
16,287
def permutations(**kwargs): """Generate a CSV with each permutation of columns and possible values. The probabilities are not considered. """ cols_template, gen_rows = handle_common_cmdline(kwargs) col_opts = prepare_col_opts(cols_template) rows = [] gen_permutations(col_opts, cols=list(col_opts.ke...
16,288
def validate_parent_instance(parent: Optional[Any]) -> None: """ Validate specified parent is `ChildInterface` instance. Parameters ---------- parent : * Any parent instance or None. Raises ------ ValueError If specified parent is not None and not `ChildInte...
16,289
def _is_valid_img_uri(uri: str) -> bool: """ Returns true if a string is a valid uri that can be saved in the database. """ regex = "data:image/jpeg;base64*." return not uri or re.match(regex, uri)
16,290
def insert_global_vars(config): """ replace global variable placeholders with respective values """ for key, value in config.items(): if type(value) != dict and value in vars(globals): config[key] = getattr(globals, value)
16,291
def update_config(a, b, mode="default"): """Update the configuration a with b.""" if not b: return a from_version = get_config_version(a) to_version = get_config_version(b) if from_version == 1 and to_version == 2: # When updating the configuration to a newer version, we clear all u...
16,292
def disk_partitions(disk_ntuple, all=False): """Return all mountd partitions as a named tuple. If all == False return physical partitions only. """ phydevs = [] if os.path.exists('/proc/filesystems'): my_file = open('/proc/filesystems', 'r') for line in my_file: if not li...
16,293
def create_app(config_name='DevelopmentConfig'): """Create the Flask application from a given config object type. Args: config_name (string): Config instance name. Returns: Flask Application with config instance scope. """ app = Flask(__name__) {{cookiecutter.package_name | up...
16,294
def label_accuracy_score(hist): """Returns accuracy score evaluation result. - overall accuracy - mean accuracy - mean IU - fwavacc """ with np.errstate(divide='ignore', invalid='ignore'): iu = np.diag(hist) / ( hist.sum(axis=1) + hist.sum(axis=0) - np.diag(hist) ...
16,295
def get_page_title(title: str): """ Возвращает заголовок, отображаемый на вкладках """ return f'{title} | NeuraHS'
16,296
def scan_build(registry, xml_parent, data): """yaml: scan-build This plugin allows you configure a build step that will execute the Clang scan-build static analysis tool against an XCode project. The scan-build report has to be generated in the directory ``${WORKSPACE}/clangScanBuildReports`` for t...
16,297
def make_pointer_union_printer(val): """Factory for an llvm::PointerUnion printer.""" pointer, value = get_pointer_int_pair(val['Val']) if not pointer or not value: return None pointer_type = val.type.template_argument(int(value)) string = 'llvm::PointerUnion containing %s' % pointer_type return make_pr...
16,298
def test_default_quality_2_down(): """ Test that quality goes down by 2 when sell_in date has gotten to 0 GIVEN: GildedRose with one Item of type default WHEN: call update_quality method THEN: quality should be two less """ quality = 10 sell_in = 0 name = 'default' items = [Item...
16,299