content
stringlengths
22
815k
id
int64
0
4.91M
def yolo_detect(video_id): """ This is a HACK since Tensorflow is absolutely atrocious in allocating and freeing up memory. Once a process / session is allocated a memory it cannot be forced to clear it up. As a result this code gets called via a subprocess which clears memory when it exits. :param...
57,100
def linear_surge( state: np.ndarray, thrust: np.ndarray, parameters: np.ndarray ) -> np.ndarray: """AUV equation of motion for low velocities in 1DOF (surge) Args: state (np.ndarray): position and velocity in surge thrust (np.ndarray): current thrust in surge parameters (np.ndarray)...
57,101
def get_cloud_assets(id_token, is_printing_page_results): """Method to call the Cloud Assets API using the ID token we got earlier. We use a loop to handle pagination. Cloud assets output is printed to stdout using pretty-print for formatting, and returned as a list of json objects. Args: id_t...
57,102
def login(request): """View to check the auth0 assertion and remember the user""" login = request.authenticated_userid if login is None: namespace = userid = None else: namespace, userid = login.split('.', 1) # create new user account if one does not exist if namespace != 'auth0...
57,103
async def test_send_payment_meets_travel_rule_threshold_sender_kyc_data_is_soft_match_and_accepted_receiver_kyc_data_is_soft_match_and_rejected( currency: str, travel_rule_threshold: int, target_client: RestClient, stub_client: RestClient, ) -> None: """ Test Plan: 1. Create sender account ...
57,104
def construct_M(frequencies,basis='gaussian',order=1,epsilon=1): """ Construct M matrix for calculation of DRT ridge penalty. x^T@M@x gives integral of squared derivative of DRT over all ln(tau) Parameters: ----------- frequencies : array Frequencies at which basis functions are centered basis : string, opt...
57,105
def KK_RC76_fit(params, w, t_values): """ Kramers-Kronig Function: -RC- Kristian B. Knudsen (kknu@berkeley.edu / kristianbknudsen@gmail.com) """ Rs = params["Rs"] R1 = params["R1"] R2 = params["R2"] R3 = params["R3"] R4 = params["R4"] R5 = params["R5"] R6 = params["R6"] ...
57,106
def relu_prime(x): """ ReLU derivative. """ return (0 <= x)
57,107
def get_api_key(auth_header: Optional[models.AuthHeader] = None) -> models.ApiKey: """Get a user's API key.""" res_json = Users.get('apikey', auth=auth_header) return models.ApiKey.from_dict(res_json)
57,108
def detect_host_os(): """ Returns an instance of OperatingSystem that matches given host system :raises: NotImplementedError if host operating system is not yet supported :rtype: HostOS """ global CURRENT_OS if not CURRENT_OS: if sys.platform.startswith('linux'): from za...
57,109
def opts2v_polys_bb(opts): """Creates VPolysBb functor by calling its constructor with options from opts. Args: opts (obj): Namespace object with options. Returns: v_polys_bb (obj): Instantiated VPolysBb functor. """ return VPolysBb(opts.lm_ordering_lm_order)
57,110
def import_optional_dependency(name, message): """ Import an optional dependecy. Parameters ---------- name : str The module name. message : str Additional text to include in the ImportError message. Returns ------- module : ModuleType The imported module. ...
57,111
def test_renewal_rl_success(session, client, jwt): """Assert that a valid repairer's lien create statement returns a 200 status.""" # setup rv1 = create_financing_test(session, client, jwt, 'RL') assert rv1.status_code == HTTPStatus.CREATED assert rv1.json['baseRegistrationNumber'] base_reg_num ...
57,112
def test_create_equal_sampling_atom_dataset(crystal_file_dir): """Tests that elements are sampled uniformly by atomic number. Parameters ---------- crystal_file_dir: str Path to a directory containing Crystal Information Files (CIFs). """ crystal_files = glob_crystal_files(crystal_file_d...
57,113
def road_distance(lat1, lon1, lat2, lon2): """ Calculate the distance by road between two points """ point1 = lat1, lon1 point2 = lat2, lon2 url = "https://maps.googleapis.com/maps/api/distancematrix/json?origins={0},{1}&destinations={2},{3}&mode=driving&language=en-EN&sensor=false&key={4}".form...
57,114
def initializer(fun): """ Automatically initialize instance variables Args: fun: an init function Returns: a wrapper function """ names, varargs, keywords, defaults, kwonlyargs, kwonlydefaults, annotations = inspect.getfullargspec(fun) @wraps(fun) def wrapper(self, *args, **kwarg...
57,115
def _twosided_zerolag(data, zerolag): """Build a symmetric vector out of stricly positive lag vector and zero-lag .. doctest:: >>> data = [3,2,1] >>> zerolag = 4 >>> twosided_zerolag(data, zerolag) array([1, 2, 3, 4, 3, 2, 1]) .. seealso:: Same behaviour as :func:`twosided...
57,116
def Filter2D(src, dst, ker, type=DataType.none): """\ Convolve an image with a kernel. :param src: source image :param dst: destination image :param ker: convolution kernel :param type: destination DataType. If set to DataType.none, the DataType of ``src`` is used :return: None ""...
57,117
def collate_function(batch): """ create a mini batch an make sure the image are of the same size """ batch.sort(key=lambda data: len(data[1]), reverse=True) # sort by the longest caption images, captions = zip(*batch) # unzip the batch images = torch.stack(images) # stack the images captions...
57,118
def convert(value): """Convert widget definitions to JSON-able object""" widget_definitions = {} if (os.path.splitext(value)[1] == '.py'): for (name, cls) in find_widgets(filename=value): widget_definitions[name] = convertWidget(name, cls) else: # Assume input is module name...
57,119
def cluster_status(cluster, collection=None, shard=None): """ Retrieve status for the specified cluster. Arg Usage: cluster: Identifies the SolrCloud cluster you want to get status for. collection (optional): restricts status info to this collection. shard (optional, comma-separated list):...
57,120
def scheduled_operation_state_update(context, operation_id, values): """Update the ScheduledOperationState record with the most recent data.""" session = get_session() with session.begin(): state_ref = _scheduled_operation_state_get(context, operation_id, ...
57,121
def msec2cmyear(ms): """ Return m/s converted to cm/year Quantity Args: ms (float): meters per second Returns: cm / year """ return (ms * UR.m / UR.s).to(UR.cm / UR.year).magnitude
57,122
def send_template(ACCESS_TOKEN, touser, template_id, data=None): """ 发送模板消息 接口调用请求说明 http请求方式: POST https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=ACCESS_TOKEN :param ACCESS_TOKEN:获取到的凭证 :param touser:接收者openid :param template_id:模板ID :...
57,123
def find_chinese(str): """ 查找字符串中中文集合 :param str: :return: """ return re.findall(RE_CHINESE, str)
57,124
def localpooling_filter(adj, symmetric=True): """ Computes the local pooling filter from the given adjacency matrix, as described by Kipf & Welling (2017). :param adj: a np.array or scipy.sparse matrix of rank 2 or 3; :param symmetric: boolean, whether to normalize the matrix as \(D^{-\\frac{1}...
57,125
def curate_url(url): """ Put the url into a somewhat standard manner. Removes ".txt" extension that sometimes has, special characters and http:// Args: url: String with the url to curate Returns: curated_url """ curated_url = url curated_url = curated_url.r...
57,126
def copy_into(src, dst, timeout=90, symlinks=False, lock=None, locking=True): """Copy all the files and directories in src to the directory dst""" log = get_logger(__name__) if isdir(src): merge_tree(src, dst, symlinks, timeout=timeout, lock=lock, locking=locking) else: if isdir(dst): ...
57,127
def full(shape: Shape, fill_value: Array, dtype: Optional[DType] = None) -> Array: """Returns an array of `shape` filled with `fill_value`. Args: shape: sequence of integers, describing the shape of the output array. fill_value: the value to fill the new array with. dtype: the type of the output array,...
57,128
def get_news(): """ Returns two dictionnary object containing news articles informations. The first one is a short version, with little informations and the second one contains all the informations. """ API_KEY = 'd913f4f1287a42819abc66f428e0fad4' sources = 'bloomberg'...
57,129
def post(request): """ 新增关注 @param request: @return: """ try: # 获取当前登录用户的user_id user_id = request.session.get('user_id') user = User.objects.get(pk=user_id) query_dict = request.POST # 获取要关注的用户的id following_user_id = query_dict.get('user_id') ...
57,130
def get_module_root(path): """ Get closest module's root begining from path # Given: # /foo/bar/module_dir/static/src/... get_module_root('/foo/bar/module_dir/static/') # returns '/foo/bar/module_dir' get_module_root('/foo/bar/module_dir/') # returns '/foo/bar/...
57,131
def read_saved_ip(): """reads current ip""" with CURRENT_IP_ADDRESS_PATH.open('r') as fp: saved_ip = fp.read() return saved_ip
57,132
def runProtocolsWithReactor(reactorBuilder, serverProtocol, clientProtocol, endpointCreator): """ Connect two protocols using endpoints and a new reactor instance. A new reactor will be created and run, with the client and server protocol instances connected to each other us...
57,133
def datetime_to_string(dt): """ Convert the given datetime (converted in UTC) to a string value. """ return fields.Datetime.to_string(dt.astimezone(utc))
57,134
def load_model(path='../models/inception_v3'): """Retrieves the trained model""" model = keras_load_model(path) return model
57,135
def AddSubstitutions(argument_group): """Adds a substituion flag to the given argument group. Args: argument_group: argparse argument group to which the substitution flag will be added. """ argument_group.add_argument( '--substitutions', metavar='KEY=VALUE', type=arg_parsers.ArgDic...
57,136
def _md_scan_and_assemble(): """Scan all md devices and assemble RAID arrays from them. This call does not fail if no md devices are present. """ try: utils.execute('mdadm', '--assemble', '--scan', '--verbose') except processutils.ProcessExecutionError: LOG.info('No new RAID devices...
57,137
def parse_args(): """ Parse input arguments. """ parser = argparse.ArgumentParser(description='Compare different motion planners') parser.add_argument('--paths', nargs='+', help='List of bag files that should be analyzed', type=str, required=False) args = parser.parse_args() return args
57,138
def log_artifact(message): """This function is used to write the execution time of the functions in the log file.""" logging.basicConfig(filename= r"C:\Users\Vissamsetty Bharath\Downloads\Artifact_Detection-master\logs\log_file_ringing.log", format='%(asctime)s : %(name)s : %(funcName)s : %(levelname)s ...
57,139
def mqtt_client(ini: dict, mqtt_iface: MQTTInterface): """ Establishes an MQTT connection with the brocker server, subscribes all configured topics and enqueue received messages into the MQTT interface queue. """ # Validate mqtt configuration parameters if not verify_params(ini, 'mqtt', ['se...
57,140
def dcdt_liden(t, y): """ System of ODEs representing the biomass pyrolysis kinetic reactions from Liden 1988. Reactions in the kinetic scheme are Reaction 1: wood -> tar Reaction 2: tar -> gas Reaction 3: wood -> (gas + char) Parameters ---------- t : scalar Ti...
57,141
def create_dataset_positives_one_sub(subdir, file): """This function creates a positive patch and the corresponding mask Args: subdir (str): folder where positive patch is stored file (str): filename of positive patch Returns: out_array (np.ndarray): it contains the positive patch an...
57,142
def cutback_polarization_rotator(n_devices_target, design=3): """ sample of component cutback """ rows = 4 cols = n_devices_target // (rows * 2) from pp.components.polarization_rotator import polarization_rotator c = cutback_component( component=polarization_rotator(design=design), rows=row...
57,143
async def randomise(items): """ For .random command, get a random item from the list of items. """ itemo = (items.text[8:]).split() if len(itemo) < 2: await items.edit( "`2 atau lebih item yang diperlukan! Periksa .help random untuk info lebih lanjut.`" ) return index...
57,144
def update_db_ddl(c): """ Creates a ddl from the entire db in usmai_dw_etl.sql """ db_settings = dwetl.database_credentials.db_settings() db_user = db_settings['DB_USER'] db_host = db_settings['DB_HOST_NAME'] db_port = db_settings['DB_PORT'] db_password = db_settings['DB_PASSWORD'] d...
57,145
def get_ky_and_hyp_pack(name, s1, e1, s2, e2, same: bool, hyps: np.ndarray, kernel_grad, cutoffs=None, hyps_mask=None): """ computes a block of ky matrix and its derivative to hyper-parameter If the cpu set up is None, it uses as much as posible cpus :param hyps: list of hyper-parameters :p...
57,146
def generate_language_cnf(cnf_grammar): """ Returns the language of a grammar in form 2 (CNF). """ key_productions = {key: [[key]] for key in _NO_EXPAND} def is_terminal_rule(rule_rhs): return isinstance(rule_rhs, str) def is_nonterminal_rule(rule_rhs): return isinstance(rule_rhs, tupl...
57,147
async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry): """Unload a config entry.""" unload_ok = all(await asyncio.gather(*[ hass.config_entries.async_forward_entry_unload(entry, component) for component in PLATFORMS ])) if unload_ok: hass.data[DOMAIN].pop(entry.e...
57,148
def get_todays_image(session: Session = Depends(generate_session), group_name: str = "Home"): """ Returns the image for todays meal-plan. """ group_in_db: GroupInDB = db.groups.get(session, group_name, "name") recipe = get_todays_meal(session, group_in_db) recipe_image = recipe.image_dir.joinpa...
57,149
def test_status(): """Test that the pokemon's stats are affected by stats.""" test_speed_paralyze() test_attack_burn()
57,150
def get_enzyme_train_set(traindata): """[获取酶训练的数据集] Args: traindata ([DataFrame]): [description] Returns: [DataFrame]: [trianX, trainY] """ train_X = traindata.iloc[:,7:] train_Y = traindata['isemzyme'].astype('int') return train_X, train_Y
57,151
def get_last_cherry_pick_sha(): """ Finds the SHA of last cherry picked commit. SHA should be added to cherry-pick commits with -x option. :return: SHA if found, None otherwise. """ get_commit = ['git', 'log', '-n', '1'] _, output = run_cmd_with_output(get_commit, exit_on_failure=True) ...
57,152
def patch_utils_path(endpoint: str) -> str: """Returns the utils module to be patched for the given endpoint""" return f"bluebird.api.resources.{endpoint}.utils"
57,153
def convert_scen(source, target, param_dict, *, add_header=False): """ Takes a file-like object following movingai's .scen-format and converts characters to clingo literals following the provided dictionary. Writes to specified target file. Arguments: source - file-like object to read from ...
57,154
def extract_proportions(groups: InpGroups): """ Get species proportions of each source and the total source emission rates Returns: numpy.ndarray: proportions, [sources x species] numpy.ndarray: total emission of every source [sources x 1] """ srcEmiss = groups.sourceEmiss total = np....
57,155
def balance_of(currency_module, address) -> None: """ This module is used to get your someone's current balance, i.e, get the number of tokens that you hold. """ details = get(currency_module) print(colored( f"The balance of {address} is {currency_module.format_units(currency_module.balance_...
57,156
def sample_randdir(num_obs, signal_ranks, R=1000, n_jobs=None): """ Draws samples for the random direction bound. Parameters ---------- num_obs: int Number of observations. signal_ranks: list of ints The initial signal ranks for each block. R: int Number of sample...
57,157
def init_db(): """Initializes database""" with app.app_context(): init_db() click.echo("Database initialized")
57,158
def _rescale(M, C, D): """ Rescales the specified matrix, M, according to the new minimum, C, and maximum, D. C and D should be of the dimension 1 x cols. - TODO: avoid recomputing A and B, might not be efficient :param M: Matrix. :param C: Vector of new target minimums. :param D: Vect...
57,159
def get_artist_playmeid(h5, songidx=0): """ Get artist playme id from a HDF5 song file, by default the first song in it """ return h5.root.metadata.songs.cols.artist_playmeid[songidx]
57,160
def validate_transformer_unit_tests(transformer): """Validate the unit tests of a transformer. This function finds the module where the unit tests of the transformer have been implemented and runs them using ``pytest``, capturing the code coverage of the tests (how many lines of the source code are exe...
57,161
def rgbToGray(r, g, b): """ Converts RGB to GrayScale using luminosity method :param r: red value (from 0.0 to 1.0) :param g: green value (from 0.0 to 1.0) :param b: blue value (from 0.0 to 1.0) :return GreyScale value (from 0.0 to 1.0) """ g = 0.21*r + 0.72*g + 0.07*b return g
57,162
def BottleneckBlock( filters: int, strides: int, use_projection: bool, bn_momentum: float = 0.0, bn_epsilon: float = 1e-5, activation: str = "relu", se_ratio: float = 0.25, survival_probability: float = 0.8, name=None, ): """Bottleneck block variant for residual networks with BN.""...
57,163
def bag_of_words(words, dictionary, count=True): """ Compute Bag-of-Words from word list and dictionary """ n_feature_words = len( dictionary.keys() ) BOW = sp.zeros(n_feature_words, dtype=int) for word in words: if word in dictionary.keys(): if count: BOW[ d...
57,164
def gen_plane_cdmesh(updirection=np.array([0, 0, 1]), offset=0, name='autogen'): """ generate a plane bulletrigidbody node :param updirection: the normal parameter of bulletplaneshape at panda3d :param offset: the d parameter of bulletplaneshape at panda3d :param name: :return: bulletrigidbody ...
57,165
def main(config, resume, test_flag, visual_flag): """ 获取config,resume,test_flag参数 Args: config: 配置文件json格式 resume(bool): 是否继续训练 test_flag(bool): 是否仅测试 visual_flag(bool): 是否开启tensorboard相关代码 Returns: """ torch.manual_seed(int(config["seed"])) # both CPU and CUDA ...
57,166
def import_c_accel(globs, cname): """ Import the C-accelerator for the __name__ and copy its globals. """ name = globs.get('__name__') if not name or name == cname: # Do nothing if we're being exec'd as a file (no name) # or we're running from the C extension return ...
57,167
def main(): """ Runs hyperparameter search. """ args = create_parser().parse_args() conf = json.load(args.configuration_file) env = args.environment_path submit_jobs(env, conf['submit_template'], conf['experiment_template'], conf['name'], conf['options'], conf['num_jobs'], conf['num_parallel'])
57,168
def create_virt_emb(n, size): """Create virtual embeddings.""" emb = slim.variables.model_variable(name='virt_emb', shape=[n, size], dtype=tf.float32, trainable=True, ...
57,169
def rselect(input_handle, output_handle, name, first, last): """Select a substring from every read. Positions are one-based and inclusive. :arg stream input_handle: Open readable handle to a FASTA/FASTQ file. :arg stream output_handle: Open writable handle to a FASTA/FASTQ file. :arg str name: Acce...
57,170
def vivado_iscas89_runner(): """ Set for all .vhd files in ../iscas89/vhdl/ """ files = list(helpers.natural_sort(glob.iglob('../iscas89/vhdl/*.vhd'))) logging.debug('ISCAS89 files: %r', files) for file in files: name = os.path.splitext(os.path.basename(file))[0] yield dict(name=...
57,171
async def test_text_type_discovery( hass: HomeAssistant, text_node: Sensor, transport_write: MagicMock, receive_message: Callable[[str], None], ) -> None: """Test text type discovery.""" receive_message("1;2;0;0;36;\n") receive_message("1;2;1;0;47;test\n") receive_message("1;2;1;0;47;tes...
57,172
def domain_to_index(search_domain): """ Convert domain name into corresponding index """ domain_tokens_dict = get_domain_dict() if search_domain == 'Лингвистика': domain_token = domain_tokens_dict.get('Linguistics') elif search_domain == 'Социология': domain_token = domain_token...
57,173
def choose_reads(hole, rng, n, predicate): """Select reads from the hole metadata.""" reads = [] required_reads = set(v for v in hole.metadata.required_reads if predicate(v)) allowed_reads = set(v for v in hole.metadata.allowed_reads if predicate(v)) while len(reads) < n and (required_reads or allowed_reads):...
57,174
def task_test_send_template(request): """测试发送模板""" datas = json.loads(request.body.decode()) address = datas["params"]["wx_bot_addr"] data = { "msgtype": "text", "text": { "content": datas["params"]["template"] } } return response(0, data={ "sendResult...
57,175
def kbrandmac(length = 8): """Returns a random MAC address using a list valid OUI's from ZigBee device manufacturers.""" return randmac(length)
57,176
def Acf(poly, dist, N=None, **kws): """ Auto-correlation function. Args: poly (numpoly.ndpoly): Polynomial of interest. Must have ``len(poly) > N``. dist (Dist): Defines the space the correlation is taken on. N (int): The number of time steps apar...
57,177
def worker (conn, addr, rsyslog_socket, buffer_read_size): """ Read from the TCP buffer and lookup for one valid JSON struct. When a JSON struct is find, it sends to Rsyslog and start over """ data="" # Read from socket forever while 1: data = data + conn.recv(buffer_read_size).deco...
57,178
def position_potential_operator(n_dimensions, grid_length, length_scale, spinless=False): """Return the potential operator in position space second quantization. Args: n_dimensions: An int giving the number of dimensions for the model. grid_length: Int, the numbe...
57,179
def maximum(x, y): """Returns the larger one between real number x and y.""" return x if x > y else y
57,180
def swissPairings(): """Returns a list of pairs of players for the next round of a match. Assuming that there are an even number of players registered, each player appears exactly once in the pairings. Each player is paired with another player with an equal or nearly-equal win record, that is, a pla...
57,181
def patched_auth_succeeded_open_connection( auth_succeeded_prepared_stream_reader, event_loop ): """Return a tuple of patched stream_reader and stream_writer.""" stream_writer = MagicMock() if asyncio.iscoroutinefunction(stream_writer): # Python 3.8.2 and later return_value = (auth_succe...
57,182
def make_compatible(structures): """Enforce that points be shared by all structures""" gen_coord_dict = {} for i, structure in enumerate(structures): for gen_coord in structure.getGenCoords(): if gen_coord in gen_coord_dict: gen_coord_dict[gen_coord] += 1 else: gen_coord_dict[gen_coord] = 1 consen...
57,183
def test_kface_bulk_add(client): """ Test bulk add known face """ # Test incorrect upload response = client.post('/fras/app/login', json = {'login_id': 'admin', 'password': 'admin'}) response = client.post('/fras/app/kface_bulk_add', data = {'file': './../test_data/modi_grp1.jpeg'}) assert response....
57,184
def make_scores_df(metatlas_dataset): """ Returns pandas dataframe with columns 'max_intensity', 'median_rt_shift','median_mz_ppm', 'max_msms_score', 'num_frag_matches', and 'max_relative_frag_intensity', rows of compounds in metatlas_dataset, and values of the best "score" for a given compound across a...
57,185
def compute_sensitivity(f_jac, X): """Calculate sensitivity for many samples via .. math:: S = (I - J)^{-1} D(\frac{1}{{I-J}^{-1}}) """ J = f_jac(X) n_genes, n_genes_, n_cells = J.shape S = np.zeros_like(J) I = np.eye(n_genes) for i in tqdm( np.arange(n_cells), des...
57,186
def subsequent_mask(size): """Mask out subsequent positions (adapted from http://nlp.seas.harvard.edu/2018/04/03/attention.html)""" attn_shape = (1, size, size) subsequent_mask = np.triu(np.ones(attn_shape), k=1).astype('uint8') return torch.from_numpy(subsequent_mask) == 0
57,187
def remove_file(filepath): """Remove a file if it exists.""" try: os.remove(os.path.join(PROJECT_DIRECTORY, filepath)) except FileNotFoundError: pass
57,188
def plot_rebit_prior(prior, rebit_axes=REBIT_AXES, n_samples=2000, true_state=None, true_size=250, force_mean=None, legend=True, mean_color_index=2 ): """ Plots rebit states drawn from a given prior. :param qinfer.tomography.DensityOperatorDistribution prior: Distributio...
57,189
def create_dir(dir): """ Checks if a directory exists, or else create it Args: dir: directory to create """ if not os.path.exists(dir): os.makedirs(dir)
57,190
def game_to_dict(game: cpp.Game) -> GameDict: """Convert a game object into a dictionary (easily convertible to JSON).""" result = { "total": game.total_bet_score, "bet": game.table.bet_money, "state": game.game_state.value, } for cards_key, card_list in [ ("playerHand", ...
57,191
def cut_square_to_circle(img): """ 将正方形图片切割成圆形 :param img对象 :return: img对象 """ ima = img size = ima.size print(size) # 因为是要圆形,所以需要正方形的图片 r2 = min(size[0], size[1]) if size[0] != size[1]: ima = ima.resize((r2, r2), Image.ANTIALIAS) # 最后生成圆的半径 r3 =...
57,192
def is_acceptable_multiplier(m): """A 61-bit integer is acceptable if it isn't 0 mod 2**61 - 1. """ return 1 < m < (2 ** 61 - 1)
57,193
def vol_rms_diff(arr_4d): """ Return root mean square of differences between sequential volumes Parameters ---------- data : 4D array 4D array from FMRI run with last axis indexing volumes. Call the shape of this array (M, N, P, T) where T is the number of volumes. Returns ---...
57,194
def shift_fields(simulation, names): """ Shift variables to next time step. Examples:: shift_fields(sim, ['u%d', 'up%d', 'upp%d']) shift_fields(sim, ['rho', 'rho_p', 'rho_pp']) Will cause eg rho_pp = rho_p, rho_p = rho. This function can also be used for assigment, since a = b can be w...
57,195
def extract_all_features(imgs_collection, feature_extractor, mode): """ feature extraction of local and global features This function is necessary because it is not possible to extract local features directly with `extract_features`. Instead, if any local features are to be extracted this method calls ...
57,196
def extractRSS_VSIZE(line1, line2, record_number): """ >>> extractRSS_VSIZE("%MSG-w MemoryCheck: PostModule 19-Jun-2009 13:06:08 CEST Run: 1 Event: 1", \ "MemoryCheck: event : VSIZE 923.07 0 RSS 760.25 0") (('1', '760.25'), ('1', '923.07')) """ if ("Run" in line1) and ("Event" in line1): # the first li...
57,197
def cosine_distance(a, b=None): """Compute element-wise cosine distance between `a` and `b`. Parameters ---------- a : tf.Tensor A matrix of shape NxL with N row-vectors of dimensionality L. b : tf.Tensor A matrix of shape NxL with N row-vectors of dimensionality L. Returns ...
57,198
def get_dicom_roi_seqs(input_dir, roi_set_zip_file): """Gets an iterator of ROIs from a .zip file and the list of all DICOM images in the corresponding directory. :param input_dir: path containing the DICOM images :param roi_set_zip_file: path to the RoiSet.zip file containing the regions of interest :r...
57,199