content
stringlengths
22
815k
id
int64
0
4.91M
def split_df(df, index_range, columns, iloc=False): """Split a data frame by selecting from columns a particular range. Args: df (:class:`pd.DataFrame`): Data frame to split. index_range (tuple): Tuple containing lower and upper limit of the range to split the index by. If `index_ra...
47,300
def basemap_to_tiles(basemap, day=yesterday, **kwargs): """Turn a basemap into a TileLayer object. Parameters ---------- basemap : class:`xyzservices.lib.TileProvider` or Dict Basemap description coming from ipyleaflet.basemaps. day: string If relevant for the chosen basemap, you ca...
47,301
def ensure_directory_exists(path, expand_user=True, file=False): """ Create a directory if it doesn't exists. Expanding '~' to the user's home directory on POSIX systems. """ if expand_user: path = os.path.expanduser(path) if file: directory = os.path.dirname(path) else: ...
47,302
def test_rotate_polygon_about_pt_2d_triangle_0deg_origin(): """ Rotate a triangle 0 degrees counterclockwise, about the origin """ polygon_pts = np.array([[0, 0], [4, 0], [4, 4]]) theta = 0 # radians, which is 0 degrees c = np.cos(theta) s = np.sin(theta) rotmat = np.array([[c, ...
47,303
def seq2blastdb(fasta_set,db_name,db_type="prot",quiet=False): """ Convert a set of fasta-type sequences into a blast database. fasta_set: list of sequence strings in fasta format. db_name: database name. db_type: type of database to generate quiet: don't print status-y things """ ...
47,304
def sms_count(request): """Return count of SMSs in Inbox""" sms_count = Messaging.objects.filter(hl_status__exact='Inbox').count() sms_count = sms_count if sms_count else "" return HttpResponse(sms_count)
47,305
def test_load_db_data_from_json_version(fxtr_setup_logger_environment): """Test Load Database Data - unexpected api version.""" cfg.glob.logger.debug(cfg.glob.LOGGER_START) # ------------------------------------------------------------------------- initial_database_data_path = pathlib.Path(cfg.glob.set...
47,306
def deserializer(file_name: Path) -> Deserializer: """Load and parse the data deserialize declaration""" with open(file_name) as f: return Deserializer(yaml.load(f, Loader=SafeLoader))
47,307
def test_java_args(args): """ https://github.com/dkmiller/pyconfigurableml/blob/master/tests/test_entry.py """ spark = mock.MagicMock() gateway = mock.MagicMock() gateway.new_array = lambda _, n: [None] * n with mock.patch("pyspark.SparkContext._gateway", gateway): rv = java_args(sp...
47,308
def read_annotations(**kws): """Read annotations from either a GAF file or NCBI's gene2go file.""" if 'gaf' not in kws and 'gene2go' not in kws: return gene2gos = None if 'gaf' in kws: gene2gos = read_gaf(kws['gaf'], prt=sys.stdout) if not gene2gos: raise RuntimeError...
47,309
def p2db(a): """Returns decibel of power ratio""" return 10.0*np.log10(a)
47,310
def buildDictionary(message): """ counts the occurrence of every symbol in the message and store it in a python dictionary parameter: message: input message string return: python dictionary, key = symbol, value = occurrence """ _dict = dict() for c in message: if ...
47,311
def boston_housing(path): """Load the Boston Housing data set [@harrison1978hedonic]. It contains 506 examples of housing values in suburbs of Boston, each with 13 continuous attributes and 1 binary attribute. The data contains the following columns: | Feature | Description | | --- | --- | | CRIM | per ...
47,312
def model_fit(mb_query: str, features_dict: dict, target_var: str, model_struct_fn, get_model_sample_fn, existing_models: dict, batch_size: int, epochs: int, patience: int, verbose: int, bias_query: str, model_in: str, model_out: str, out_tensorboard: str, lr: float, iter: int, ...
47,313
def classify_subtrop(storm_type): """ SD purely - yes SD then SS then TS - no SD then TS - no """ if 'SD' in storm_type: if 'SD' in storm_type and True not in np.isin(storm_type,['TD','TS','HU']): return True if 'SS' in storm_type and True not in np.isin(storm_type,['TD',...
47,314
def overridden_settings(settings): """Return a dict of the settings that have been overridden""" settings = Settings(settings) for name, dft_value in iter_default_settings(): value = settings[name] if value != dft_value and value is not None: settings.update(name, value) ...
47,315
def ScaleImageToSize(ip, width, height): """Scale image to a specific size using Stephans scaler""" smaller = ip.scale( width, height ); return smaller
47,316
def retrieve_parent(*, schema: types.Schema, schemas: types.Schemas) -> str: """ Get or check the name of the parent. If x-inherits is True, get the name of the parent. If it is a string, check the parent. Raise InheritanceError if x-inherits is not defined or False. Args: schema: The...
47,317
def sorted_dfs_equal_by_pandas_testing(df1: pd.DataFrame, df2: pd.DataFrame) -> None: """ Wraps the pandas.util.testing assert_frame_equal with the boilerplate of fixing any irregularities from the publish/fetch process - this includes index and sorting, as those will almost never match Args: df...
47,318
def read_vensim(mdl_file, data_files=None, initialize=True, missing_values="warning", split_views=False, encoding=None, **kwargs): """ Construct a model from Vensim `.mdl` file. Parameters ---------- mdl_file : str The relative path filename for a raw Vensim ...
47,319
def test_statement_number_of_lines(sample_statement_object): """Tests the statement.lines property.""" assert sample_statement_object.lines == 3
47,320
def get_feature_importance( trained_pipeline: sklearn.pipeline.Pipeline, numeric_features: typing.List[str] ) -> pd.Series: """ Get feature importance measures from a trained model. Args: trained_pipeline (:obj:`sklearn.pipeline.Pipeline`): Fitted model pipeline numeric_feat...
47,321
def main(config): """ This tool creates building groups that can be used in the heat rejection model. For buildings that are NOT into a district system (according to the HVAC_SUPPLY databases), each building will be assigned to a different group. For buildings that are into a district system (according...
47,322
def json_loads(json_text: str) -> Any: """Does the same as json.loads, but with some additional validation.""" try: json_data = json.loads(json_text) validate_all_strings(json_data) return json_data except json.decoder.JSONDecodeError: raise _jwt_error.JwtInvalidError('Failed to parse JSON string'...
47,323
def weights(layer, expected_layer_name): """ Return the kernels/weights and bias from the VGG model for a given layer. """ W = vgg_layers[0][layer][0][0][2][0][0] b = vgg_layers[0][layer][0][0][2][0][1] layer_name = vgg_layers[0][layer][0][0][0][0] #to check we obtained the correct laye...
47,324
def test_apprise_logger(): """ API: Apprise() Logger """ # Ensure we're not running in a disabled state logging.disable(logging.NOTSET) # Set our log level URLBase.logger.setLevel(logging.DEPRECATE + 1) # Deprication will definitely not trigger URLBase.logger.deprecate('test') ...
47,325
def alert(title: str, text: str, *, level: str = "warning", ID: str = None): """ Generate the HTML to display a banner that can be permanently hidden This is used to inform player of important changes in updates. Arguments: text: Main text of the banner title: Title of the banner ...
47,326
def test_create_media_id(tmpdir): """also needs a file""" path = lambda *x: os.path.join(tmpdir, *x) with open(path("pixel.png"), "wb") as file: file.write(b'\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR') media = medium.Medium(None, path("pixel.png"), []) assert media.medium_id == \ "02a3e298f153...
47,327
def initialize_database(app): """ Prepares and registers the authentication database supported by the API. :param app: app instance :type app: flask.Flask :return: None :rtype: None type """ # Register the initialize the authentication database object to the application db.init_app...
47,328
def get_stim_data_df(sessions, analyspar, stimpar, stim_data_df=None, comp_sess=[1, 3], datatype="rel_unexp_resp", rel_sess=1, basepar=None, idxpar=None, abs_usi=True, parallel=False): """ get_stim_data_df(sessions, analyspar, stimpar) Returns dataframe with rela...
47,329
def get_all_elems_from_json(search_json: dict, search_key: str) -> list: """Returns values by key in all nested dicts. Args: search_json: Dictionary in which one needs to find all values by specific key. search_key: Key for search. Returns: List of values stored in nested structure...
47,330
def FindVisualStudioInstallation(): """ Returns appropriate values for .build_tool and .uses_msbuild fields of TestGypBase for Visual Studio. We use the value specified by GYP_MSVS_VERSION. If not specified, we search for likely deployment paths. """ msvs_version = 'auto' for flag in (f for f in sys.a...
47,331
def prFinalNodeName(q): """In : q (state : string) Out: dot string (string) Return dot string for generating final state (double circle) """ return dot_san_str(q) + '[shape=circle, peripheries=2];'
47,332
def decodeExifDateTime(value: str) -> typing.Optional[datetime.datetime]: """ utility fct to encode/decode """ try: # return path.encode(sys.stdout.encoding, 'ignore').decode(sys.stdout.encoding) d = datetime.datetime.strptime(value, '%Y:%m:%d %H:%M:%S') return d except Value...
47,333
def parse(file: str) -> Env: """Parse an RLE file and create a user environment Parameters ---------- file: str Path to the RLE file. Returns ------- user_env: `dict` [str, `Any`] User environment returned from ``user_env()``. It has these attributes: ``width`` ...
47,334
def logger_has_handlers(logger): """ Check if given logger has at least 1 handler associated, return a boolean value. Since Python 2 doesn't provide Logger.hasHandlers(), we have to perform the lookup by ourself. """ if six.PY3: return logger.hasHandlers() else: c = logger ...
47,335
def query_parameters(prefix, arpnum, t_recs, keywords, redis=True): """Query keyword sequence from a header file. Alternative design: replace prefix and arpnum with filepath. """ KEYWORDS = ['T_REC', 'AREA', 'USFLUXL', 'MEANGBL', 'R_VALUE'] if redis: id = f'{prefix}{arpnum:06d}' # header f...
47,336
def init_app(app, **kwargs): """ Init GeoAPI module. """ # Touch underlying modules from . import resources api_v1.add_namespace(resources.api)
47,337
def get_columns(tablename): """ This function returns simbench csv file column names for a given table name. """ allcolumns = all_columns() if tablename in allcolumns.keys(): if "Profile" in tablename: logger.debug("The returned column list of %s is given for simbench " % tablename + ...
47,338
def x0_rand(mu3,xb,num_min): """ Randomly initialise the 5 protocol parameters using the specified bounds. Parameters and bounds should be specified in the order {Px,pk1,pk2,mu1,mu2}. Parameters ---------- mu3 : float Intensity of pulse 3 (vacuum). xb : float, array-like Upp...
47,339
def render_smiles_list(smiles_list): """ Format and return a SMILES string(s). """ # The string that will be returned to the template result = r'<h3>Solvent SMILES:</h3>' + '\n' result += r'<p>' if len(smiles_list) == 1: result += smiles_list[0] else: result += 'This is a...
47,340
def generate_csv_eer_report(stats, ids, save_file): """ Generate a CSV file with the given statistics @param stats: An iterable with instances of the named tuple Stats @type stats: iterable @param ids: An iterable with an ID (str) for each stat @type ids: iterable @param save_file: The filename...
47,341
def create_relationships( self: celery.Task, secateur_user_pk: int, type: RelationshipType, user_ids: List[int] = None, screen_name: Optional[str] = None, until: Optional[datetime.datetime] = None, ) -> None: """Directly calls 'create_relationship() for each id in `user_ids`. Doesn't call it...
47,342
def test_sparsemax_of_inf(): """check sparsemax proposition 1, part 2""" z = np.random.uniform(low=-3, high=3, size=(100, 10)) # assume |A(z)| = 1, as z is continues random z_sort_arg = np.argsort(z, axis=1)[:, ::-1] z_sort = np.sort(z, axis=-1)[:, ::-1] gamma_z = z_sort[:, 0] - z_sort[:, 1] ...
47,343
def get_config_id(kwargs=None, call=None): """ Returns a config_id for a given linode. .. versionadded:: 2015.8.0 name The name of the Linode for which to get the config_id. Can be used instead of ``linode_id``. linode_id The ID of the Linode for which to get the config_id...
47,344
def bunq_oauth_reauthorize(): """ Endpoint to reauthorize OAuth with bunq """ cookie = request.cookies.get('session') if cookie is None or cookie != util.get_session_cookie(): return render_template("message.html", msgtype="danger", msg=\ "Invalid request: session cookie not set or not v...
47,345
def get_centrality_measures(network, tol): """ Calculates five centrality measures (degree, betweenness, closeness, and eigenvector centrality, and k-shell) for the nodes of the given network. Parameters ---------- network: networkx.Graph() tol: tolerance parameter for calculating eigenvect...
47,346
def extract_mealentries(meals: List[Meal]) -> List[Tuple]: """ Extract meal entries records from a sequence of myfitnesspal meals. Args: - meals (List[Meal]): A list with meal objects to extract data from Returns: - List[Tuple]: A list with meal record values """ return [ ...
47,347
def get_45point_spiralling_sphere_with_normal_zaxis_dist( num_of_spirals = 4, num_of_vertices = 45): """ A sphere of spiralling points. Each point is equally spaced on the x,y,z axes. The equal spacing is calculated by dividing the straight-line spiral distance by 45. Adapted from Leonsim's code here: https...
47,348
def refresh_gui_with_new_image(shared, df_files, df_model, df_landmarks, main_window, landmarks_window): """ Parameters ---------- shared : dictionary contains data shared across windows, definition is in the main function. df_files : pandas DataFrame dataframe containing the paths t...
47,349
def pak64(seq, debug=False): """ :param seq: smallish sequence of smallish integers :return seq64: smaller sequence of 64bit integers Pack a sequence of smallish integers into an array of 64 bit ints, using bit pitch and number of big ints appropriate to the length of the sequence and the ra...
47,350
def parse_results(line): """Parses and logs event information from logcat.""" header = re.search(r'cr_PasswordChangeTest: (\[[\w|:| |#]+\])', line).group(1) print(header) credentials_count = re.search(r'Number of stored credentials: (\d+).', line) if not credentials_count: # Event does not contain any cr...
47,351
def bqwrapper(datai): """ Wraps the kdtree ball query for concurrent tree search. """ return kdtbq(datai, r=bw[0])
47,352
def crawl_user_movies(): """ @功能: 补充用户观看过的电影信息 @参数: 无 @返回: 电影信息 """ user_df = pd.read_csv('douban_users.csv') user_df = user_df.iloc[:, [1, 2, 3]] user_movies = list(user_df['movie_id'].unique()) movies = [] # 储存电影 count = 1 # 日志参数 for i in user_movies: url = 'http...
47,353
def filter_by_shape(data: pd.DataFrame, geofence: Polygon) -> pd.DataFrame: """Remove trips outside of geofence. Filter by pickup and dropoff locations""" logging.info('Filtering by bbox') (min_lon, min_lat, max_lon, max_lat) = geofence.bounds data = data[ (data.pickup_longitude > min_lon) & (...
47,354
def test_typevar_attribute_fail(): """Test that the verifier of an generic attribute can fail.""" with pytest.raises(Exception) as e: ParamWrapperAttr([StringData("foo")]) assert e.value.args[0] == "Unexpected attribute StringData(data='foo')"
47,355
def upload_collection(flask_app, filenames, runs, dataset_id, collection_id, descriptions=None, cache=None): """ Create new Predictors from TSV files Args: filenames list of (str): List of paths to TSVs runs list of (int): List of run ids to apply events to dataset_...
47,356
def get_filtered_metadata_list(metadata_list, strand): """ Given a lis of exon junctions, remove the ones that redundantly cover a junction Parameters ---------- metadata_list: List(Output_metadata), strand: strand of the gene Returns ------- filtered_meetadata_list: List of metadata o...
47,357
def logger (type, message): """This is logger method to log messages based on type error, warning or success (or info)""" msg="" if (type == "error"): msg += co['fr'] elif (type == "warning"): msg += co['fy'] elif (type == "success"): msg += co['fg'] else: msg...
47,358
def handle_exceptions(database, params, constraints, start_params, general_options): """Handle exceptions in the criterion function. This decorator catches any exceptions raised inside the criterion function. If the exception is a :class:`KeyboardInterrupt` or a :class:`SystemExit`, the user wants to s...
47,359
def vector2angles(gaze_vector: np.ndarray): """ Transforms a gaze vector into the angles yaw and elevation/pitch. :param gaze_vector: 3D unit gaze vector :return: 2D gaze angles """ gaze_angles = np.empty((1, 2), dtype=np.float32) gaze_angles[0, 0] = np.arctan(-gaze_vector[0]/-gaze_vector[2]...
47,360
def setup_train_test_idx(X, last_train_time_step, last_time_step, aggregated_timestamp_column='time_step'): """ The aggregated_time_step_column needs to be a column with integer values, such as year, month or day """ split_timesteps = {} split_timesteps['train'] = list(range(last_train_time_step + 1)) ...
47,361
def get_targets_as_list(key_list): """Get everything as list :param key_list: Target key list :type key_list: `list` :return: Values list :rtype: `list` """ session = get_scoped_session() values = [] for key in key_list: values.append(get_all_targets(session, key)) retur...
47,362
def load_jmfd(jmfd_path): """Loads j-MFD as Pandas DataFrame. Args: jmfd_path (str): Path of J-MFD. Raises: JMFDFormatError: J-MFD format error. Returns: pandas.DataFrame: Pandas DataFrame of loaded j-MFD with word, existence of stem, foundation id ...
47,363
def binary_to_notelist(data): """data is a numpy array: [timestep, feature]. Timestep 0 is a midi #, timestep 1 is a duration, timestep 2 is midi, etc...""" assert len(data.shape) == 2 # Read the duration symbol table symbol_to_index = read_pickle(os.path.join(TXT_TOKENIZED, 'symbol_to_index.pkl')) ...
47,364
async def test_delete_cascade(factory: ComponentFactory) -> None: """Test that deleting a token cascades to child tokens.""" token_service = factory.create_token_service() session_token_data = await create_session_token( factory, scopes=["admin:token", "read:all", "user:token"] ) async with ...
47,365
def objectId(value): """objectId校验""" if value and not ObjectId.is_valid(value): raise ValueError('This is not valid objectId') return value
47,366
def add_lists(list1, list2): """ Add corresponding values of two lists together. The lists should have the same number of elements. Parameters ---------- list1: list the first list to add list2: list the second list to add Return ---------- output: list ...
47,367
def get_struc_first_offset(*args): """ get_struc_first_offset(sptr) -> ea_t Get offset of first member. @param sptr (C++: const struc_t *) @return: BADADDR if memqty == 0 """ return _ida_struct.get_struc_first_offset(*args)
47,368
def export_gps_route( trip_id, trip_date, vehicle_id, gtfs_error, offset_seconds, gps_data ): """ Writes the given entry to the "tracked_routes" table. This table is used to cache the results of finding and filtering only the valid routes as represented in the GPS da...
47,369
def optimize_solution(solution): """ Eliminate moves which have a full rotation (N % 4 = 0) since full rotations don't have any effects in the cube also if two consecutive moves are made in the same direction this moves are mixed in one move """ i = 0 while i < len(soluti...
47,370
def ipu_handler(ipu_data): """ Decodes the message received from the ipu router and distribute the sub-messages to corresponding IPU modules expected ipu_data structure: ipu_data = { sensor_type: { sensor_name: sensor_data, sensor_name: senso...
47,371
def secretsmanager_resource( client: Client, policies: Iterable[Policy] = None, ): """ Create Secrets Manager resource. Parameters: • client: Secrets Manager client object • policies: security policies to apply to all operations """ if client.service_name != "secretsmanager": ...
47,372
def lgbm_hyperband_classifier(numeric_features, categoric_features, learning_rate=0.08): """ Simple classification pipeline using hyperband to optimize lightgbm hyper-parameters Parameters ---------- `numeric_features` : The list of numeric features `categoric_features` : The list of categoric ...
47,373
def print_formatted(n: int): """Prints inclusive range from 1 to n in decimal, octal, hexa, and binary forms.""" adjustment = len(convert_int_to_form(n, 2)) for num in range(1, n+1): num_forms = [ str(num), convert_int_to_form(num, 8), get_hexa(num), ...
47,374
def GL(mu, wid, x, m = 0.5): """ Function to generate a 1D Gaussian-Lorentzian peak. The peak is centered at pos, is wid wide (FWHM) and with blending parameter m. Parameters ---------- mu: float Peak center wid: float FWHM of Gaussian peak. FWHM is related to ...
47,375
def jp_(var,mask): """Value at j+1/2, no gradient across boundary""" return div0((var*mask + np.roll(var*mask,-1,axis=0)),(mask+np.roll(mask,-1,axis=0)))
47,376
def clone(ctx, name, path, template): """Clones a template to create a new environment. \b - If no name is supplied the default name "Untitled" will be used. - If no path is supplied the template is saved to the current working directory. """ path_function = get_clone_function(path) status...
47,377
def _solrize_date(date, date_type=''): """ Takes a date string like 2018/01/01 and returns an integer suitable for querying the date field in a solr document. """ solr_date = "*" if date: date = date.strip() start_year, end_year = fulltext_range() if date_type == 'start'...
47,378
def validate_social_sharing_image(image): """Raises a validation error if the image is too large or too small.""" if image and (image.width > 4096 or image.height > 4096): raise ValidationError( "Social sharing image must be less than 4096w x 4096h" )
47,379
def read_file(filename): """ read filename and return its content """ in_fp = open(filename) content = in_fp.read() in_fp.close() return content
47,380
def get_arguments(): """Return the values of CLI params""" parser = argparse.ArgumentParser() parser.add_argument("--image_folder", default="images") parser.add_argument("--image_width", default=400, type=int) args = parser.parse_args() return getattr(args, "image_folder"), getattr(args, "image_...
47,381
def delete_job(job_id): """Delete my job by Id Upon success, marks job as &#x27;aborted&#x27; if it must be suspended, and returns the deleted job with the appropriate status # noqa: E501 :param job_id: Id of the job that needs to be deleted :type job_id: str :rtype: Job """ job = q.fetch...
47,382
def service(appctx): """Service with files instance.""" return RecordService(ServiceWithFilesConfig)
47,383
def forum(fid: str, page: int = 1): """ 访问指定版块 :param fid: 指定版块id :param page: 指定页数 """ global cont cont['now_page'] = page r = api.get_showf(fid, page) if type(r.json()) is list: cont['input_command_info'] = "" forum_data_process(r.json(), page) pad_browse_up...
47,384
def get_sci_edus(filepath): """ load each sciedu """ with open(filepath, 'r') as fb: train = json.loads(fb.read().encode('utf-8'))['root'] EDUs = [] sentenceNo = 1 sentenceID = 1 for edu_dict in train: if edu_dict['id'] == 0: continue EDUs.append(EDU([...
47,385
def vec_moderates(vec, minv, maxv, inclusive=1): """return a integer array where values inside bounds are 1, else 0 if inclusive, values will also be set if they equal a bound return error code, new list success: 0, list error : 1, None""" if not vec: return 1, None i...
47,386
def SideInfo(version_index, channel_mode, raw_data=None): """SideInfo(version_index, channel_mode, raw_data) -> object Return an object representing MPEG layer 3 side info, based on the given parameters. The class of the object varies based on the MPEG version and channel mode (only applicable fields are present, and...
47,387
def test_primary_bitmap_negative_missing(): """ Primary bitmap is required for all messages """ spec["h"]["data_enc"] = "ascii" spec["h"]["len_type"] = 0 spec["h"]["max_len"] = 6 spec["t"]["data_enc"] = "ascii" spec["p"]["data_enc"] = "ascii" s = b"header0200" with pytest.raises...
47,388
def datetimeConvertor(date, month, year, time, timezone): """ Converts raw date/time data into an object of datetime class. """ Date = date + "/" + monthnumberSwap(month) + "/" + year Time = time + " " + timezone return dt.datetime.strptime(Date + " " + Time, "%d/%m/%Y %H:%M:%S %z")
47,389
def dump_gone(aspect_store: dict, indent=False) -> bool: """Not too dry ...""" return _dump(aspect_store, pathlib.Path('gone.json'), indent)
47,390
def loss_fn(params, model, data): """ Description: This is MSE loss function, again pay close attention to function signature as this is the function which is going to be differentiated, so params must be in its inputs. we do not need to vectorize this function as it is written with batching co...
47,391
def lufact(A): """ lufact(A) Compute the LU factorization of square matrix A, returning the factors. """ n = A.shape[0] L = eye(n) # puts ones on diagonal U = copy(A) # Gaussian elimination for j in range(n-1): for i in range(j+1,n): L[i,j] = U[i,j] / U[j,j] # row multiplier U[i,j:] = U[i,j:] ...
47,392
def get_city(msg): """ 提取消息中的地名 """ # 对消息进行分词和词性标注 words = posseg.lcut(msg) # 遍历 posseg.lcut 返回的列表 for word in words: # 每个元素是一个 pair 对象,包含 word 和 flag 两个属性,分别表示词和词性 if word.flag == 'ns': # ns 词性表示地名 return word.word return None
47,393
def test_make_payload_with_other_signer(): """Test with signer is neither user nor manager""" user_key = helper.user.key() user_id = user_key.public_key manager_key = helper.user.key() manager_id = manager_key.public_key other_id = helper.user.id() other_key = helper.user.key() name = he...
47,394
def test_get_labeled_array(): """ Test outlined label arrays to send to the front-end. """ project = models.Project.create(DummyLoader()) frame = 0 feature = 0 expected_frame = project.label_frames[frame].frame[..., feature] label_arr = project.get_labeled_array(frame, feature) ass...
47,395
async def schedule_all(): """Recreate all jobs for the apscheduler. Will be used on startup.""" countdowns = await get_all_countdowns() if countdowns: for countdown in countdowns: name = countdown["name"] user_id = countdown["tg_user_id"] countdown_dt = countdown...
47,396
def render_model(cobra_model, background_template=None, custom_css=None, figure_id=None, hide_unused=None, hide_unused_cofactors=None, inactive_alpha=1., figsize=None, label=None, fontsize=None, default_flux_width=2.5, flux_dict=None, metabolite_dict=None, ...
47,397
def handle_config_defaults(config, num_params_fn): """Resolve dependencies within `config`. In particular, set hidden_size (if -1) according to num_params and make the embedding sizes default to the hidden size. Also, handle budgeting: if hidden_size is not provided (it is -1), but num_params is, then compute ...
47,398
def take_while(pred, iterator): """Take iterator elements while predicate true""" for next_val in iterator: if pred(next_val): yield next_val else: break
47,399