content
stringlengths
22
815k
id
int64
0
4.91M
def plot_sleep_per_weekday(title, ylabel, keys, values, counter, color_list): """ creates a bar chart for the given data :param title: title to display :param ylabel: ylabel text :param keys: names for the bars :param values: values to create bars for :param user: the user which we are visua...
5,326,300
def binary_seg_loss(loss): """ Chooses the binary segmentation loss to use depending on the loss name in parameter :param loss: the type of loss to use """ if loss == 'focal': return BinaryFocalLoss() else: return tf.keras.losses.BinaryCrossentropy()
5,326,301
def time_test_csv( ID, CSV_TIMES, SCALE_PARAM, GTNX, GRAPH_TYPE, graph, path_costs, cost_sum, dist, time_pipeline, notes ): """ Prepare current data for time logs csv file :param CSV_TIMES: output file :params: all parameters to save in the csv """ # get scale factor and number of nonzer...
5,326,302
def get_config_file(): """ Return the loaded config file if one exists. """ # config will be created here if we can't find one new_config_path = os.path.expanduser('~/dagobahd.yml') config_dirs = ['/etc', os.path.expanduser('~/dagobah/dagobah/daemon/')] config_filenames = ['dago...
5,326,303
def bostock_cat_colors(color_sets = ["set3"]): """ Get almost as many categorical colors as you please. Get more than one of the color brewer sets with ['set1' , 'set2'] Parameters ---------- sets : list list of color sets to return valid options are (set1, set2, set3, paste...
5,326,304
def SaveClose(): """Close all scene.""" SaveCloseMatplotlib() SaveCloseMlab()
5,326,305
def run_docstyle_check(repository): """Run PyDocsStyle checker against the selected repository.""" command = "pushd {repo};./check-docstyle.sh > ../{repo}.pydocstyle.txt;popd".format( repo=repository) os.system(command)
5,326,306
def PruneXTraceJSONFiles(request_types): """ Prune a folder of xtrace files to remove garbace collection traces and a few others that do not correspond to the various request types @params request_types: the allowable request types for this set of traces. """ # start statistics start_time = ...
5,326,307
def bbpssw_gates_and_measurement_bob(q1, q2): """ Performs the gates and measurements for Bob's side of the BBPSSW protocol :param q1: Bob's qubit from the first entangled pair :param q2: Bob's qubit from the second entangled pair :return: Integer 0/1 indicating Bob's measurement outcome """ ...
5,326,308
def fiber_array( n: int = 8, pitch: float = 127.0, core_diameter: float = 10, cladding_diameter: float = 125, layer_core: Tuple[int, int] = gf.LAYER.WG, layer_cladding: Tuple[int, int] = gf.LAYER.WGCLAD, ) -> Component: """Returns a fiber array .. code:: pitch <-> ...
5,326,309
def check_flags(): """Additional logic to make sure flags are set appropriately.""" if FLAGS.customized_model is not None: if (not tf.compat.v1.gfile.Exists(FLAGS.customized_model + '.data-00000-of-00001') or not tf.compat.v1.gfile.Exists(FLAGS.customized_model + '....
5,326,310
def delete(movie_id): """ deletes the movie from the database :param movie_id: id to delete :return: index file """ movie_to_delete_id = Movie.query.get(movie_id) db_session.delete(movie_to_delete_id) db_session.commit() return redirect(url_for('home'))
5,326,311
def one_vector_block_diagonal(num_blocks: int, vector_length: int) -> Tensor: """Computes a block diagonal matrix with column vectors of ones as blocks. Associated with the mathematical symbol :math:`E`. Example: :: one_vector_block_diagonal(3, 2) == tensor([ [1., 0., ...
5,326,312
def get_cli_args(): """ :return: argparse.Namespace with command-line arguments from user """ args = get_main_pipeline_arg_names().difference({ 'output', 'ses', 'subject', 'task', WRAPPER_LOC[2:].replace('-', '_') }) tasks = ('SST', 'MID', 'nback') parser = get_pipeline_cli_a...
5,326,313
def list_all_assets(organization_id): """Demonstrate listing and printing all assets.""" i = 0 # [START securitycenter_list_all_assets] from google.cloud import securitycenter client = securitycenter.SecurityCenterClient() # organization_id is the numeric ID of the organization. # organizat...
5,326,314
def _0_to_empty_str(dataframe: pd.DataFrame, column_data_type: dict): """ 데이터가 str인 column에 들어있는 0을 '' 로 바꾸어 준다. column_data_type 에서 value가 'str' 인 column 만 바꾸어 준다. """ for column, datatype in column_data_type.items(): if datatype == "str": dataframe[column].replace("0", "", inpl...
5,326,315
async def several_static_pools(fixt_controller, count: int = 5): """Создать несколько статических пулов.""" pool_main_resources = await get_resources_for_pool_test() controller_id = pool_main_resources["controller_id"] resource_pool_id = pool_main_resources["resource_pool_id"] context = await get_au...
5,326,316
def set_proxies(): """Set proxies to allow downloading of external URLs.""" os.environ["HTTP_PROXY"] = "http://fwdproxy:8080" os.environ["HTTPS_PROXY"] = "http://fwdproxy:8080" os.environ["http_proxy"] = "fwdproxy:8080" os.environ["https_proxy"] = "fwdproxy:8080"
5,326,317
def _predict(rel): """ Predicts the betrayal probabilities and returns them as an inference.Output object. """ return inference.predict(rel)
5,326,318
def evaluate_exams(request, exam_id): """ Request-Methods :POST Request-Headers : Authorization Token Request-Body: Student-Solution -> JSON Response: "student_name" -> str, "teacher_name" -> str, "batch" -> str, "marks" -> str, "exam...
5,326,319
def _accumulated_penalty_energy_fw(energy_to_track, penalty_matrix, parallel): """Calculates acummulated penalty in forward direction (t=0...end). `energy_to_track`: squared abs time-frequency transform `penalty_matrix`: pre-calculated penalty for all potential jumps between two frequ...
5,326,320
def rot90(m, k=1, axis=2): """Rotate an array k*90 degrees in the counter-clockwise direction around the given axis This differs from np's rot90 because it's 3D """ m = np.swapaxes(m, 2, axis) m = np.rot90(m, k) m = np.swapaxes(m, 2, axis) return m
5,326,321
def get_pads(onnx_node): # type: (NodeWrapper) -> Tuple[int, int, int] """ Get padding values for the operation described by an ONNX node. If `auto_pad` attribute is specified as SAME_UPPER or SAME_LOWER, or VALID values are calculated. Otherwise values are taken from the `pads` attribute. `pads`...
5,326,322
def get_changelog_version() -> Optional[str]: """ Return latest version from changelog.txt file. """ version: Optional[str] = None root_dir = hgit.get_client_root(super_module=False) changelog_file = os.path.join(root_dir, "changelog.txt") hdbg.dassert_file_exists(changelog_file) changel...
5,326,323
def from_dict(transforms): """Deserializes the transformations stored in a dict. Supports deserialization of Streams only. Parameters ---------- transforms : dict Transforms Returns ------- out : solt.core.Stream An instance of solt.core.Stream. """ if not...
5,326,324
def create_mp_pool(nproc=None): """Creates a multiprocessing pool of processes. Arguments --------- nproc : int, optional number of processors to use. Defaults to number of available CPUs minus 2. """ n_cpu = pathos.multiprocessing.cpu_count() if nproc is None: ...
5,326,325
def subpixel_edges(img, threshold, iters, order): """ Detects subpixel features for each pixel belonging to an edge in `img`. The subpixel edge detection used the method published in the following paper: "Accurate Subpixel Edge Location Based on Partial Area Effect" http://www.sciencedirect.com/sci...
5,326,326
def arrays(hyperchunks, array_count): """Iterate over the arrays in a set of hyperchunks.""" class Attribute(object): def __init__(self, expression, hyperslices): self._expression = expression self._hyperslices = hyperslices @property def expression(self): return self._expression ...
5,326,327
def ne(x: Union[DNDarray, float, int], y: Union[DNDarray, float, int]) -> DNDarray: """ Returns a :class:`~heat.core.dndarray.DNDarray` containing the results of element-wise rich comparison of non-equality between values from two operands, commutative. Takes the first and second operand (scalar or :class:`...
5,326,328
def iter_paired_end_filenames(sample_name_delims, sample_names, patterns, filenames): """Print paired end files to stdout, one pair per line. Print unpaired files to stderr. """ tbl = {} for filename in filenames: filename = filename.strip() try: sample_name, end = get_s...
5,326,329
def main(samples = 1195191, cores = -1): """ This function loads data as a pandas dataframe, calculates mean and variance of the sentiment scores per week and month. Lastly, it saves the figures. Inputs: samples, default: 50000: description: int, a number of titles to be sampled (max 1 milion) cores, defau...
5,326,330
def _quote_embedded_quotes(text): """ Replace any embedded quotes with two quotes. :param text: the text to quote :return: the quoted text """ result = text if '\'' in text: result = result.replace('\'', '\'\'') if '"' in text: result = result.replace('"', '""') ret...
5,326,331
def exp2(x): """Calculate 2**x""" return 2 ** x
5,326,332
def test_update_metadata_family_does_not_exist(db_session, make_workspace, upload_file, mocker): """Updating metadata of a family not present in a workspace should fail""" mocker.patch('flask_principal.Permission.can', return_value=True) workspace = make_workspace(families={'base': 0, 'existing': 0}) fi...
5,326,333
def play(): """Play page.""" ticket_name = request.cookies.get('ticket_name') ticket = None game = get_game() new_ticket = True if ticket_name: ticket = Ticket.get_by_name(ticket_name) new_ticket = ticket and ticket.game != game.id if new_ticket: ticket = Ticket.cre...
5,326,334
def count_search_results(idx, typ, query, date_range, exclude_distributions, exclude_article_types): """Count the number of results for a query """ q = create_query(query, date_range, exclude_distributions, exclude_article_types) #print q return _es()....
5,326,335
def ifft(data: np.ndarray) -> np.ndarray: """ Perform inverse discrete Fast Fourier transform of data by conjugating signal. Arguments: data: frequency data to be transformed (np.array, shape=(n,), dtype='float64') Return: result: Inverse transformed data """ n = len(data) result =...
5,326,336
def archived_minute(dataSet, year, month, day, hour, minute): """ Input: a dataset and specific minute Output: a list of ride details at that minute or -1 if no ride during that minute """ year = str(year) month = str(month) day = str(day) #Converts hour and minute into 2 digit integers (that are strings) ho...
5,326,337
def Rq(theta, vect): """Returns a 3x3 matrix representing a rotation of angle theta about vect axis. Parameters ---------- theta: float, rotation angle in radian vect: list of float or array, vector about which the rotation happens """ I = np.matrix(np.identity(3)) ...
5,326,338
def ExpsMaintPol(): """Maintenance expense per policy""" return asmp.ExpsMaintPol.match(prod, polt, gen).value
5,326,339
def inputRead(c, inps): """ Reads the tokens in the input channels (Queues) given by the list inps using the token rates defined by the list c. It outputs a list where each element is a list of the read tokens. Parameters ---------- c : [int] List of token consumption rates. inp...
5,326,340
def _split_schema_abstract(s): """ split the schema abstract into fields >>> _split_schema_abstract("a b c") ['a', 'b', 'c'] >>> _split_schema_abstract("a(a b)") ['a(a b)'] >>> _split_schema_abstract("a b[] c{a b}") ['a', 'b[]', 'c{a b}'] >>> _split_schema_abstract(" ") [] ...
5,326,341
def myfn(n): """打印hello world 每隔一秒打印一个hello world,共n次 """ if n == 1: print("hello world!") return else: print("hello world!") return myfn(n - 1)
5,326,342
def name(ea, **flags): """Return the name defined at the address specified by `ea`. If `flags` is specified, then use the specified value as the flags. """ ea = interface.address.inside(ea) # figure out what default flags to use fn = idaapi.get_func(ea) # figure out which name function to...
5,326,343
def estimate_distance( row: pd.DataFrame, agent_x: float, agent_y: float ): """ Side function to estimate distance from AGENT to the other vehicles This function should be applied by row Args: row: (pd.DataFrame) agent_x: (float) x coordinate of agent ...
5,326,344
def spinpol_bands(kpath, eigenvalues_up, eigenvalues_dn, backend=None, data=None, **kwargs): """ Plot the provided data for a bandstructure (spin-polarized) Non-weighted, weighted, as a line plot or scatter plot, color-mapped or fixed colors are all possible options :param kpath: data for the kpoin...
5,326,345
def test_init_method(): """ Test constructor """ name = 'Hallway' position = 'Entrance' inventory = ['Paper', 'Cage', 'Freshman Badge'] main_character = Character(name, position, inventory) assert main_character.name == name assert main_character.position == position assert main_...
5,326,346
def WriteSurfaceElectrostaticsView(Mode, OutFH, SelectionObjectName, ElectrostaticsGroupName, ElectrostaticsGroupMembers, DisplayAs = None, SurfaceCavityMode = 2): """Write out PML for viewing surface electrostatics. """ if len(ElectrostaticsGroupMembers) == 5: Name, ContactPotentialName, MapName, Lege...
5,326,347
def test_access_db_type_url_down(): """ :return: """ httpretty.enable() httpretty.reset() conftest.mock_user_perm("admin") conftest.mock_app_perm("bk_dataweb") conftest.mock_create_data_id() conftest.mock_get_data_id("db") res = post("/v3/access/deploy_plan/", param) assert...
5,326,348
def test_markov_word_chain_builder(): """Test typical use of the WordChainBuilder markov chain class.""" input_sequence = ( 'PIKARD', 'Q', 'PIKARD', 'DORF', 'PIKARD', 'Q', 'ROKER', 'Q', 'PIKARD' ) expected_probabilities = { 'PIKARD': [('Q', 2.0 / 3), ('DORF', 1.0 / 3)], 'Q': [('P...
5,326,349
def _verify_metadata(metadata, args): """ <Purpose> Internal method to verify link or layout signatures. <Arguments> metadata: Metablock object (contains Link or Layout object) args: see argparser <Exceptions> SystemExit(0) if verification passes SystemExit(1) if ve...
5,326,350
def valid_config_and_get_dates(): """ 校验配置文件的参数,并返回配置文件的预约疫苗日期 :return: """ if config.global_config.getConfigSection("cookie") == "": raise Exception("请先配置登陆后的 cookie,查看方式请查看 README.MD") if config.global_config.getConfigSection("date") == "": raise Exception("请先配置登陆后的 预约日期") ...
5,326,351
def check_internet_connection(): """Checks if there is a working internet connection.""" url = 'http://www.google.com/' timeout = 5 try: _ = requests.get(url, timeout=timeout) return True except requests.ConnectionError as e: return False return False
5,326,352
def wall_filter(points, img): """ Filters away points that are inside walls. Works by checking where the refractive index is not 1. """ deletion_mask = img[points[:, 0], points[:, 1]] != 1 filtered_points = points[~deletion_mask] return filtered_points
5,326,353
def navigateResults(results): """Navigate all links, returning a list contaning the ulrs and corresponding pages. results:[String] - List with links to be visited Return: {list}[{tuple}({String}url, {String}content)]""" global BASE_ADDR ret = [] for i in results: page = requests....
5,326,354
def _get_matching_signature(oper, args): """ Search the first operation signature matched by a list of arguments Args: oper: Operation where searching signature args: Candidate list of argument expressions Returns: Matching signature, None if not found """ # Search correspon...
5,326,355
def format_size(num: int) -> str: """Format byte-sizes. :param num: Size given as number of bytes. .. seealso:: http://stackoverflow.com/a/1094933 """ for x in ['bytes', 'KB', 'MB', 'GB']: if num < 1024.0 and num > -1024.0: return "%3.1f%s" % (num, x) num /= 1024.0 ...
5,326,356
def annotate_task(task_id, note): """Annotate task with task_id with note string""" uuid = Popen(['task', task_id, 'uuids'], stdout=PIPE).stdout.read().strip().decode('utf-8') call(['task', task_id, 'annotate', '--', 'email:', 'Notes']) notes_dir = get_notes_dir() note_file = os.path.join(notes_di...
5,326,357
def __sort_merge(arr: [], start: int, end: int): """ 二路归并:分割数组为两部分,分别对这两部分排序,然后将两个有序数组合并 """ # 结束条件,当分割部分只剩一个元素时已有序,结束分割 if end - start <= 1: return mid = (start + end) // 2 __sort_merge(arr, start, mid) __sort_merge(arr, mid, end) # 递归合并 __merge_array(arr, start, mid, e...
5,326,358
def hub_payload(hub): """Create response payload for a hub.""" if hasattr(hub, "librarySectionID"): media_content_id = f"{HUB_PREFIX}{hub.librarySectionID}:{hub.hubIdentifier}" else: media_content_id = f"{HUB_PREFIX}server:{hub.hubIdentifier}" payload = { "title": hub.title, ...
5,326,359
def _decrypt(secret_key, data): """Decrypt data using the secret_key""" print(Encryptor(secret_key).decrypt_string(data))
5,326,360
def roq_transform(pressure, loading): """Rouquerol transform function.""" return loading * (1 - pressure)
5,326,361
def test_report_properties(): """``Report`` objects have statistically evaluated properties.""" report = Report(verbs=['GET', 'POST'], status_codes=['20', 404]) report.add( path='/foo/bar', verb='GET', status=205, time=0.1, upstream_time=0.09, body_bytes=255) ...
5,326,362
def _cms_inmem(file_names): """ Computes mean and image_classification deviation in an offline fashion. This is possible only when the dataset can be allocated in memory. Parameters ---------- file_names: List of String List of file names of the dataset Returns ------- mean ...
5,326,363
def ddphi_spherical_zm (dd, ps_zm, r_e, lat, time_chunk=None ): """ This function calculates the gradient in meridional direction in a spherical system It takes and returns xarray.DataArrays inputs: dd data xarray.DataArray with (latitude, time, level) or (latitude, time), or combinations...
5,326,364
def kill_port(port: int): """ Kill a process which listening to a port """ os.system('fuser -k {}/tcp'.format(port)) pass
5,326,365
def process_group_magmom_comp( name=None, group=None, write_atoms_objects=False, verbose=False, ): """ """ #| - process_group_magmom_comp # ##################################################### group_w_o = group # ##################################################### out...
5,326,366
def precompute_dgmatrix(set_gm_minmax,res=0.1,adopt=True): """Precomputing MODIT GRID MATRIX for normalized GammaL Args: set_gm_minmax: set of gm_minmax for different parameters [Nsample, Nlayers, 2], 2=min,max res: grid resolution. res=0.1 (defaut) means a grid point per digit adopt: i...
5,326,367
def get_image_urls(ids): """function to map ids to image URLS""" return [f"http://127.0.0.1:8000/{id}" for id in ids]
5,326,368
def partition(n: int) -> int: """Pure Python partition function, ported to Python from SageMath. A000041 implemented by Peter Luschny. @CachedFunction def A000041(n): if n == 0: return 1 S = 0; J = n-1; k = 2 while 0 <= J: T = A000041(J) S = S+T if is_odd(k//2) else ...
5,326,369
def port_to_host_int(port: int) -> int: """Function to convert a port from network byte order to little endian Args: port (int): the big endian port to be converted Returns: int: the little endian representation of the port """ return ntohs(port)
5,326,370
def inv_median(a): """ Inverse of the median of array a. This can be used as the `scale` argument of ccdproc.combine when combining flat frames. See CCD Data Reduction Guide Sect. 4.3.1 """ return 1 / np.median(a)
5,326,371
def mpdisted(dask_client, T_A, T_B, m, percentage=0.05, k=None, normalize=True): """ Compute the z-normalized matrix profile distance (MPdist) measure between any two time series with a distributed dask cluster The MPdist distance measure considers two time series to be similar if they share many s...
5,326,372
def validate_input(helper, definition): """Implement your own validation logic to validate the input stanza configurations""" # This example accesses the modular input variable # client_account = definition.parameters.get('client_account', None) if(definition.parameters.get('client_account', None) is No...
5,326,373
def test_describe_enclaves(init_resources): # pylint: disable=unused-argument """Test describe enclaves does what we expect it to do.""" result = describe_enclaves_ok() result_json = json.loads(result.stdout.decode('UTF-8')) assert not result_json result = run_enclave_ok(SAMPLE_EIF, "1028", "2") ...
5,326,374
def naive_pipeline_2() -> Pipeline: """Generate pipeline with NaiveModel(2).""" pipeline = Pipeline(model=NaiveModel(2), transforms=[], horizon=7) return pipeline
5,326,375
def caption_image_batch(encoder, decoder, images, word_map, device, max_length): """ Reads an image and captions it with beam search. :param encoder: encoder model :param decoder: decoder model :param image: image :param word_map: word map :param beam_size: number of sequences to consider at...
5,326,376
def wasserstein_distance(p, q, C): """Wasserstein距离计算方法, p.shape=(m,) q.shape=(n,) C.shape=(m,n) p q满足归一性概率化 """ p = np.array(p) q = np.array(q) A_eq = [] for i in range(len(p)): A = np.zeros_like(C) A[i,:] = 1.0 A_eq.append(A.reshape((-1,))) for i in ...
5,326,377
def median_cutoff_points(ventricular_rate, ponset, toffset): """Calculate the median cutoff start and end points""" ponset = 0 if np.isnan(ponset) else int(ponset) toffset = 600 if np.isnan(toffset) else int(toffset) # limit the onset and offset to be in the range of 0-600 # take some margin of 10ms...
5,326,378
def make_colormap(color_palette, N=256, gamma=1.0): """ Create a linear colormap from a color palette. Parameters ---------- color_palette : str, list, or dict A color string, list of color strings, or color palette dict Returns ------- cmap : LinearSegmentedColormap A...
5,326,379
def frac_correct(t): """Compute fraction correct and confidence interval of trials t """ assert np.all(t.outcome.values<2) frac = t.outcome.mean() conf = confidence(frac, len(t)) return frac, conf
5,326,380
def run_location(tokens, description): """Identifies the indices of matching text in the lines. Arguments: tokens (list): A list of strings, serialized from the GUI. description (CourseDescription): The course to be matched against. Returns: list: List of list of index positions. ...
5,326,381
def SUM(r, expression = lambda trx:None): #todo None ok? cause error = good? """Sum expression""" if expression.func_code.co_consts==(None,) and len(r._heading)==1: #if no expression but 1 attribute, use it expression = lambda trx:trx[r._heading[0]] return reduce(lambda x,y: x + y, (expres...
5,326,382
def domean(data, start, end, calculation_type): """ Gets average direction using Fisher or principal component analysis (line or plane) methods Parameters ---------- data : nest list of data: [[treatment,dec,inc,int,quality],...] start : step being used as start of fit (often temperature mi...
5,326,383
def download_data(dataset: str): """ Downloads a dataset as a .csv file. :param dataset: The name of the dataset to download. """ return send_from_directory(app.config['DATA_FOLDER'], dataset, as_attachment=True)
5,326,384
def _split_features_target(feature_matrix, problem_name): """Split the features and labels. Args: feature_matrix (pd.DataFrame): a dataframe consists of both feature values and target values. problem_name (str): the name of the problem. Returns: tuple: ...
5,326,385
def model_create_load_run_save(gpu, args, files, train_files): """The main function which does the overall training. Should be split into multiple parts in the future. Currently monolithc intentionally.""" rank = args.nr * args.gpus + gpu ## The rank of the current process out of the total number of processes i...
5,326,386
def descope_queue_name(scoped_name): """Descope Queue name with '.'. Returns the queue name from the scoped name which is of the form project-id.queue-name """ return scoped_name.split('.')[1]
5,326,387
def start(host="0.0.0.0", port=None, handlers=None, static_dir='./static', startup_callback=None, max_message_size=1 * 1024 * 1024, log_file='eui.log', log_level='DEBUG'): """ start eui :param host: host :param port: port, if port is None, port will be a random int value :param handlers: ...
5,326,388
def SearchBeamPosition(DriverType=None): """A factory for SearchBeamPosition classes.""" DriverInstance = DriverFactory.Driver(DriverType) class SearchBeamPositionWrapper(DriverInstance.__class__): def __init__(self): DriverInstance.__class__.__init__(self) self.set_executa...
5,326,389
def movie(function, movie_name="movie.gif", play_range=None, loop=0, optimize=True, duration=100, embed=False, mp4=True): """ Make a movie from a function. function has signature: function(index) and should return a PIL.Image. """ from IPython.display import Image frames = [] ...
5,326,390
def get_rounded_reward_2(duration: float) -> float: """ Helper function to round reward. :param duration: not rounded duration :return: rounded duration, two decimal points """ return round(get_reward(duration), 2)
5,326,391
def fitness_order(order): """fitness function of a order of cities""" score = 0 cacher = str(order) if cacher in cache: return cache[cacher] for i in range(len(order) - 1): score += distance_map[(order[i], order[i + 1])] score += distance_map[(order[0], order[-1])] cache[cach...
5,326,392
def get_human_readable_user_scripts_path() -> str: """Return a human readable location of user-scripts. This is NOT a valid filesystem path; may be something like "(SD Card)". """ from ba import _lang app = _ba.app path: Optional[str] = app.python_directory_user if path is None: ret...
5,326,393
def download_model_from_url(path, model='lstm'): """Downlod the model from url""" if os.path.exists(path): return download_model_path = DOWNLOAD_MODEL_PATH_DICT[model] logging.info("The first run will download the pre-trained model, which will take some time, please be patient!") dir_path = ...
5,326,394
def rotated_positive_orthogonal_basis( angle_x=np.pi / 3, angle_y=np.pi / 4, angle_z=np.pi / 5 ): """Get a rotated orthogonal basis. If X,Y,Z are the rotation matrices of the passed angles, the resulting basis is Z * Y * X. Parameters ---------- angle_x : Rotation angle around the ...
5,326,395
def reset_db(): """Reset all databases.""" click.confirm('This operation will delete all database, do you want to continue?', abort=True) db.drop_all() click.echo('Drop all tables.') db.create_all() click.echo('Reset all database.') admin_privkey = "0x8ef2fa4907d75fa653cede21fa0a75d62add49e4...
5,326,396
def create_sequences(tokenizer, max_length, descriptions, photos_features, vocab_size): """ 从输入的图片标题list和图片特征构造LSTM的一组输入 Args: :param tokenizer: 英文单词和整数转换的工具keras.preprocessing.text.Tokenizer :param max_length: 训练数据集中最长的标题的长度 :param descriptions: dict, key 为图像的名(不带.jpg后缀), value 为list, 包含一个图像的几...
5,326,397
def create_project_locale_groups(apps, schema_editor): """Create translators groups for every project locale object.""" Group = apps.get_model('auth', 'Group') Permission = apps.get_model('auth', 'Permission') ProjectLocale = apps.get_model('base', 'ProjectLocale') ContentType = apps.get_model('cont...
5,326,398
def avatar_uri(instance, filename): """ upload_to handler for Channel.avatar """ return generate_filepath(filename, instance.name, "_avatar", "channel")
5,326,399