content
stringlengths
22
815k
id
int64
0
4.91M
def plot_2_3d(data2,best_array,n,rates,noises,save): """3d version of plots 2 based on Minh's code Parameters ------ data2,best_array : array_like `data2` and `best_array` defined above n,rates,noises: list `n` `rates` `list` lists of each parame...
2,100
def Float(request): """ A simple form with a single integer field """ schema = schemaish.Structure() schema.add('myFloatField', schemaish.Float()) form = formish.Form(schema, 'form') return form
2,101
def AddMatcher(parser, required=True): """Adds the matcher arguments to the argparse.""" matcher = parser.add_group( mutex=True, required=required, help='Security policy rule matcher.') matcher.add_argument( '--src-ip-ranges', type=arg_parsers.ArgList(), metavar='SRC_IP_RANGE', help=...
2,102
def pca(X): """ Returns the eigenvectors U, the eigenvalues (on diagonal) in S. Args: X: array(# of training examples, n) Returns: U: array(n, n) S: array(n, n) """ # Get some useful values m, n, _, _ = X.shape # Init U and S. U = np.zeros(n) S = np.z...
2,103
def read_py_version(script_name, search_path): """Read the version of a script from a python file""" file, pathname, desc = imp.find_module(script_name, [search_path]) try: new_module = imp.load_module(script_name, file, pathname, desc) if hasattr(new_module.SCRIPT, "version"): r...
2,104
def post_check_variable(team_id, source_id, check_id): """ .. :quickref: POST; Lorem ipsum.""" if not TeamPermission.is_manager_or_editor(team_id): abort(403) payload = get_payload() payload.update({"team_id": team_id, "source_id": source_id, "check_id": check_id}) variable = VariableC...
2,105
def diff_re(a, b, fromfile='', tofile='', fromfiledate='', tofiledate='', n=3, lineterm='\n'): """ A simple "diff" of two sets of lines when the expected lines are regular expressions. This is a really dumb thing that just compares each line in turn, so it doesn't look for chunks of mat...
2,106
def storeAgent(sess, agentObj): """ INPUT : session object OUTPUT : Updated agent Onject DESCRIPTION : Updates the agent object in that session """ currAgents = getCurrGen(sess) lock(sess) try: if(sess.mode == 'SAFE'): tpfp = open(GA_UTIL_DIR+"/utilFi...
2,107
def info(device): """ Get filesystem geometry information. CLI Example: .. code-block:: bash salt '*' xfs.info /dev/sda1 """ out = __salt__["cmd.run_all"]("xfs_info {}".format(device)) if out.get("stderr"): raise CommandExecutionError(out["stderr"].replace("xfs_info:", "")...
2,108
def serialize_framework_build_config(dict_: Union[Dict[str, str], str]) -> Tuple[Any, ...]: """Serialize a dict to a hashable tuple. Parameters ---------- dict_: Dict[str, str] Returns ------- hashable_tuple: Tuple[Any, ...] A hashable tuple. """ if isinstance(dict_, dict):...
2,109
def _check_columns(data: pd.DataFrame, features: list) -> pd.DataFrame: """ Given a dataframe and a list of expected features, print missing columns and return new dataframe with only valid features Parameters ----------- data: Pandas.DataFrame DataFrame for checking...
2,110
def get_confidence(imgfilename): """ 1003_c60.jpg -> c6 """ if not imgfilename: return '' return 'c' + imgfilename.split('/')[-1][0:1]
2,111
def test_connection_proxy_api_wrong_certs(app): """Connecting to the proxy api fails without correct certs""" with pytest.raises(SSLError): kwargs = {'verify': False} r = yield async_requests.get(app.proxy.api_url, **kwargs) r.raise_for_status()
2,112
def get_connection(hostname: str, port: int, username: str, password: str): """ DBへのコネクションを取得します。 Returns: Connection: コネクション """ return pymysql.connect( host=hostname, port=port, user=username, passwo...
2,113
def test_generate_init_open_alchemy(): """ GIVEN name and version WHEN generate_init_open_alchemy is called with the name and version THEN the __init__.py file contents with the name and version are returned. """ returned_contents = build.generate_init_open_alchemy() expected_contents = """...
2,114
def get_alleles_existing_alleleinterpretation( session, allele_filter, user=None, page=None, per_page=None ): """ Returns allele_ids that has connected AlleleInterpretations, given allele_filter from argument. Supports pagination. """ # Apply filter using Allele table as base allele_id...
2,115
def _patched_copy_file( src_file, dest_file, hide_listing=True, preserve_mode=True ): """Copy ``src_file`` to ``dest_file`` ensuring parent directory exists. By default, message like `creating directory /path/to/package` and `copying directory /src/path/to/package -> path/to/package` are displayed ...
2,116
def _get_session(db_uri, use_batch_mode=True, echo=False): """Helper to get an SQLAlchemy DB session""" # `use_batch_mode` is experimental currently, but needed for `executemany` #engine = create_engine(db_uri, use_batch_mode=use_batch_mode, echo=echo) engine = create_engine(db_uri, echo=echo) Base....
2,117
def has_extension(experiment: Experiment, name: str) -> bool: """ Check if an extension is declared in this experiment. """ return get_extension(experiment, name) is not None
2,118
def test_get_plaid_accounts(lunch_money_obj: LunchMoney): """ Get Plaid Account and Assert it's a Plaid Account """ plaid_accounts = lunch_money_obj.get_plaid_accounts() assert len(plaid_accounts) >= 1 for plaid_account in plaid_accounts: assert isinstance(plaid_account, PlaidAccountObje...
2,119
def machine_is_valid(cloud_machine, accounts): """ As the criteria for "what makes a glance image an atmosphere ProviderMachine" changes, we can use this function to hook out to external plugins, etc. Filters out: - ChromoSnapShot, eri-, eki- - Private images not shared with atmosphere accou...
2,120
def remove_dups(list, key): """Returns a new list without duplicates. Given two elements e1, e2 from list, e1 is considered to be a duplicate of e2 if key(e1) == key(e2). Args: list: the list to read from. key: a function that receives an element from list and returns its key. Yields: unique el...
2,121
def ReadPickledNetworkxGraphs() -> Iterable[Tuple[str, nx.MultiDiGraph]]: """Read the pickled networkx graphs.""" with NETWORKX_GRAPHS_ARCHIVE as pickled_dir: for path in pickled_dir.iterdir(): with open(path, "rb") as f: yield path.name, pickle.load(f)
2,122
def min_max_median(lst): """ a function that takes a simple list of numbers lst as a parameter and returns a list with the min, max, and the median of lst. """ s = sorted(lst) n = len(s) return [ s[0], s[-1], s[n//2] if n % 2 == 1 else (s[n//2 - 1] + s[n//2]) / 2]
2,123
def Tree(tree=tree): """the main recursive fonction that is responsible of reading the tree and deciding witch node is next This fonction takes the cuurent position in the tree (current node), do the processing and end up with a recursive call with the next node Args: tree (obj): a node...
2,124
def _CreateRJavaSourceFile(srcjar_dir, package, resources_by_type, rjava_build_options): """Generates an R.java source file.""" package_r_java_dir = os.path.join(srcjar_dir, *package.split('.')) build_utils.MakeDirectory(package_r_java_dir) package_r_java_path = os.path.join(package_r...
2,125
async def test_unaviable_on_update_failure(hass: HomeAssistant) -> None: """Test entity unaviable on update failure.""" await setup_uptimerobot_integration(hass) entity = hass.states.get(UPTIMEROBOT_SENSOR_TEST_ENTITY) assert entity.state == STATE_UP with patch( "pyuptimerobot.UptimeRobot....
2,126
def _extract_decimal_with_text_az(tokens, short_scale, ordinals): """ Extract decimal numbers from a string. This function handles text such as '2 nöqtə 5'. Notes: While this is a helper for extractnumber_az, it also depends on extractnumber_az, to parse out the components of the decim...
2,127
def assign_read_kmers_to_contigs_new(kmer_ii, ambiguous_kmer_counts, unambiguous_contig_counts, contig_abundances): """ Assign ambiguous read k-mers based on contig averages counts. """ contig_counts = copy.deepcopy(unambiguous_contig_counts) contig_location_tuples = [] total_abundance = 0 ...
2,128
def test_file_analyser( tmpdir: "StrPathLike", contents: str, expected_n_lines: int, expected_n_definitions: int, expected_avg_lines: float, ) -> None: """Tests the results of a file analyser. Args: contents: Source code to be analysed expected_n_lines: Expected total number...
2,129
def cremi_scores(seg, gt, border_threshold=None, return_all=True): """ Compute the cremi scores (Average of adapted rand error, vi-split, vi-merge) Parameters ---------- seg: np.ndarray - the candidate segmentation gt: np.ndarray - the groundtruth border_threshold: value by which the border...
2,130
def run_testlauncher(package): """Run test launcher""" from qtpy.QtWidgets import QApplication app = QApplication([]) win = TestLauncherWindow(package) win.show() app.exec_()
2,131
def test_force_single_line_imports() -> None: """Test to ensure forcing imports to each have their own line works as expected.""" test_input = ( "from third_party import lib1, lib2, \\\n" " lib3, lib4, lib5, lib6, lib7, \\\n" " lib8, lib9, lib10, lib11, lib12, \\\n" " li...
2,132
def process_work_records(max_rows=20, record_id=None): """Process uploaded work records.""" set_server_name() task_ids = set() work_ids = set() """This query is to retrieve Tasks associated with work records, which are not processed but are active""" tasks = (Task.select( Task, WorkReco...
2,133
def test_IterateOverTuples(): """ @brief Demonstrates that we can iterate over a tuple. """ test_on_data_1 = IterateOverTuples.get_data_test() == (1, 7, 2) test_on_data_2 = IterateOverTuples.get_data_tswift() == (2008, 2014, 5) assert(test_on_data_1 and test_on_data_2)
2,134
def _coio_rebase(helper_module): """Rebase classes `tasklet' and `bomb' from those in the helper_module.""" global tasklet global bomb global current global main global _tasklets_created is_tasklet_ok = list(tasklet.__bases__) == [helper_module.tasklet] if is_tasklet_ok and bomb is helper_module.bomb: ...
2,135
def sign_transaction(transaction_dict, private_key) -> SignedTransaction: """ Sign a (non-staking) transaction dictionary with the specified private key Parameters ---------- transaction_dict: :obj:`dict` with the following keys nonce: :obj:`int` Transaction nonce gasPrice: :obj:`in...
2,136
def integralHesapla(denklem): """ Polinom kullanarak integral hesaplar. :param denklem: İntegrali hesaplanacak polinom. """ a,b=5,len(anaVeriler) deltax = 0.1 integral = 0 n = int((b - a) / deltax) for i in range(n): integral += deltax * (denklem.subs({x:a}) + denklem.subs({x...
2,137
def fmt(text,*args,**kwargs): """ String formatting made easy text - pattern Examples fmt("The is one = %ld", 1) fmt("The is text = %s", 1.3) fmt("Using keywords: one=%(one)d, two=%(two)d", two=2, one=1) """ return _fmt(text,args,kwargs)
2,138
def test_mask_bad_input_color_img(threshold_test_data): """Test for PlantCV.""" # Read in test data bad_img = cv2.imread(threshold_test_data.small_rgb_img) with pytest.raises(RuntimeError): _ = mask_bad(bad_img, bad_type='nan')
2,139
def value_to_class(v): """ Return the label of the pixel patch, by comparing the ratio of foreground to FOREGROUND_THRESHOLD Input: patch (numpy.ndarray): patch of a groundtruth image size:(PATCH_SIZE, PATCH_SIZE) Output: the label of the patch: ...
2,140
def namelist_path(output_dir): """Given directory containing TC results, return path to `*.in` file.""" file_paths = [os.path.join(output_dir, y) for x in os.walk(output_dir) for y in glob(os.path.join(x[0], '*.in'))] if len(file_paths) > 1: raise Exception("Multiple *.in files found in directory.")...
2,141
def mc(cfg): """ Return the MC (multi-corpus) AAI model, trained on the dysarthric and cross corpora. 3 BLSTM layers, and two single linear regression output layers to obtain articulatory trajectories corresponding to each corpus. Parameters ---------- cfg: main.Configuration user configur...
2,142
def gradient_dxyz(fxyz: tf.Tensor, fn: Callable) -> tf.Tensor: """ Function to calculate gradients on x,y,z-axis of a tensor using central finite difference. It calculates the gradient along x, y, z separately then stack them together :param fxyz: shape = (..., 3) :param fn: function to call :r...
2,143
def get_chunk_range(): """ Get the range of partitions to try. """ n_chunks = multiprocessing.cpu_count() if n_chunks > 128: raise NotImplementedError('Currently we consider the num. procs in machine to ' 'be < 128') chunk_range = [n_chunks] wh...
2,144
def test_iou(boxes_1, boxes_2, expected_iou): """Test IOU calculation.""" boxes_1 = torch.tensor(boxes_1) boxes_2 = torch.tensor(boxes_2) expected_iou = torch.tensor(expected_iou) assert ( torch.round(100 * iou(boxes_1, boxes_2)) == torch.round(100 * expected_iou) ).all()
2,145
def probabilityEval(Mub,Mbu,PSD,ID_basal,Mub_notBleached=None,Mbu_notBleached=None,ID_notBleached=None): """Returns the updated PSD Matrix and the corresponding number of receptors that got bound and unbound. To types, "basal" and "not bleached" can be considered, which is necessary when simulation FRAP. ...
2,146
def train_on_data_once( model_path, cv_folds=0, frames_path=None, annotations_path=None, species=None, fold=0, fraction=None, perform_evaluation=True, debug=0, ): """Performs training for the segmentation moduel of SIPEC (SIPEC:SegNet). Parameters ---------- model_pa...
2,147
def is_dict_like(obj: Dict[Literal["day", "month", "year"], List[int]]): """ usage.modin: 2 """ ...
2,148
def train(data_base_path, output_dir, label_vocab_path, hparams_set_name, train_fold, eval_fold): """Constructs trains, and evaluates a model on the given input data. Args: data_base_path: str. Directory path containing tfrecords named like "train", "dev" and "test" output_dir: str. Path to...
2,149
def get_seven_seg_light_pattern(img, seven_seg_pts, base=[0, 0]): """入力画像imgに対してseg_ptsで指定した座標群""" ptn = 0x00 # TODO: この座標群を全て事前計算しておくとさらに高速化できそう。 seven_seg_pts_based = [ np.array(seven_seg_pts[0]) + np.array(base), np.array(seven_seg_pts[1]) + np.array(base), np.array(s...
2,150
def _enzyme_path_to_sequence(path, graph, enzymes_sites): """Converts a path of successive enzymes into a sequence.""" return "".join( [enzymes_sites[path[0]]] + [graph[(n1, n2)]["diff"] for n1, n2 in zip(path, path[1:])] )
2,151
def profile_to_section(profile_name): """Converts a profile name to a section header to be used in the config.""" if any(c in _WHITESPACE for c in profile_name): profile_name = shlex_quote(profile_name) return 'profile %s' % profile_name
2,152
def BytesFromFile(filename: str) -> ByteList: """Read the EDID from binary blob form into list form. Args: filename: The name of the binary blob. Returns: The list of bytes that make up the EDID. """ with open(filename, "rb") as f: chunk = f.read() return [int(x) for x ...
2,153
def array_to_patches(arr, patch_shape=(3,3,3), extraction_step=1, normalization=False): #Make use of skleanr function extract_patches #https://github.com/scikit-learn/scikit-learn/blob/51a765a/sklearn/feature_extraction/image.py """Extracts patches of any n-dimensional array in place using strides. Given an n-d...
2,154
def directory_select(message: str, default: Optional[str] = None, cli_flag: Optional[str] = None, force_interactive: bool = False) -> Tuple[int, str]: """Display a directory selection screen. :param str message: prompt to give the user :param default: default value to return (if one ex...
2,155
def trade_from_kraken(kraken_trade): """Turn a kraken trade returned from kraken trade history to our common trade history format""" currency_pair = kraken_to_world_pair(kraken_trade['pair']) quote_currency = get_pair_position(currency_pair, 'second') return Trade( # Kraken timestamps have f...
2,156
def load_ipython_extension(ipython): """Register extension with IPython.""" ipython.register_magics(PDCache)
2,157
def _create_instancer_mesh(positions: np.ndarray, name="mesh_points", *, bpy): """Create mesh with where each point is a pseudo face (three vertices at the same position. """ assert positions.ndim == 2 assert positions.shape[1] == 3 if name in bpy.data.meshes: raise RuntimeError("Mesh '...
2,158
def bound_to_nitorch(bound, as_type='str'): """Convert boundary type to niTorch's convention. Parameters ---------- bound : [list of] str or bound_like Boundary condition in any convention as_type : {'str', 'enum', 'int'}, default='str' Return BoundType or int rather than str R...
2,159
def distance_transform_edt( base_region_raster_path_band, target_distance_raster_path, sampling_distance=(1., 1.), working_dir=None, raster_driver_creation_tuple=DEFAULT_GTIFF_CREATION_TUPLE_OPTIONS): """Calculate the euclidean distance transform on base raster. Calculates the euclidean...
2,160
def test_encoder_on_nonfull(numerical, cyclical, categorical): """The test checks that if the dataframe has more columns than columns map - extra columns are ignored.""" columns_map = defaultdict(list) result = {} for feature, category_type in [(numerical, "numerical"), (cyclical, "cyclical"), (catego...
2,161
def Amp(f: jnp.ndarray, theta: jnp.ndarray) -> jnp.ndarray: """ Computes the Taylor F2 Frequency domain strain waveform with non-standard spin induced quadrupoole moment for object two. Note that this waveform assumes object 1 is a BH and therefore uses the chi * M_total relation to find C Not...
2,162
def get_forecastgroup_path(dscript_name): """ get forecast group from dispatcher init file :param dscript_name: filepath of dispatcher init file :return: string containing the path of the forecast group """ # create object to represent init file try: df = DispatcherInitFile(dscript_n...
2,163
def spol(f, g): """ Compute the S-polynomial of f and g. INPUT: - ``f, g`` -- polynomials OUTPUT: the S-polynomial of f and g EXAMPLES:: sage: R.<x,y,z> = PolynomialRing(QQ) sage: from sage.rings.polynomial.toy_buchberger import spol sage: spol(x^2 - z - 1, z^2 - y ...
2,164
def test_create_resource(): """Should create resource successfully when no error is caught.""" response = execution.create_resource(MagicMock(), echo=True) assert response.symbol == "+" assert response.reason == "Created"
2,165
def evaluate_baselines(experiment, seed, num_pairs, samples_per_pair, loop_size=None): """Helper function to evaluate the set of baselines.""" gumbel_max_joint_fn = functools.partial( coupling_util.joint_from_samples, ...
2,166
def add_command(subparsers): """Add specific subcommands that the action "create" can use""" parser = subparsers.add_parser('create', help=create.__doc__) parser.add_argument('-r', '--recreate', action='store_true', help='If set, I\'ll first erase the current database') parser.add_argument('-v', '--verbose', ...
2,167
def generate_template_mask(protein): """Generate template mask.""" protein['template_mask'] = np.ones(shape_list(protein['template_domain_names']), dtype=np.float32) return protein
2,168
def minimal_rotation(R, t, iterations=2): """Adjust frame so that there is no rotation about z' axis The output of this function is a frame that rotates the z axis onto the same z' axis as the input frame, but with minimal rotation about that axis. This is done by pre-composing the input rotation with...
2,169
def test_sigterm_log(create_project): """Test that a log file is generated when a SIGTERM is received.""" with create_project( ''' import sys import time def nothing(): """usage: say nothing""" print('ready') sys.stdout.flush() whi...
2,170
def get_info(api_key: hug.types.text, hug_timer=20): """Return 'getinfo' data from the Gridcoin Research client!""" if (api_key == api_auth_key): # Valid API Key! response = request_json("getinfo", None) if (response == None): return {'success': False, 'api_key': True} else: return {'success': True, 'ap...
2,171
def clean_all(): """清理所有二维码图片""" for file_name in os.listdir(QR_CODE_PATH): file_path = os.path.join(QR_CODE_PATH, file_name) if os.path.isfile(file_path): os.remove(file_path)
2,172
def stats_proc(optlist, hduids, hdulist): """print statistics for region according to options """ # Process each HDU in the list "hduids" for hduid in hduids: hdu = hdulist[hduid] pix = hdu.data name = hdu.name if optlist.bias: iu.subtract_bias(optlist.bias, o...
2,173
def get_output_col_names(perils, factors): """Column names of the output data frame that contains `perils` and `factors`""" return ( PCon.RAW_STRUCT['stem']['col_names'] + [per + PCon.OUTPUT_DEFAULTS['pf_sep'] + fac for per, fac in pd.MultiIndex.from_product( [perils, [PCon...
2,174
def item_chosen(button, choice): """Respond to button clicks and enter or space presses.""" # from pudb import set_trace; set_trace() mark_menu_item(cli.main_menu) advance_menu(cli.main_menu) send_wrapper(choice, cli.tty)
2,175
def _get_real_path(workspace_path): """Converts the given workspace path into an absolute path. A tuple of a real path and an error is returned. In this tuple, either the real path or error is present. The error is present in the returned tuple either if no workspace dir is given or the generated real path is...
2,176
def create_alpha_graph(experiments, filename, alphas, just_plot=False): """ Save experiment results to CSV file and graph :param experiments: List of (data, dictionary) for experiments ('no_normalization', 'd_normalization', 'x_normalization', 'full_normalization') :param filename: filename for the CSV ...
2,177
async def ws_send(websocket: WebSocket, chat_info: dict) -> None: """ wait for new items on chat stream and send data from server to client over a WebSocket :param websocket: :type websocket: :param chat_info: :type chat_info: """ rprint("ws_send first line") pool = await get_re...
2,178
def simple_caesar(txt, rot=7): """Caesar cipher through ASCII manipulation, lowercase only.""" alphabet = string.ascii_lowercase # pick alphabet shifted_alphabet = alphabet[rot:] + alphabet[:rot] # shift it table = str.maketrans(alphabet, shifted_alphabet) # create mapping table ...
2,179
def target(streamlines, target_mask, voxel_size): """Retain tracks that pass though target_mask This function loops over the streamlines and returns streamlines that pass though target_mask. Parameters: ----------- streamlines : iterable A squence of streamlines. Each streamline should...
2,180
def weave(devicePairs): """ """ routers = [x[0] for x in devicePairs if x[0][1] == "router.PNG"] selected = [] for devicePair in devicePairs: starterDevice = devicePair[0] if starterDevice[1] == "router.PNG": continue starterPosition = maths.getCenter(t...
2,181
def plot_xmhm(result, gals_bf, halos_bf, bf_chi2): """ Plot SMHM from data, best fit param values, param values corresponding to 68th percentile 100 lowest chi^2 values. Parameters ---------- result: multidimensional array Array of SMF, blue fraction and SMHM information gals_...
2,182
def change_image_ani(image: _Surface, name: _Optional[str] = None, id_: _Optional[int] = None) -> _TextureAni: """ change_image_ani(image, name=None, id_None) Type: function Description: returns a TextureAni that simply changes the image of an AniEleme...
2,183
def import_string(dotted_path): """ Import a dotted module path and return the attribute/class designated by the last name in the path. Raise ImportError if the import failed. """ try: module_path, class_name = dotted_path.rsplit('.', 1) except ValueError as err: raise ImportErro...
2,184
def read_u16(f): """Reads a two byte unsigned value from the file object f. """ temp = f.read(2) if not temp: raise EOFError("EOF") return int.from_bytes(temp, byteorder='little', signed=False)
2,185
def encrypt_file(input_file, output_file, write_mode, encryption_key, scrypt_n=14, scrypt_r=8, scrypt_p=1, remove_input=True): """Taking an input file as well as the ASCII encryption key, the file is encrypted with AES-256, and outputted to output_file. The input file is removed by default. ...
2,186
def new_figure_manager_given_figure(num, figure): """ Create a new figure manager instance for the given figure. """ canvas = FigureCanvasQTAgg(figure) return FigureManagerQT(canvas, num)
2,187
def process_image(sample, settings, mode, color_jitter, rotate): """ process_image """ mean = settings.image_mean std = settings.image_std crop_size = settings.crop_size img_path = sample[0] img = cv2.imread(img_path) if mode == 'train': if rotate: img = rotate_image(i...
2,188
def flag_spot(states: np.ndarray, x: int, y: int, annotations: np.ndarray) -> None: """Put a flag in (x, y) coordinate.""" global _marked_mines_count x = x + 1 y = y + 1 if is_marked(states[y, x]): states[y, x] = states_id.CLOSED annotations[y, x] = "" _marked_...
2,189
def loglinear(F, X, confmeth, conftype=1, alpha=0.75, t_star=0.0): # pylint: disable=C0103 """ Function to estimate the parameters (gamma0 and gamma1) of the NHPP loglinear model. There is no regression function for this model. :param list F: list of failure counts. :param list X: list of indivi...
2,190
def convert_pressures(a, from_units, to_units): """Converts values in numpy array (or a scalar) from one pressure unit to another, in situ if array. arguments: a (numpy float array, or float): array of pressure values to undergo unit conversion in situ, or a scalar from_units (string): the units ...
2,191
def extend(best): """ Extend current best sum for next triangle row offering best value from previous row. E.g. for triangle: 1 / 2, 3 / 4, 1, 5 best values second row are: 3, 4. Emit 3, 4, 4 for updating third row which gives best values as: 7, 5, 9, which gives 7, 7, 9, 9 for next row. :param best: cu...
2,192
def split_train_hdf(size_SB=4000): """ split master hdf5 file into smaller hdf5s in order to load completely into memory with latd_generator which was originally created for loading the cached augmented data, by splitting the larger hdf5, we can load non-augmented files into memory and run the network m...
2,193
def amovie(stream: Stream, *args, **kwargs) -> FilterableStream: """https://ffmpeg.org/ffmpeg-filters.html#amovie""" return filter(stream, amovie.__name__, *args, **kwargs)
2,194
def kutta_condition(A_source, B_vortex): """ Builds the Kutta condition array. Parameters ---------- A_source: 2D Numpy array of floats Source contribution matrix for the normal velocity. B_vortex: 2D Numpy array of floats Vortex contribution matrix for the normal velocity. ...
2,195
def absorption_sinogram(p, anglelist): """Generates the absorption sinogram for absorption by the full elemental content of the Phantom2d object. Parameters ---------- p : Phantom2d object anglelist : list of float Ordered list of sinogram projection angles in degrees. Returns ...
2,196
def trace_feature_vector_from_nodes(embeddings, traces, dimension): """ Computes average feature vector for each trace Parameters ----------------------- embeddings, Text-based model containing the computed encodings traces: List, List of traces treated as sentences by the model...
2,197
def jitter_rotate(drawing, sigma=0.2): """ Rotate an entire drawing about 0,0 by a random gaussian. """ rotation = np.random.randn(1) * sigma matrix = create_rotation_matrix(rotation) return [np.dot(stroke, matrix).squeeze() for stroke in drawing]
2,198
def reset_matrix(node): """Reset the offsetParentMatrix attribute to identity. Arguments: node (str): The node to reset. """ matrix_ = OpenMaya.MMatrix() cmds.setAttr(node + ".offsetParentMatrix", matrix_, type="matrix")
2,199