content
stringlengths
22
815k
id
int64
0
4.91M
def _removeSimpleAnnotation(ro_config, ro_dir, rofile, attrname, attrvalue): """ Remove a simple annotation or multiple matching annotations a research object. ro_config is the research object manager configuration, supplied as a dictionary ro_dir is the research object root directory rofile...
23,000
def modify_column_cell_content(content, value_to_colors): """ Function to include colors in the cells containing values. Also removes the index that was used for bookkeeping. """ idx, value = content if type(value) == int or type(value) == float: color = value_to_colors[content] ...
23,001
def ReversePolishSolver(expression): """ Solves a given problem in reverse polish notation :param expression - tuple of strings """ # Create empty stack rp_calculator = Stack() for c in expression: # Check if next part of expression is an operator or a number operator = {'+...
23,002
def _make_selection(stdscr, classes, message='(select one)'): """ This function was originally branched from https://stackoverflow.com/a/45577262/5009004 :return: option, classes index :rtype: (str, int) """ attributes = {} curses.init_pair(1, curses.COLOR_WHITE, curses.COLOR_BLACK) att...
23,003
def add_newword(cleaned_word, cleaned_meaning, file_name = 'words.txt'): """ Takes the preprocessed word, its meaning and default txt file argument as input. Updates the txt file with the temporary dict containing word and meaning as key:value pair. Also, handles the condition where the file doesn't exi...
23,004
def cmorization(in_dir, out_dir, cfg, _): """Cmorization func call.""" cmor_table = cfg['cmor_table'] glob_attrs = cfg['attributes'] logger.info("Starting cmorization for Tier%s OBS files: %s", glob_attrs['tier'], glob_attrs['dataset_id']) logger.info("Input data from: %s", in_dir) ...
23,005
def evaluate_model(epoch, controller, shared_cnn, data_loaders, n_samples=10): """Print the validation and test accuracy for a controller and shared_cnn. Args: epoch: Current epoch. controller: Controller module that generates architectures to be trained. shared_cnn: CNN that contains a...
23,006
def _check_keys(keys, spec): """Check a list of ``keys`` equals ``spec``. Sorts both keys and spec before checking equality. Arguments: keys (``list``): The list of keys to compare to ``spec`` spec (``list``): The list of keys to compare to ``keys`` Returns: ``bool`` Rais...
23,007
def get_snmp_table(hostname, table_oid, community, index=False): """ hostname : <str> table_oid : <str> community : <str> index : <bool> append index to every row, snmptable Option -Ci call snmptable command and get output ooutput will be transferred to list of dictionaries, key names ...
23,008
def hangToJamo(hangul: str): """한글을 자소 단위(초, 중, 종성)로 분리하는 모듈입니다. @status `Accepted` \\ @params `"안녕하세요"` \\ @returns `"ㅇㅏㄴㄴㅕㅇㅎㅏ_ㅅㅔ_ㅇㅛ_"` """ result = [] for char in hangul: char_code = ord(char) if not 0xAC00 <= char_code <= 0xD7A3: result.append(char) ...
23,009
def build_metadata_pairs(samples=100): """ Build sample data in format: isbn, title_a, authors_a, title_b, authors_b Where: isbn is in both datasets title_a + authors_a != title_b + authors_b """ from itertools import cycle import gc gc.enable() combos = [c for...
23,010
def get_config(config_path): """ Open a Tiler config and return it as a dictonary """ with open(config_path) as config_json: config_dict = json.load(config_json) return config_dict
23,011
def groupby_index(iter: Iterable[T],n:int) -> Iterable[Iterable[T]]: """group list by index Args: iter (Iterable[T]): iterator to group by index n (int): The size of groups Returns: Iterable[Iterable[T]]: iterable object to group by index >>> [*map(lambda x:[*x],groupby_index(...
23,012
def create(ctx, name, company, email, position): """Create a new Client""" client = Client(name, company, email, position) client_service = ClientService(ctx.obj['clients_table']) client_service.create_client(client)
23,013
def _build_message_classes(message_name): """ Create a new subclass instance of DIMSEMessage for the given DIMSE `message_name`. Parameters ---------- message_name : str The name/type of message class to construct, one of the following: * C-ECHO-RQ * C-ECHO-RSP ...
23,014
def valid_string(s, min_len=None, max_len=None, allow_blank=False, auto_trim=True, pattern=None): """ @param s str/unicode 要校验的字符串 @param min_len None/int @param max_len None/int @param allow_blank boolean @param auto_trim boolean @:param pattern re.p...
23,015
def update_visitor(visitor_key, session_key=None): """ update the visitor using the visitor key """ visitor = get_visitor(visitor_key) if visitor: visitor.mark_visit() if session_key: visitor.last_session_key = session_key visitor.save() return visitor
23,016
def test_receive_payment_with_travel_rule_metadata_and_invalid_reference_id( sender_account: AccountResource, receiver_account: AccountResource, currency: str, hrp: str, stub_config: AppConfig, diem_client: jsonrpc.Client, pending_income_account: AccountResource, invalid_ref_id: Optional...
23,017
def PNewUVTable (inUV, access, tabType, tabVer, err): """ Obsolete use PGetTable """ if ('myClass' in inUV.__dict__) and (inUV.myClass=='AIPSUVData'): raise TypeError("Function unavailable for "+inUV.myClass) return PGetTable (inUV, access, tabType, tabVer, err)
23,018
def fmt_hex(bytes): """Format the bytes as a hex string, return upper-case version. """ # This is a separate function so as to not make the mistake of # using the '%X' format string with an ints, which will not # guarantee an even-length string. # # binascii works on all versions of Python, ...
23,019
def pressure_filename(): """ Return the filename used to represent the state of the emulated sense HAT's pressure sensor. On UNIX we try ``/dev/shm`` then fall back to ``/tmp``; on Windows we use whatever ``%TEMP%`` contains """ fname = 'rpi-sense-emu-pressure' if sys.platform.startswith('wi...
23,020
def getTracksAudioFeatures(access_token, id_string): """ getTracksAudioFeatures() retrieves the track list audio features, this includes danceability, energy, loudness, etc.. """ # URL to pass a list of tracks to get their audio features audio_features_url = f"/audio-features" # Header par...
23,021
def list_model_evaluations( project_id, compute_region, model_display_name, filter_=None ): """List model evaluations.""" result = [] # [START automl_tables_list_model_evaluations] # TODO(developer): Uncomment and set the following variables # project_id = 'PROJECT_ID_HERE' # compute_region...
23,022
def tan(x): """Element-wise `tangent`.""" return sin(x) / cos(x)
23,023
def scalingImage(img, minVal, maxVal): """ Scale image given a range. Parameters: img, image to be scaled; minVal, lower value for range; maxVal, upper value for range. Returns: imgScaled, image scaled. """ imax = np.max(img) imin = np.min(img) std = (...
23,024
def test_python_module_ctia_positive_incident_search(get_entity): """Perform testing for incident/search entity of custom threat intelligence python module ID: CCTRI-2848 - 8fc6ba46-a610-4432-a72b-af92836fa560 Steps: 1. Send POST request to create new incident entity using custom pyth...
23,025
def forcestr(name): """ returns `name` as string, even if it wasn't before """ return name if isinstance(name, bytes) else name.encode(RAW_ENCODING, ENCODING_ERROR_HANDLING)
23,026
def IsGitSVNDirty(directory): """ Checks whether our git-svn tree contains clean trunk or some branch. Errors are swallowed. """ # For git branches the last commit message is either # some local commit or a merge. return LookupGitSVNRevision(directory, 1) is None
23,027
def read_attr( attr_desc: str, package_dir: Optional[Mapping[str, str]] = None, root_dir: Optional[_Path] = None ): """Reads the value of an attribute from a module. This function will try to read the attributed statically first (via :func:`ast.literal_eval`), and only evaluate the module if it...
23,028
def create_pyfunc_dataset(batch_size=32, repeat_size=1, num_parallel_workers=1, num_samples=None): """ Create Cifar10 dataset pipline with Map ops containing only Python functions and Python Multiprocessing enabled """ # Define dataset cifar10_ds = ds.Cifar10Dataset(DATA_DIR, num_samples=num_sample...
23,029
def test_collect_runtime_dependencies_driver(instr_workbench): """Test the collection of drivers as runtime dependencies. """ instr_workbench.register(InstrContributor1()) d_p = instr_workbench.get_plugin('exopy.app.dependencies') d_c = d_p.run_deps_collectors.contributions['exopy.instruments.driv...
23,030
def test_invalid_server_oneshot(tmpworkdir): # pylint: disable=unused-argument,redefined-outer-name """test to raise exception in oneshot""" result = agent_main(['--server', 'http://localhost:0', '--debug', '--oneshot']) assert result == 1
23,031
def serve(args): """ Create the grpc service server for processing measurement groups """ channel = grpc.insecure_channel(args.sendserver) stub = measurement_pb2_grpc.TrackProducerStub(channel) server = grpc.server(futures.ThreadPoolExecutor(max_workers=10)) measurement_pb2_grpc.add_Measu...
23,032
def _infer_structured_outs( op_config: LinalgStructuredOpConfig, in_arg_defs: Sequence[OperandDefConfig], ins: Sequence[Value], out_arg_defs: Sequence[OperandDefConfig], outs: Union[Sequence[Value], OpResultList]) -> Tuple[ValueList, List[Type]]: """Infers implicit outs and output types. Respects e...
23,033
def event_source(method: t.Callable, name: t.Optional[str] = None): """A decorator which makes the function act as a source of before and after call events. You can later subscribe to these event with :py:func:`before` and :py:func`after` decorators. :param method: Target class method :param: Name of...
23,034
def lst_blocks(uvp, blocks=2, lst_range=(0., 2.*np.pi)): """ Split a UVPSpec object into multiple objects, each containing spectra within different contiguous LST ranges. There is no guarantee that each block will contain the same number of spectra or samples. N.B. This function uses the `lst...
23,035
def test_list_customers(client, response): """Retrieve a list of existing customers.""" response.get("https://api.mollie.com/v2/customers", "customers_list") customers = client.customers.list() assert_list_object(customers, Customer)
23,036
def is_completed(book): """Determine if the book is completed. Args: book: Row instance representing a book. """ return True if book.status == BOOK_STATUS_ACTIVE \ and not book.complete_in_progress \ and book.release_date \ else False
23,037
def compute_encryption_key_AESV3(password : 'str', encryption_dict : 'dict'): """ Derives the key to be used with encryption/decryption algorithms from a user-defined password. Parameters ---------- password : bytes Bytes representation of the password string. encryption_dict : dict...
23,038
def list_group(group_name, recursive=True): """Returns all members, all globs and all nested groups in a group. The returned lists are unordered. Returns: GroupListing object. """ return get_request_cache().auth_db.list_group(group_name, recursive)
23,039
def test_num_iterations(): """ test values are given in the following order: theta, interval_width, confidence_level=1-alpha, n_pearson, n_spearman, n_kendall where theta is the value of the correlation coefficient References ---------- Sample size requirements for estimating Pearson, Kenda...
23,040
def list_tickets(result: typing.List[typing.List] = None) -> None: """Lists the tickets created on this session. Args: result (typing.List[typing.List]): Result received from the decorator. Defaults to None. """ if result is not None: if len(result) != 0: headers...
23,041
def pi(): """Compute Pi to the current precision. >>> print(pi()) 3.141592653589793238462643383 """ getcontext().prec += 2 # extra digits for intermediate steps three = Decimal(3) # substitute "three=3.0" for regular floats lasts, t, s, n, na, d, da = 0, three, 3, 1, 0, 0, 24 whi...
23,042
def test_reactivate_and_save(): """Test that the reactivate_and_save method in enrollment models sets properties and saves""" course_run_enrollment = CourseRunEnrollmentFactory.create( active=False, change_status=ENROLL_CHANGE_STATUS_REFUNDED ) program_enrollment = ProgramEnrollmentFactory.creat...
23,043
def molecule_rot(axis,degree,XYZ): """ molecular rotation use axis to specify x,y,z vectors """ atlist=range(0,len(XYZ)) rad=radians(degree) p2=np.array([0,0,0]) for i in sorted(atlist[:]): print 'rotating...',i v=XYZ[i,:] Rmat= RotMatArb(axis,rad,p2,v) XYZ[i,:]=R...
23,044
def load_cifar_data(limit=None) -> np.ndarray: """ :param limit: :return: """ # cifar10 data (integrated in TensorFlow, downloaded on first use) cifar10_data = tf.keras.datasets.cifar10 # split into training and test data train_data, test_data = cifar10_data.load_data() # split dta i...
23,045
def set_goal_orientation(delta, current_orientation, orientation_limit=None, set_ori=None): """ Calculates and returns the desired goal orientation, clipping the result accordingly to @orientation_limits. @delta and @current_orientat...
23,046
def report(args, unreconciled, reconciled, explanations, column_types): """Generate the report.""" # Everything as strings reconciled = reconciled.applymap(str) unreconciled = unreconciled.applymap(str) # Convert links into anchor elements reconciled = reconciled.applymap(create_link) unrec...
23,047
def get_fixed_income_index(): """获取固定收益及中债总财富指数对比走势""" return get_stg_index('fixed_income', '037.CS')
23,048
def ignoreQtMessageHandler(msgs): """A context that ignores specific qMessages for all bindings Args: msgs: list of message strings to ignore """ from Qt import QtCompat def messageOutputHandler(msgType, logContext, msg): if msg in msgs: return sys.stderr.write(...
23,049
def get_jobid(db): """ Ask MongoDB for the a valid jobid. All processing jobs should have a call to this function at the beginning of the job script. It simply queries MongoDB for the largest current value of the key "jobid" in the history collection. If the history collection is em...
23,050
def collect_input_arguments(): """ Collecting input arguments at the command line for use later. """ parser = argparse.ArgumentParser(prog= 'Alignseq', description='Align Codon Sequences', usage='%(prog)s [options]', epilog="And that's how you make an Alignment!") parser.add_argument('-inf', me...
23,051
def isA(token, tt=None, tv=None): """ function to check if a token meets certain criteria """ # Row and column info may be useful? for error messages try: tokTT, tokTV, _row, _col = token except: return False if tt is None and tv is None: return True elif tv is No...
23,052
def authenticate( *, token: str, key: str, ) -> Tuple[bool, Dict]: """Authenticate user by token""" try: token_header = jwt.get_unverified_header(token) decoded_token = jwt.decode(token, key, algorithms=token_header.get("alg")) except JWTError: return False, {} else: ...
23,053
def backup(source, destination, *, return_wrappers=False): """ Backup the selected source(s) into the destination(s) provided. Source and destination will be converted into ``Source`` and ``Destination`` respectively. If this conversion fails, an exception will be raised. :param return_wrapper...
23,054
def _prepare_data(cfg, imgs): """Inference image(s) with the detector. Args: model (nn.Module): The loaded detector. imgs (str/ndarray or list[str/ndarray] or tuple[str/ndarray]): Either image files or loaded images. Returns: result (dict): Predicted results. """ ...
23,055
def test_update_email_change_request_existing_email(user): """Test that update change email request gives validation error for existing user email""" new_user = UserFactory.create() change_request = ChangeEmailRequest.objects.create( user=user, new_email=new_user.email ) serializer = ChangeE...
23,056
def test_sx(params=''): """ Execute all tests in docker container printing output and terminating tests at first failure :param params: parameters to py.test """ docker_exec('py.test -sx {}'.format(params))
23,057
def _HandleJsonList(response, service, method, errors): """Extracts data from one *List response page as JSON and stores in dicts. Args: response: str, The *List response in JSON service: The service which responded to *List request method: str, Method used to list resources. One of 'List' or 'Ag...
23,058
def gray_arrays_to_rgb_sequence_array(arrays, start_rgb, end_rgb, normalise_input=False, normalise_output=True): """Returns an RGB array that is mean of grayscale arrays mapped to linearly spaced RGB colors in a range. :param list arrays: list of numpy.ndarrays of shape (N, M) :param tuple start_rgb: (R, G...
23,059
def normalize_inputs(df, metrics): """Normalize all inputs around mean and standard deviation. """ for m in metrics: mean = np.mean(df[m]) stdev = np.std(df[m]) def std_normalize(x): return (x - mean) / stdev #df[m] = df[m].map(std_normalize) xmin = min(df...
23,060
def calc_z_rot_from_right(right): """ Calculates z rotation of an object based on its right vector, relative to the positive x axis, which represents a z rotation euler angle of 0. This is used for objects that need to rotate with the HMD (eg. VrBody), but which need to be robust to changes in orientati...
23,061
def poisson_interval(data, alpha=0.32): """Calculates the confidence interval for the mean of a Poisson distribution. Parameters ---------- data: array_like Data giving the mean of the Poisson distributions. alpha: float Significance level of interval. Defaults to one si...
23,062
def sales_administrative_expense(ticker, frequency): """ :param ticker: e.g., 'AAPL' or MULTIPLE SECURITIES :param frequency: 'A' or 'Q' for annual or quarterly, respectively :return: obvious.. """ df = financials_download(ticker, 'is', frequency) return (df.loc["Sales, General and administr...
23,063
def clip(x, min_, max_): """Clip value `x` by [min_, max_].""" return min_ if x < min_ else (max_ if x > max_ else x)
23,064
async def test_get_triggers(hass): """Test triggers work.""" gateway = await setup_deconz(hass, options={}) device_id = gateway.events[0].device_id triggers = await async_get_device_automations(hass, "trigger", device_id) expected_triggers = [ { "device_id": device_id, ...
23,065
def generate_code(): """Generate a URL-compatible short code.""" return ''.join(random.choice(ALPHABET) for _ in range(10))
23,066
def prox_pos(v, t = 1, *args, **kwargs): """Proximal operator of :math:`tf(ax-b) + c^Tx + d\\|x\\|_2^2`, where :math:`f(x) = \\max(x,0)` applied elementwise for scalar t > 0, and the optional arguments are a = scale, b = offset, c = lin_term, and d = quad_term. We must have t > 0, a = non-zero, and d >= 0. ...
23,067
def delete_mapping(module, sdk, cloud, mapping): """ Attempt to delete a Mapping returns: the "Changed" state """ if mapping is None: return False if module.check_mode: return True try: cloud.identity.delete_mapping(mapping) except sdk.exceptions.OpenStackCloud...
23,068
def insert_target(x, segment_size): """ Creates segments of surrounding words for each word in x. Inserts a zero token halfway the segment to mark the end of the intended token. Parameters ---------- x: list(int) A list of integers representing the whole data as one long encoded ...
23,069
def find_nearest_network(ipa, nets): """ :param ipa: An ip address string :param nets: A of str gives and ip address with prefix, e.g. 10.0.1.0/24 >>> net1 = "192.168.122.0/24" >>> net2 = "192.168.0.0/16" >>> net3 = "192.168.1.0/24" >>> net4 = "192.168.254.0/24" >>> net5 = "0.0....
23,070
def find_lines(image, show_image, logger): """Find lines in the *image*.""" logger("preprocessing") show_image(image, "original image") im_h = prepare(image, show_image, logger) hough = Hough.default(im_h) logger("hough transform") im_h2 = transform(im_h, hough, show_image) ...
23,071
def set_action_translation( language_id: int, action_id: int, name: str, description: str = '', short_description: str = '', ) -> ActionTranslation: """ Create or update an action translation. :param language_id: the ID of an existing language :param action_id: t...
23,072
def partialSVD(batch, S, VT, ratio = 1, solver = 'full', tol = None, max_iter = 'auto'): """ Fits a partial SVD after given old singular values S and old components VT. Note that VT will be used as the number of old components, so when calling truncated or randomized, will output a specific number of eigenvector...
23,073
def can_move_in_direction(node: Node, direction: Direction, factory: Factory): """If an agent has a neighbour in the specified direction, add a 1, else 0 to the observation space. If that neighbour is free, add 1, else 0 (a non-existing neighbour counts as occupied). """ has_direction = node.has_nei...
23,074
def render_list_end(token, body, stack, loop): """Pops the pushed ``urwid.Pile()`` from the stack (decreases indentation) See :any:`lookatme.tui.SlideRenderer.do_render` for argument and return value descriptions. """ stack.pop()
23,075
def action(plugin_name: str, with_client: bool = False): """ アクション定義メソッドに使うデコレータ """ def _action(func): def wrapper(client: BaseClient, *args, **kwargs): logger.debug("%s called '%s'", client.get_send_user(), plugin_name) logger.debug("%s app called '%s'", client.get_ty...
23,076
def main(architecture: str = DEFAULT_ARCHITECTURE, clean: bool = False, mirror_url: str = DEFAULT_MIRROR_URL, number: int = DEFAULT_NUMBER, output_dir: str = DEFAULT_OUTPUT_DIR, reuse_contents_file: bool = DEFAULT_REUSE_CONTENTS_FILE, sort_descending: bool = DEFAULT...
23,077
def setup_helper_functions(app): """Sets up the helper functions. Args: app (werkzeug.local.LocalProxy): The current application's instance. """ import helper functions = { "get_project_category": helper.get_project_category, "get_blurred_cover_image_path": helper.get_blurre...
23,078
def Usable(entity_type,entity_ids_arr): """Only for Linux modules""" filNam = entity_ids_arr[0] return filNam.endswith(".ko.xz")
23,079
def detection_collate(batch): """Custom collate fn for dealing with batches of images that have a different number of associated object annotations (bounding boxes). Arguments: batch: (tuple) A tuple of tensor images and lists of annotations Return: A tuple containing: 1) (...
23,080
def write_gct(matrix, filepath, descriptions=None): """ Establish .gct filepath and write matrix to it. :param matrix: DataFrame or Serires; (n_samples, m_features) :param filepath: str; filepath; adds .gct suffix if missing :param descriptions: iterable; (n_samples); description column :return:...
23,081
def SkipUntilNewLine(handle): """Skips data until a new-line character is received. This is needed so that the first sample is read from a complete line. """ logging.debug("Skipping until the end of a new line.") while not handle.readline(4096).endswith('\n'): pass
23,082
def assert_allclose( actual: scipy.stats.mstats_basic.Ttest_1sampResult, desired: scipy.stats.mstats_basic.Ttest_1sampResult, ): """ usage.scipy: 1 """ ...
23,083
def get_total_invites_in_mempool(): """ Call merit-cli subprocess and get the number of free invites in mempool :rtype: int """ invites_in_mempool = json.loads( (subprocess.check_output(['merit-cli', '-conf={}'.format(config.MERIT_CONF), ...
23,084
def _apply_fft_high_pass_filter(data, fmin, fs=None, workers=None, detrend=True, time_name=None): """Apply high-pass filter to FFT of given data. Parameters ---------- data : xarray.DataArray Data to filter. fmin : float Lowest frequency in pass band...
23,085
def load_inputs(mod, switch_data, inputs_dir): """ Import project-specific data. The following files are expected in the input directory. all_projects.tab PROJECT, proj_dbid, proj_gen_tech, proj_load_zone, proj_connect_cost_per_mw existing_projects.tab PROJECT, build_year,...
23,086
def plot_cospectrum(fnames, figname=None, xlog=None, ylog=None, output_data_file=None): """Plot the cospectra from a list of CPDSs, or a single one.""" if is_string(fnames): fnames = [fnames] figlabel = fnames[0] for i, fname in enumerate(fnames): pds_obj = load_pds...
23,087
def truncate(array:np.ndarray, intensity_profile:np.ndarray, seedpos:int, iso_split_level:float)->np.ndarray: """Function to truncate an intensity profile around its seedposition. Args: array (np.ndarray): Input array. intensity_profile (np.ndarray): Intensities for the input array. se...
23,088
def stac2ds( items: Iterable[pystac.Item], cfg: Optional[ConversionConfig] = None ) -> Iterator[Dataset]: """ Given a lazy sequence of STAC :class:`pystac.Item` turn it into a lazy sequence of :class:`datacube.model.Dataset` objects """ products: Dict[str, DatasetType] = {} for item in items...
23,089
def fitting_process_parent(scouseobject, SAA, key, spec, parent_model): """ Pyspeckit fitting of an individual spectrum using the parent SAA model Parameters ---------- scouseobject : Instance of the scousepy class SAA : Instance of the saa class scousepy spectral averaging area key...
23,090
def train_logistic_model(sess: tf.Session, model: Model, train_feeder: FileFeeder, val_feeder: FileFeeder): """Train via scikit-learn because it seems to train logistic regression models more effectively""" train_data = _get_dataset(train_feeder) val_data = _get_dataset(val_feeder) logging.info("read {...
23,091
def run(args: Namespace): """ run function which is the start point of program Args: args: program arguments """ tgr = PosTagger(args.model_dir) for line_num, line in enumerate(sys.stdin, start=1): if line_num % 100000 == 0: logging.info('%d00k-th line..', (line_num ...
23,092
def _load_grammar(grammar_path): """Lee una gramática libre de contexto almacenada en un archivo .cfg y la retorna luego de realizar algunas validaciones. Args: grammar_path (str): Ruta a un archivo .cfg conteniendo una gramática libre de contexto en el formato utilizado por NLTK. ...
23,093
def time_span(ts): """计算时间差""" delta = datetime.now() - ts.replace(tzinfo=None) if delta.days >= 365: return '%d年前' % (delta.days / 365) elif delta.days >= 30: return '%d个月前' % (delta.days / 30) elif delta.days > 0: return '%d天前' % delta.days elif delta.seconds < 60: ...
23,094
def check_point(point_a, point_b, alpha, mask): """ Test the point "alpha" of the way from P1 to P2 See if it is on a face of the cube Consider only faces in "mask" """ plane_point_x = lerp(alpha, point_a[0], point_b[0]) plane_point_y = lerp(alpha, point_a[1], point_b[1]) plane_point_z =...
23,095
def gIndex(df, query_txt, coluna_citacoes:str): """Calcula índice g""" df = df.query(query_txt).sort_values(by=[coluna_citacoes],ascending=False) df = df.reset_index(drop=True) df.index+= 1 df['g^2'] = df.index**2 df['citações acumuladas'] = df[coluna_citacoes].cumsum() df['corte'] = abs(df['g^2']...
23,096
def dockerize_cli_args(arg_str: str, container_volume_root="/home/local") -> str: """Return a string with all host paths converted to their container equivalents. Parameters ---------- arg_str : str The cli arg string to convert container_volume_root : str, optional The container di...
23,097
def _invert_monoms(p1): """ Compute ``x**n * p1(1/x)`` for a univariate polynomial ``p1`` in ``x``. Examples ======== >>> from sympy.polys.domains import ZZ >>> from sympy.polys.rings import ring >>> from sympy.polys.ring_series import _invert_monoms >>> R, x = ring('x', ZZ) ...
23,098
def cleaned_picker_data(date: dt.date) -> Dict: """Retrieve and process data about Podcast Picker visits from Webtrekk API for a specific date. Args: date (dt.date): Date to request data for. Returns: Dict: Reply from API. """ config = AnalysisConfig( [ Ana...
23,099