content
stringlengths
22
815k
id
int64
0
4.91M
def install_hook(profile="default"): """Install the hook in a given IPython profile. Args: profile: the IPython profile for which to install the hook. """ hook_source_path = os.path.join(os.path.dirname(__file__), "hook.py") ipython_dir = get_ipython_dir() startup_dir = os.path.join(ip...
12,000
def testhsv(): """Main function to test hsv problems""" from PIL import ImageFilter fnames = sys.argv[1:] fname = fnames[0] i = 0 basemem = procmem() print 'Basemem is %s, using image %s of size %s' % (basemem, fname, Image.open(fname).size) #while 1: for fname in fnames: i +...
12,001
def number_of_qucosa_metadata_in_elasticsearch( host: str = SLUB_ELASTICSEARCH_SERVER_URL, http_auth: Optional[Tuple[str, str]] = None, index_name: str = "fulltext_qucosa", ) -> int: """Return the number of qucosa documents currently available at the SLUB elastic search server. Parameters -----...
12,002
def print_png(filename): """Print a png file from the current viewport Parameters ---------- filename : str The name of the output png file. """ from abaqus import session from abaqusConstants import PNG viewport=session.viewports[session.currentViewportName] session.print...
12,003
def choose(ctx, *choices: str): """Chooses between multiple choices.""" if choices is None: return user = ctx.message.author yield from bot.say('Alright, **@{0}**, I choose: "{1}"'.format(user.display_name, random.choice(choices)))
12,004
def codegen_py(typeit_schema: TypeitSchema, top: bool = True, indent: int = 4) -> Tuple[str, Sequence[str]]: """ :param typ: A type (NamedTuple definition) to generate a source for. :param top: flag to indicate that a toplevel structure is to be generated. When False, a...
12,005
def _tuple_to_string(tup): """ Converts a tuple of pitches to a string Params: * tup (tuple): a tuple of pitch classes, like (11, 10, 5, 9, 3) Returns: * string: e.g., 'et593' """ def _convert(pitch): pitch = mod_12(pitch) if pitch not in (0, 1, 2, 3, 4, 5, 6, 7...
12,006
def update_file_structure(limit=999): """ Opens the hardcoded file containing CIKs to collect data on, and ensures they have the associated directory. :return: None """ # FUTURE Adapt to CIK_List.pkl f = open('objects/ref/CIK_List.txt', 'r') if not os.path.exists('/storage/cik'): ...
12,007
def dashboard(): """Logged in Dashboard screen.""" session["redis_test"] = "This is a session variable." return render_template( "dashboard.jinja2", title="Flask-Session Tutorial.", template="dashboard-template", current_user=current_user, body="You are now logged in!...
12,008
def choose_top_k(scores_flat, config): """Chooses the top-k beams as successors. """ next_beam_scores, word_indices = tf.nn.top_k(scores_flat, k=config.beam_width) return next_beam_scores, word_indices
12,009
def train_valid_test_split(data, proportions='50:25:25'): """ Splits the data into 3 parts - training, validation and test sets :param proportions: proportions for the split, like 2:1:1 or 50:30:20 :param data: preprocessed data :return: X_train, Y_train, target_rtns_train, X_valid, Y_valid, target_...
12,010
def basis_ders_on_quad_grid(knots, degree, quad_grid, nders, normalization): """ Evaluate B-Splines and their derivatives on the quadrature grid. If called with normalization='M', this uses M-splines instead of B-splines. Parameters ---------- knots : array_like Knots sequence. de...
12,011
def analyze_jumps(jumps): """takes the list of Jump tuples from group_jumps. returns JumpCmp. fails if input is weird (tell me more). """ # todo: more of a decompile, AST approach here? look at uncompyle. if jumps[-1].head is not None: raise BadJumpTable("last jump not an else") if len(jumps) < 3: raise Bad...
12,012
def create_notification_handler(actor, recipient, verb, **kwargs): """ Handler function to create a Notification instance. :requires: :param actor: User instance of that user who makes the action. :param recipient: User instance, a list of User instances or string 'global' defi...
12,013
def data(*args, **kwargs): """ The HTML <data> Element links a given content with a machine-readable translation. If the content is time- or date-related, the <time> must be used. """ return el('data', *args, **kwargs)
12,014
def process_dir(dir, doc_type = 'Annual Return', parallel = False): """ Process all document directories in a directory. Parameters ---------- dir : str Relative path to directory containing the document directories doc_type : str Type of documents (default = 'Annual Return') ...
12,015
def key_I(buf, input_line, cur, count): """Move cursor to first non-blank character and start Insert mode. See Also: `key_base()`. """ pos, _, _ = motion_carret(input_line, cur, 0) set_cur(buf, input_line, pos) set_mode("INSERT")
12,016
def get_crops(nodules, fmt='raw', nodule_shape=(32, 64, 64), batch_size=20, share=0.5, histo=None, variance=(36, 144, 144), hu_lims=(-1000, 400), **kwargs): """ Get pipeline that performs preprocessing and crops cancerous/non-cancerous nodules in a chosen proportion. Parameters ----------...
12,017
def get_dict_from_args(args): """Extracts a dict from task argument string.""" d = {} if args: for k,v in [p.strip().split('=') for p in args.split(',')]: d[k] = v return d
12,018
def plot_mean_feature_impact( explanations, features_name=None, max_display=None, ): """ The same than plot_feature_importance but we will consider the mean explanation value grouped by feature. A more informative plot is the summary_plot_tabular. """ # sanitize explanations to numpy...
12,019
def multi_area_propagation_gpu(input_domain, net_model, thread_number=32): """ Propagation of the input domain through the network to obtain the OVERESTIMATION of the output bound. The process is performed applying the linear combination node-wise and the necessary activation functions. The process is on GPU, com...
12,020
def kernel(): """Create a ipykernel conda environment separate from this test environment where jupyter console is installed. The environments must be separate otherwise we cannot easily check if kernel start is activating the environment or if it was already active when the test suite started. ...
12,021
def opensslCmsSignedDataCreate( conveyedInfoFile, cert, privateKey ): """Create a signed CMS encoded object given a conveyed-info file and base64 encode the response.""" opensslCmdArgs = [ "openssl", "cms", "-sign", "-in", conveyedInfoFile, "-signer", cert, "-inkey",...
12,022
def auth_error_handler() -> None: """Handle authorization error. Raises an exception that will be handled by Flask-RESTPlus error handling. """ raise UnauthorizedException('Invalid credentials.')
12,023
def compute_kv(config): """Parse log data and calling draw""" result = {} for _cfg in config['data']: data = data_parser.log_kv(_cfg['path'], _cfg['phase'], _cfg['keys']) # clip from start idx if 'start_iter' in _cfg: start_idx = 0 for idx, iteration in enumerate(data['iter']): if...
12,024
def cmd_abbreviation(ensoapi, query = None): """ Search for abbreviation meaning """ ws = WebSearchCmd("http://www.urbandictionary.com/define.php?term=%(query)s") ws(ensoapi, query)
12,025
def change_app_header(uri, headers, body): """ Add Accept header for preview features of Github apps API """ headers["Accept"] = "application/vnd.github.machine-man-preview+json" return uri, headers, body
12,026
def fib_fail(n: int) -> int: """doesn't work because it's missing the base case""" return fib_fail(n - 1) + fib_fail(n - 2)
12,027
def get_grad_hook(mod, grad_in, grad_out, mod_name=None, grad_map=None): """ The hook to collect gradient. """ assert isinstance(mod_name, str) assert isinstance(grad_map, dict) assert len(grad_out) == 1 grad_map[mod_name] = grad_out[0]
12,028
def int2str(num, radix=10, alphabet=BASE85): """helper function for quick base conversions from integers to strings""" return NumConv(radix, alphabet).int2str(num)
12,029
def randomize_onesample(a, n_iter=10000, h_0=0, corrected=True, random_seed=None, return_dist=False): """Nonparametric one-sample T test through randomization. On each iteration, randomly flip the signs of the values in ``a`` and test the mean against 0. If ``a`` is two-dimensi...
12,030
def git_get_project( directory: str, token: Optional[str] = None, revisions: Optional[Dict[str, str]] = None ) -> BuiltInCommand: """ Create an Evergreen command to clones the tracked project and check current revision. Also, applies patches if the task was created by a patch build. :param directo...
12,031
def main(args=None): """ec2mc script's entry point Args: args (list): Arguments for argparse. If None, set to sys.argv[1:]. """ if args is None: args = sys.argv[1:] try: # Classes of available commands in the commands directory commands = [ configure_cmd....
12,032
def body_contour(binary_image): """Helper function to get body contour""" contours = find_contours(binary_image) areas = [cv2.contourArea(cnt) for cnt in contours] body_idx = np.argmax(areas) return contours[body_idx]
12,033
def rule_like(rule, pattern): """ Check if JsonLogic rule matches a certain 'pattern'. Pattern follows the same structure as a normal JsonLogic rule with the following extensions: - '@' element matches anything: 1 == '@' "jsonlogic" == '@' [1, 2] == '@' {'+': [1, 2]...
12,034
def apt_repo(module, *args): """run apt-repo with args and return its output""" # make args list to use in concatenation args = list(args) rc, out, err = module.run_command([APT_REPO_PATH] + args) if rc != 0: module.fail_json(msg="'%s' failed: %s" % (' '.join(['apt-repo'] + args), err)) ...
12,035
async def get_data( *, config: Box, region: Region, start: Optional[int] = None, end: Optional[int] = None, ) -> Dict[Any, Any]: """Return a new consumer token.""" lookup = f"awattar.{region.name.lower()}" awattar_config = config[lookup] endpoint = f"{awattar_config.host}{awattar_con...
12,036
def deactivated_equalities_generator(block): """ Generator which returns all deactivated equality Constraint components in a model. Args: block : model to be studied Returns: A generator which returns all deactivated equality Constraint components block """ for c in...
12,037
def get_rasterization_params() -> RasterizationParams: """ Construct the RasterizationParams namedtuple from the static configuration file :return: the rasterization parameters """ if cfg is None: load_cfg() # get rasterization section rasterization_dict = cfg[compute_dsm_tag][...
12,038
def compact(values): """Creates a generator (that can be iterated using next()), from a list of values, avoiding any adjacent duplicates Args: values: Iterator of integer values Returns: A generator without adjacent duplicates """ # check that the iterator is not empty if ...
12,039
def main(): """Make a jazz noise here""" args = get_args() kmers1 = count_kmers(args.file1, args.kmer) kmers2 = count_kmers(args.file2, args.kmer) for common in set(kmers1).intersection(set(kmers2)): print('{:10} {:5} {:5}'.format( common, kmers1.get(common), kmers2.get(common)...
12,040
def rain_attenuation_probability(lat, lon, el, hs=None, Ls=None, P0=None): """ The following procedure computes the probability of non-zero rain attenuation on a given slant path Pr(Ar > 0). Parameters ---------- lat : number, sequence, or numpy.ndarray Latitudes of the receiver points...
12,041
def discover(paths=None): """Get the full list of files found in the registered folders Args: paths (list, Optional): directories which host preset files or None. When None (default) it will list from the registered preset paths. Returns: list: valid .json preset file paths. ...
12,042
def largets_prime_factor(num): """ Returns the largest prime factor of num. """ prime_factors = [] for n in itertools.count(2): if n > num: break if num%n == 0: prime_factors.append(n) while (num%n == 0): num = num/n return max(prime_factors)
12,043
def run(): """ entrypoint """ parser = ArgumentParser( "kimsufi-checker", description="tool to perform actions when Kimsufi availabilty changes", ) parser.add_argument( "-s", "--sleep", metavar="SECONDS", type=int, default=60, help=...
12,044
def delete_md5(md5): """Delete the data of the file that has the MD5 hash.""" file = File.query.filter(File.md5 == md5).one_or_none() schema = FileSchema() result = schema.dump(file) if file is not None: filename = f"{result['file_name']}.{result['file_type']}" if not os.path.exists(...
12,045
def compute_eigenvectors(exx, exy, eyy): """ exx, eyy can be 1d arrays or 2D arrays :param exx: strain component, float or 1d array :param exy: strain component, float or 1d array :param eyy: strain component, float or 1d array :rtype: list """ e1, e2 = np.zeros(np.shape(exx)), np.zeros...
12,046
def name_looks_valid(name: str) -> bool: """ Guesses if a name field is valid. Valid is defined as being at least two words, each beginning with a capital letter and ending with a lowercase letter. :param name: the name to check :return: whether this name is considered valid """ existing_pa...
12,047
def convert_polygons_to_lines(src_polygons, dst_lines, crs=None, add_allone_col=False): """Convert polygons to lines. Arguments: src_polygons {path to geopandas-readable file} -- Filename of the the polygon vector dataset to be converted to lines. dst_lines {[type]} -- Filename whe...
12,048
def format_decimal(amount): """ jinja2 filter function for decimal number treatment """ amt_whole = int(amount) amt_whole_len = len(str(amt_whole)) if amount < 1: amt_str = '{:0.15f}'.format(amount).rstrip("0").rstrip(".") elif amt_whole_len < 4: amt_str = '{:0.3f}'.format(amount).r...
12,049
def remove_special_char(df, col): """Removes special characters such as % and $ from numeric variables and converts them into float""" df[col] = df[col].replace(regex = True, to_replace = r'[^0-9.\-]', value=r'') df[col] = df[col].astype("float") return df[col]
12,050
def getNonlinearInfo(numHiddenLayers, numBinary, unaryPerBinary): """ Generates a 2D list to be used as a nonlinearInfo argument in building an EQL/EQL-div model # Arguments numHiddenLayers: integer, number of hidden layers (i.e. layers including nonlinear keras layer components) ...
12,051
def construct_magmad_gateway_payload(gateway_id: str, hardware_id: str) -> types.Gateway: """ Returns a default development magmad gateway entity given a desired gateway ID and a hardware ID pulled from the hardware secrets. Args: gateway_id: Desired gateway...
12,052
def endpoint(fun): """ REST HTTP method endpoints should use this decorator. It converts the return value of the underlying method to the appropriate output format and sets the relevant response headers. It also handles RestExceptions, which are 400-level exceptions in the REST endpoints, AccessExce...
12,053
def test_secrets_provider_get_expired(mock_name, mock_value, config): """ Test SecretsProvider.get() with a cached but expired value """ # Create a new provider provider = parameters.SecretsProvider(config=config) # Inject value in the internal store provider.store[(mock_name, None)] = Exp...
12,054
def gene_annotations(corpus_path, annotation_path, mer_path): """ Creates a gene annotation file for each article in the corpus :param corpus_path: article corpus path :param mer_path: mer data path :param annotation_path: genes annotation path :return: gene annotation file for each article in the ...
12,055
def script_rename_number(config): """ The scripting version of `rename_number`. This function applies the rename to the entire directory. It also adds the tags to the header file of each fits. Parameters ---------- config : ConfigObj The configuration object that is to be used for...
12,056
def jasper10x4(**kwargs): """ Jasper 10x4 model from 'Jasper: An End-to-End Convolutional Neural Acoustic Model,' https://arxiv.org/abs/1904.03288. Parameters: ---------- pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.chain...
12,057
def swap(lst, idx1, idx2): """ >>> swap([0, 1, 2], 0, 1) [1, 0, 2] >>> swap([0, 1, 2], 0, 0) [0, 1, 2] """ # print("Swapping [{}, {}] from {}".format(idx1, idx2, lst)) lst[idx1], lst[idx2] = lst[idx2], lst[idx1] # print("resulting to {}".format(lst)) return lst
12,058
def drawLine(queryDef): """画分割线 Args: queryDef: 查询定义 """ formatStr = "" valueList = [] for title in queryDef.titleList: colDef = queryDef.tableCols[title] size = colDef.size + 2 formatStr += ('+' + formatString("string", size, False)) valueList.a...
12,059
def debug_keytester() -> None: """Show a keytester widget.""" global _keytester_widget if (_keytester_widget and not sip.isdeleted(_keytester_widget) and _keytester_widget.isVisible()): _keytester_widget.close() else: _keytester_widget = miscwidgets.KeyTesterWidge...
12,060
def substring_index(column, delim=' ', cnt=1): """ Returns the substring from string ``column`` before ``cnt`` occurrences of the delimiter ``delim``. If ``cnt`` is positive, everything the left of the final delimiter (counting from left) is returned. If ``cnt`` is negative, every to the right of the fi...
12,061
def askPrize(mon: int) -> str: """ Args : n:欲查詢的期別 Returns: 查詢結果字串 """ (date, data) = initData(mon) date = f"{date}月\n" ssp_prize = f"特別獎:{data[0]}\n" sp_prize = f"特獎:{data[1]}\n" first_prize = f"頭獎:{data[2]}、{data[3]}、{data[4]}\n" six_prize = f"六獎:{data[2][5:]}、{...
12,062
def maintain_all(delta_day=1): """ 维护所有的mysql表的分区 """ storage_rt_list = model_manager.get_storage_rt_objs_by_type(MYSQL) count = 0 start_time_ts = time.time() mysql_conns = {} maintain_failed_rts = [] # 避免此接口执行时间跨天,导致添加的分区发生变化。 add_date = util.get_date_by_diff(delta_day) add_...
12,063
def get_letters_df(letters_dict_pickle): """Get the letters Pandas Dataframe Parameters ---------- letters_dict_pickle: string Path to the dict with the letters text Returns ------- Pandas DataFrame Pandas DataFrame with a columns with the tokens """ with open(lette...
12,064
def lorenzmod1(XYZ, t, a=0.1, b=4, dz=14, d=0.08): """ The Lorenz Mod 1 Attractor. x0 = (0,1,0) """ x, y, z = XYZ x_dt = -a * x + y**2 - z**2 + a * dz y_dt = x * (y - b * z) + d z_dt = -z + x * (b * y + z) return x_dt, y_dt, z_dt
12,065
def binomial_p(x, n, p0, reps=10**5, alternative='greater', keep_dist=False, seed=None): """ Parameters ---------- sample : array-like list of elements consisting of x in {0, 1} where 0 represents a failure and 1 represents a seccuess p0 : int hypothesized number of successes in...
12,066
def test_docs_by_author1(flask_client, user4): """docs_by_author() displays appropriate docs if user logged in.""" response = flask_client.get("/all/author/2", follow_redirects=True) assert ( b"First user doc" in response.data and b"Third user doc" in response.data and b"Second user ...
12,067
def is_guild_owner() -> commands.check: """ Returns True under the following conditions: - **ctx.author** is the owner of the guild where this command was called from """ def predicate(ctx): if ctx.guild is None: raise commands.NoPrivateMessage('This command can only be used...
12,068
def round_grade(grade: int) -> int: """ Round the grade according to policy. Parameters ---------- grade: int Raw grade. Returns ------- rounded_grade: int Rounded grade. """ if grade < 38: rounded_grade = grade else: closest_multiple_5 = (gr...
12,069
def patch_indecies(i_max: int, j_max: int, ps: int, pstr: int): """ Given the sizes i_max and j_max of an image, it extracts the top-left corner pixel location of all the patches of size (ps,ps) and distant "pstr" pixels away from each other. If pstr < ps, the patches are overlapping. Input: ...
12,070
def model_fn(): """ Defines a convolutional neural network for steering prediction. """ model = Sequential() # Input layer and normalization model.add(InputLayer(input_shape=(20, 80, 1))) model.add(Lambda(lambda x: (x / 255.0) - 0.5)) # Convolutional layer 1 model.add(Conv2D(filter...
12,071
def authenticate(request): """Return the user model instance associated with the given request If no user is retrieved, return an instance of `AnonymousUser` """ token, _ = get_token_from_request(request) jwt_info = { 'token': token, 'case': TokenCase.OK, 'payload': None, ...
12,072
def test_get_settings(config): """ Test function `get_settings` to get application settings. """ settings = utils.get_settings() # Settings should be a non empty dictionary assert isinstance(settings, dict) assert settings > 0
12,073
def _urpc_test_func_2(buf): """! @brief u-RPC variable length data test function. @param buf A byte string buffer @return The same byte string repeated three times """ return buf*3
12,074
def test_normal(): """Test divide_sizes.""" # 8 / 2 res = divide_sizes(8, 2) assert res == [4, 4] # 8 / 3 res = divide_sizes(8, 3) assert res == [3, 3, 2] # 7 / 3 res = divide_sizes(7, 3) assert res == [3, 2, 2] # 1 / 3 res = divide_sizes(1, 3) assert res == [1, 0,...
12,075
def main(): """ Use Netmiko to connect to each of the devices. Execute 'show version' on each device. Record the amount of time required to do this """ start_time = datetime.now() for device in devices: print() print('#' * 40) output = show_version(device) print(o...
12,076
def infer_data_type(data_container: Iterable): """ For a given container of data, infer the type of data as one of continuous, categorical, or ordinal. For now, it is a one-to-one mapping as such: - str: categorical - int: ordinal - float: continuous There may be better ways that ...
12,077
def test_loader(): """Test ChunkRequest and the ChunkLoader.""" if not config.async_loading: return # temporary until we add the @async_only pytest mark layer = _create_layer() layer_key = LayerKey.from_layer(layer, (0, 0)) key = ChunkKey(layer_key) shape = (64, 32) transpose_shap...
12,078
def test_automatic_label_suffix(setup): """ Test %% replacement with single field Sets - Error situation. Fields email_x should not be blank. Merely inducing an error to assert for correct field name replacement. """ post = deepcopy(setup) post.add(u'email_1', '') dynamic_form = WTForms...
12,079
def Preprocess( src: str, cflags: typing.List[str], timeout_seconds: int = 60, strip_preprocessor_lines: bool = True, ): """Run input code through the compiler frontend to inline macros. This uses the repository clang binary. Args: src: The source code to preprocess. cflags: A list of flags to b...
12,080
def mmgen2torchserver(config_file: str, checkpoint_file: str, output_folder: str, model_name: str, model_version: str = '1.0', model_type: str = 'unconditional', force: bool = False): ...
12,081
def versionString(version): """Create version string.""" ver = [str(v) for v in version] numbers, rest = ver[:2 if ver[2] == '0' else 3], ver[3:] return '.'.join(numbers) + '-'.join(rest)
12,082
def any(iterable, pred): """Returns True if ANY element in the given iterable is True for the given pred function""" warnings.warn( "pipe.any is deprecated, use the builtin any(...) instead.", DeprecationWarning, stacklevel=4, ) return builtins.any(pred(x) for x in iterable)
12,083
def loadRatings(ratingstablename, ratingsfilepath, openconnection): """ Inserting Ratings.dat into the Database """ with openconnection.cursor() as cursor: sqlDropCommand = "DROP TABLE IF EXISTS {}".format(ratingstablename) sqlCreateCommand = ''' CREATE TABLE {} ( userid INT NOT NULL...
12,084
def main(): """ Main entry of program. Set arguments for argument parser, loads the settings and searches current directory for compilable tex files. At the end prints help or calls the task selector function to perform one of the tasks. """ parser = ap.ArgumentParser() root_logger = logging...
12,085
def get_parser(): """ Parser of nuth kaab independent main TODO: To clean with main. Keep independent main ? """ parser = argparse.ArgumentParser( os.path.basename(__file__), description="Universal co-registration method " "presented in Nuth & Kaab 2011." "NB : 1) It ...
12,086
def build_prev_df_n( dispositions) -> pd.DataFrame: """Build admissions dataframe from Parameters.""" days = np.array(range(0, n_days)) data_dict = dict( zip( ["day", "hosp", "icu", "vent"], [days] + [disposition for disposition in dispositions], ) ) proj...
12,087
def main() -> VDOMNode: """Main entry point.""" vdom = html("<{Heading} />") return vdom
12,088
def GT(x=None, y=None): """ Compares two values and returns: true when the first value is greater than the second value. false when the first value is less than or equivalent to the second value. See https://docs.mongodb.com/manual/reference/operator/aggregation/gt/ for more details ...
12,089
def pymongo_formatter(credentials): """Returns a DSN for a pymongo-MongoDB connection. Note that the username and password will still be needed separately in the constructor. Args: credentials (dict): The credentials dictionary from the relationships. Returns: (string) A f...
12,090
def test_faulty_tessellation(): """Pass bad arguments to the tessellation.""" with pytest.raises(pqca.exceptions.IrregularCellSize): pqca.tessellation.Tessellation([[0], [1, 2]]) with pytest.raises(pqca.exceptions.PartitionUnevenlyCoversQubits): pqca.tessellation.Tessellation([[0], [0]]) ...
12,091
def sigma_disp_over_vcirc(gal, R=None): """The velocity dispersion over circular velocity computed at R=x*Rs [km/s]. Isotropic NFW is assumed. :param R: radius [kpc] :param gal: galaxy object """ # get Rs (rho, rs, c) = reconstruct_density_DM(gal, DM_profile='NFW') # make array of r, pre...
12,092
def repack_model( inference_script, source_directory, dependencies, model_uri, repacked_model_uri, sagemaker_session, kms_key=None, ): """Unpack model tarball and creates a new model tarball with the provided code script. This function does the following: - uncompresses model ta...
12,093
def filters(param: str, default_value: str, base_key: str, key_manager: KeyManager) -> list: """Filter combo box selector for parameter""" update_type = '|filters|' row = combo_row(param, default_value, base_key, key_manager, update_type) return row
12,094
def get_scanner(fs_id): """ get scanner 3T or 1.5T""" sc = fs_id.split("_")[2] if sc in ("15T", "1.5T", "15t", "1.5t"): scanner = "15T" elif sc in ("3T", "3t"): scanner = "3T" else: print("scanner for subject " + fs_id + " cannot be identified as either 1.5T or 3T...") ...
12,095
def _find_query_rank(similarities, library_keys, query_keys): """tf.py_func wrapper around _find_query_rank_helper. Args: similarities: [batch_size, num_library_elements] float Tensor. These are not assumed to be sorted in any way. library_keys: [num_library_elements] string Tensor, where each column...
12,096
def random_adjust_brightness(image, max_delta=0.2, seed=None): """Randomly adjusts brightness. """ delta = tf.random_uniform([], -max_delta, max_delta, seed=seed) image = tf.image.adjust_brightness(image / 255, delta) * 255 image = tf.clip_by_value(image, clip_value_min=0.0, clip_value_max=255.0) re...
12,097
def get_assign_ops_and_restore_dict(filename, restore_all=False): """Helper function to read variable checkpoints from filename. Iterates through all vars in restore_all=False else all trainable vars. It attempts to match variables by name and variable shape. Returns a possibly empty list of assign_ops, and a p...
12,098
def log_creations(model, **extra_kwargs_for_emit): """ Sets up signal handlers so that whenever an instance of `model` is created, an Entry will be emitted. Any further keyword arguments will be passed to the constructor of Entry as-is. As a special case, if you specify the sentinel value `INSTANCE` as...
12,099