content
stringlengths
22
815k
id
int64
0
4.91M
def build_si(cp, instruction): """ Build the integer representation of the source indices. :param cp: CoreParameters instance for the target architecture :param instruction: Instruction instance :return: integer representation of si """ # Check sizing. if len(instruction.source_indices...
5,325,200
def getRegSampledPrfFitsByOffset(prfArray, colOffset, rowOffset): """ The 13x13 pixel PRFs on at each grid location are sampled at a 9x9 intra-pixel grid, to describe how the PRF changes as the star moves by a fraction of a pixel in row or column. To extract out a single PRF, you need to address the 117...
5,325,201
def generate_list_display(object, attrs): """Generate a display string for an object based on some attributes. Args: object: An object which has specific attributes. attrs: An interable of strings containing attributes to get from the above object. Returns: A string con...
5,325,202
def create_temporary_config_file(): """ Create a minimal config file with some default values """ toml_config = document() toml_config.add("name", "Test Suite") tmp_config_file = tempfile.NamedTemporaryFile(delete=False) with tmp_config_file: content = dumps(toml_config).encode("utf-8"...
5,325,203
def csv_to_sql(directory=RAW_TWEET_DIR, **kwargs): """ csv to sql pipeline using pandas params: directory: str (file path to csv files) """ dbconn = MySqlHook(mysql_conn_id="mysql_default") conn = dbconn.get_connection() cursor = conn.cursor() for fname in glob.glob("{}/*.cs...
5,325,204
def shear(image, shear_factor, **kwargs): """ Shear image. For details see: http://scikit-image.org/docs/dev/api/skimage.transform.html#skimage.transform.AffineTransform >>> image = np.eye(3, dtype='uint8') >>> rotated = rotate(image, 45) :param numpy array image: Numpy array with range [...
5,325,205
def segments(): """Yields all segments in the unnannotated training Qatar-Living dataset.""" return (segment for document in documents() for segment in document.segments)
5,325,206
def cleanup() -> None: """Public wrapper for `_onwiki_logger.cleanup()`.""" if _onwiki_logger.cleanup(): print("Cleaning up RfD log on-wiki")
5,325,207
def get_options_between_dates( start_date, end_date): """get_options_between_dates :param start_date: start date :param end_date: end date """ valid_options = [] for rec in historical_options(): opt_date = datetime.datetime.strptime( str(rec), '%...
5,325,208
def setFontSizes(labelsize=20, fsize=17, titlesize=None, ax=None,): """ Update font sizes for a matplotlib plot """ if ax is None: ax = plt.gca() for tick in ax.xaxis.get_major_ticks(): tick.label.set_fontsize(fsize) for tick in ax.yaxis.get_major_ticks(): tick.label.set_fontsize...
5,325,209
def format_timestamp(timestamp_str, datetime_formatter): """Parse and stringify a timestamp to a specified format. Args: timestamp_str (str): A timestamp. datetime_formatter (str): A format string. Returns: str: The formatted, stringified timestamp. """ try: if '"' ...
5,325,210
def test_now(): """ Tests creating a Time object with the `now` class method. """ now = datetime.datetime.utcnow() t = Time.now() assert t.format == 'datetime' assert t.scale == 'utc' dt = t.datetime - now # a datetime.timedelta object # this gives a .1 second margin between the...
5,325,211
def post_worker_init(worker): """ Launch a process to listen worker after gunicorn worker is initialized. Children processes of gunicorn worker should be killed when worker has been killed because gunicorn master murders this worker for some reasons such as worker timeout. Args: worker (Th...
5,325,212
def dyn_stdev(val, prev_stdev, prev_mean, n): """Dynamic stdev: computes the standard deviation based on a previous stdev plus a new value. Useful when stdev is built incrementally, it saves the usage of huge arrays. Keyword arguments: val -- new val to add to the mean prev_stdev -- previous stdev...
5,325,213
def get_detail_backtest_results(input_df, features, return_col_name='returns', equity_identifier='Equity Parent', date_col_name='date', n_bins=5, ...
5,325,214
def check_one(filename): """Given a filename, return None or restart. """ # The file may have been removed from the filesystem. # =================================================== if not os.path.isfile(filename): if filename in mtimes: aspen.log("File deleted: %s" % filename)...
5,325,215
def test_create_flat_file(input_value): """ Test the whether the files are created with the given number of lines :param input_value: :return: """ file_name = input_value[0] number_of_lines = input_value[2] tot_num_char = input_value[3] create_flat_file.create_flat_file(file...
5,325,216
def sid_invalid_retry(retry=1): """ 鉴权失败,一般是因为在手机上登录,导致上次登录的 token 失效。 该函数用于返回一个函数修饰器,被修饰的 API 函数如果发生鉴权错误, 则重新登录后重新调用 API 函数,最高 retry 次 Args: retry int 重新尝试的次数,默认只重试一次 Raises: JoyrunSidInvalidError 超过重复校验次数后仍然鉴权失败 """ def func_wrapper(func): ...
5,325,217
def _check_predictions(original_model, model, X, y): """ Check to make sure both models produce the same predictions. """ if model.objective == 'regression': p1 = original_model.predict(X) X = check_input_data(X) p2 = model.predict(X)[:, 0] elif model.objective == 'binary': ...
5,325,218
def write_cfradial(filename, radar, format='NETCDF4', time_reference=None, arm_time_variables=False): """ Write a Radar object to a CF/Radial compliant netCDF file. The files produced by this routine follow the `CF/Radial standard`_. Attempts are also made to to meet many of the stan...
5,325,219
def test_hash_get(): ## 2 """[summary] Retrieving based on a key returns the value stored """ ht = Hashtable() ht.add('Saleh','what ever you want') actual = ht.find('Saleh') assert actual == 'what ever you want'
5,325,220
def check_train_balance(df,idx_train,keys): """ check the balance of the training set. if only one of the classes has more 2 instances than the other we will randomly take out those 'extra instances' from the major class """ Counts = dict(Counter(df.iloc[idx_train]['targets'].values)) if...
5,325,221
def print_ascii(file_name): """ This function print out contents from a txt file each char at time. The parameter file_name is type string. When calling the func, the format of the argument should be "filename.txt" """ with open("./ascii/" + file_name) as f: print(f.read())
5,325,222
def cli_podcast_play(podcast_name, episode_id): """ CLI facing function to play the podcast episode, when passed podcast name and episode id, (NOT episode number). :param podcast_name: name of the podcast. :param episode_id: id(index) of episode. :return: """ episode = None print("Wait ...
5,325,223
def eye(w, n): """Create diagonal matrix with w on diagonal.""" return np.array([[w if i==j else 0.0*w for i in range(n)] for j in range(n)])
5,325,224
def Messaging(): """ Messaging Creates JMS resources. Only to use in a resource block. """ if state().block and state().block != 'resources': raise SyntaxError('Messaging can only be used in a resources block') return subscope('messaging')
5,325,225
def time_series_plot_from_json(time_series_dict, single_day=False, save=False): """Given a time series dictionary, plot the trend in likelihood Arguments: time_series_dict {[type]} -- format shown as below { "[time]": { [room_number]: [likelihood] }, ... } Keyword Ar...
5,325,226
def timestamp2WP(timestamp): """ Converts a Unix Epoch-based timestamp (seconds since Jan. 1st 1970 GMT) timestamp to one acceptable by Wikipedia. :Parameters: timestamp : int Unix timestamp to be converted :Return: string Wikipedia style timestamp """ return datetime.datetime.utcfromtimestamp(ti...
5,325,227
def txt(solution1:List[List[int]],solution2:List[List[int]],matrix:List[List[int]]): """ Reorder matrix based on solution. Parameters ---------- solution1: clustering of rows as a list solution2: clustering of columns as a list matrix: matrix of the original relation Returns ------...
5,325,228
def get_available_node_types(nodenet_uid): """ Return a dict of available built-in node types and native module types""" return True, runtime.get_available_node_types(nodenet_uid)
5,325,229
def dos_element_orbitals( folder, element_orbital_dict, output='dos_element_orbitals.png', fill=True, alpha=0.3, linewidth=1.5, sigma=0.05, energyaxis='x', color_list=None, legend=True, total=True, figsize=(4, 3), erange=[-6, 6], spin='up', soc_axis=None, ...
5,325,230
def get_ceph_nodes(): """Query named relation 'ceph' to determine current nodes.""" hosts = [] for r_id in relation_ids('ceph'): for unit in related_units(r_id): hosts.append(relation_get('private-address', unit=unit, rid=r_id)) return hosts
5,325,231
def dotmm(a, b, out): """dotmm(a, b) Computes an efficient dot product of a 4x4, 2x2 or a less efficient general matrix multiplication. """ if a.shape[0] == 2 and a.shape[1] == 2: _dotmm2(a, b, out) elif a.shape[0] == 4 and a.shape[1] == 4: _dotmm4(a, b, out) else: _dotmm...
5,325,232
def metadataAbstractElementIllegalChildElementTest1(): """ No child elements, child elements not allowed. >>> doctestMetadataAbstractElementFunction( ... testMetadataAbstractElementIllegalChildElements, ... metadataAbstractElementIllegalChildElementTest1()) [] """ metadata = """...
5,325,233
def discover_fields(layout): """Discover all fields defined in a layout object This is used to avoid defining the field list in two places -- the layout object is instead inspected to determine the list """ fields = [] try: comps = list(layout) except TypeError: return fiel...
5,325,234
def replace(project_symbols): """ replace old source with non annotated signatures :param project_symbols: symbols we will use to write out new source code :return: bool """ for module_symbols in project_symbols: if not write_new_source(module_symbols, access_attr...
5,325,235
def element_list_as_string(elements): """Flatten a list of elements into a space separated string.""" names = [] for element in elements: if isinstance(element, AOVGroup): names.append("@{}".format(element.name)) else: names.append(element.variable) return " "....
5,325,236
def load_sample_metadata(path: str, sample_id: str) -> Dict[str, str]: """ Read sample metadata from either an sqlite '.db' database or a tab-delimited file. The tab-file has to have one sample per line and a header with a column labelled 'Name' or 'SampleId' in which a match to functio...
5,325,237
def test_delete_nat_gateway(): """ This method tests the deletion Nat Gateway :return: """ ec2_client = boto3.client('ec2', region_name=region_name) vpc_response = ec2_client.create_vpc(CidrBlock='10.0.0.0/16') vpc_id = vpc_response['Vpc']['VpcId'] subnet1 = ec2_client.create_subnet(VpcI...
5,325,238
def handle_rlscope_args(parser=None, args=None, directory=None, reports_progress=False, delay=False, delay_register_libs=False): """ Initialize the RL-Scope profiler (:py:obj:`rlscope.api.prof`) using :py:obj:`sys.argv`. Arguments --------- parser : argparse.ArgumentParser The training scri...
5,325,239
def delete(ctx, session_token): """Delete a session from Fl33t""" session = ctx.obj['get_fl33t_client']().get_session(session_token) if not session: click.echo('Session does not exist in Fl33t. Cannot proceed with ' 'deletion.') return if session.delete(): cl...
5,325,240
def encode_corpus(storage: LetterStorage, corpus: tuple) -> tuple: """ Encodes sentences by replacing letters with their ids :param storage: an instance of the LetterStorage class :param corpus: a tuple of sentences :return: a tuple of the encoded sentences """ if not isinstance(storage, Let...
5,325,241
def test_expected_cols(): """Testing for matching columns""" assert col_checker('http://www-bcf.usc.edu/~gareth/ISL/Auto.csv')
5,325,242
def _assert_strides_are_log2_contiguous(strides): """ Assert that each stride is 2x times its preceding stride, i.e. "contiguous in log2". """ for i, stride in enumerate(strides[1:], 1): assert stride == 2 * strides[i - 1], \ f"Strides {stride} {strides[i - 1]} are not log2 contiguous"
5,325,243
def setBaseTheme( theme ): """ Sets the name for the current base theme to be used. :param theme | <str> """ global _BASE_THEME _BASE_THEME = str(theme)
5,325,244
def test_cert_option(parse_requirements, runner, option, attr, expected): """ The options --cert and --client-cert have to be passed to the PyPIRepository. """ with open("requirements.in", "w"): pass runner.invoke(cli, [option, expected]) # Ensure the options in parse_requirements has ...
5,325,245
def aggregated_column_unique(chart: Type[BaseChart], data): """ description: main function to calculate histograms input: - chart - data output: list_of_unique_values """ a_range = cuda.to_device(np.array([chart.min_value, chart.max_value])) temp_df = cudf.Da...
5,325,246
def convert_image(qcow_image=None): """ :return: """ # A convert QCOW to VMDK new_filename = Path(qcow_image).stem + ".vmdk" path_to_vmdk = str(Path(qcow_image).parent.joinpath(new_filename)) if os.path.isfile(path_to_vmdk) is False: print("Creating vmdk image.") # convert ...
5,325,247
def collocations_table_exist(con): """Return True if the collocations table exist""" query = con.query( "select 1 from information_schema.tables " "where table_name='collocations'") return bool(list(query.dictresult()))
5,325,248
def ftp_profile(publish_settings): """Takes PublishSettings, extracts ftp user, password, and host""" soup = BeautifulSoup(publish_settings, 'html.parser') profiles = soup.find_all('publishprofile') ftp_profile = [profile for profile in profiles if profile['publishmethod'] == 'FTP'][0] matches = re.search('...
5,325,249
def main(): """Given a .bed file with probe sequences, runs Jellyfish to screen these for high abundance k-mers.""" startTime = timeit.default_timer() # Allow user to input parameters on command line. userInput = argparse.ArgumentParser(description=\ '%s version %s. Requires a .bed file cont...
5,325,250
def train(name,train_data:List[tuple],test_data=None)->tuple: """ Train Naive Bayes Classifier for Multinomial Models :param list train_data: list train data of tuple (text,tag) :param object get_features: function of features :param list test_data: list test data of tuple (text,tag) :return: ...
5,325,251
def validate_article(article_json): """ Validate the content of a raw article """ if article_json is None: return False try: # Filter title if not vstrlen(article_json['title'], 16): return False # Filter contents if not vstrlen(article_json['con...
5,325,252
def apply_overrides( posts: NewPostsInfo, overrides: GlobalOverridesConfig, subscriptions: Iterable[Subscription], ) -> None: """Apply global overrides to a set of notifications. Modifies notifications in-place. :param posts: The group of notifications to modify. :param overrides: Override...
5,325,253
def get_model_memory_usage(batch_size, model): """ Estimate how much memory the model will take, assuming all parameters is in float32 and float32 takes 4 bytes (32 bits) in memory. :param batch_size: :param model: :return: """ # Calculate the total number of outputs from all layers ...
5,325,254
def calculate_deltaangle_distance( org_ligs, smiles_keys, fg_factory, file_prefix=None ): """ Calculate the change of bite angle of each ligand in the cage. This function will not work for cages built from FGs other than metals + AromaticCNC and metals + AromaticCNN. Parameters ...
5,325,255
def wait_for_file_to_finish_writing(**args) -> tuple: """ This wait shouldn't be required but appears to be help with larger files. """ config = args.get('config') logging.info("waiting {} seconds for file to finish writing and unlock".format(config.BULK_IMPORT_WAIT)) time.sleep(config.BULK_IMPO...
5,325,256
def get_max_id(connection, generic_sensor_type: str) -> int: """ Get the max id of a given generic sensor type. :param generic_sensor_type: "asset", "market", or "weather_sensor" """ t_generic_sensor = sa.Table( generic_sensor_type, sa.MetaData(), sa.Column("id", sa.Integer),...
5,325,257
def downloadEnclosures(i, q): """This is the worker thread function. It processes items in the queue one after another. These daemon threads go into an infinite loop, and only exit when the main thread ends. """ while True: print '%s: Looking for the next enclosure' % i url ...
5,325,258
def one(count, test_number, p): """ create a return list. IRAM have 128 byte, so you can fill most 64 PC value to IRAM. """ instruction_len = 5 code_page_start_addr = test_number << 11 fisrt_addr = code_page_start_addr + 3 # reserve space for ljmp end_addr = code_page_start_addr + 0x7FA...
5,325,259
def _temp_dict_file_name(): """Name of the expected python dictionary as a json file from run_external_python(). .. versionadded:: 9.1 """ return '__shared_dictionary__'
5,325,260
def test_set_empty(): """Test set on empty table.""" string = "test" ht = HashTable() check = ht._hashing(string, ht._size) ht.set("test", "test") assert ht._table[check] == [(check, "test")]
5,325,261
def pSpectrum( data: Union[np.ndarray, List, None], samplefreq: float = 44100 ) -> (np.ndarray, np.ndarray): """Power spectrum computation. Compute the power spectrum of a data set using standard ffts, after padding the data set to the next higher power of 2. Assumes data is regularly sampled in th...
5,325,262
def main(): """ Run when the program is being used standalone, uses stdin as the input """ parser = TreeArgumentParser() parser.add_argument('-i', '--mode', '--input-mode', choices=map_mode, default='auto', nargs='?', ...
5,325,263
def accumulate_grad_ms(session, model, verbose=True): """run the given model over its data""" start_time = time.time() iters = 0 # zeros initial state for all devices state = [] for k in range(model.gpu_num): state.append(session.run(model.initial_state(k))) # evaluate loss and fin...
5,325,264
def run(vendor): """Script runner. Args: vendor (Type[Vendor]): Subclass of :class:`~pcapkit.vendor.default.Vendor` from :mod:`pcapkit.vendor`. Warns: VendorRuntimeWarning: If failed to initiate the ``vendor`` class. """ print(f'{vendor.__module__}.{vendor.__name__}: {vendor.__doc...
5,325,265
def save() -> None: """Save the image on a file.""" figure.save_image()
5,325,266
def get_environment(config, stage): """Find default environment name in stage.""" stage_data = get_stage_data(stage, config.get('stages', {})) if not stage_data: sys.exit(NO_STAGE_DATA.format(stage)) try: return stage_data['environment'] except KeyError: sys.exit(NO_ENV_IN_ST...
5,325,267
def all(a, axis=None): """ all(a, [,axis=(axis0, axis1, ...)]) --> bool or Array of booleans Returns True if all the components of iterable a evaluate to True. If axis are specified will return an Array of all(x) for x in a.axisiter(*axis). >>> A = Array([[True,True,True],[False,True,False...
5,325,268
def anisotropic_Gaussian(ksize=25, theta=np.pi, l1=6, l2=6): """ https://github.com/cszn/KAIR/blob/master/utils/utils_sisr.py Generate an anisotropic Gaussian kernel Args: ksize : e.g., 25, kernel size theta : [0, pi], rotation angle range l1 : [0.1,50], scaling of eigenvalue...
5,325,269
def get_mail(db, messages_obj, msg_id, user_id='me'): """Fetch a message from GMail by id and adds it to passed db. Args: db: Local db connection object. messages_obj: Authenticated GMail user object. msg_id: Id of Gmail message. user_id: User's email address. The special value ...
5,325,270
def get_history(ticker, start_date, end_date = None, granularity=granularity): """Fetch/load historical data from Coinbase API at specified granularity params: start_date: (str) (see pandas.to_datetime for acceptable formats) end_date: (str) granularity: (int) seconds (default: 300) ...
5,325,271
def run_command(net,cmd_list,cmd_str): """ This function returns the output of IOS command Exit script if there is no any network device. Parameters ---------- net (list): network device ip andid cmd_list (list): available IOS commands in list cmd (string): available IOS commands in str...
5,325,272
def fakemag_to_parallax(fakemag, mag, fakemag_err=None): """ To convert fakemag to parallax, Magic Number will be preserved :param fakemag: astroNN fakemag :type fakemag: Union[float, ndarray] :param mag: apparent magnitude :type mag: Union[float, ndarray] :param fakemag_err: Optional, fake...
5,325,273
def save(potential, f): """ Write a :class:`~gala.potential.PotentialBase` object out to a text (YAML) file. Parameters ---------- potential : :class:`~gala.potential.PotentialBase` The instantiated :class:`~gala.potential.PotentialBase` object. f : str, file_like A filename...
5,325,274
def provenance_stamp(routine): """Return dictionary satisfying QCSchema, https://github.com/MolSSI/QCSchema/blob/master/qcschema/dev/definitions.py#L23-L41 with QCElemental's credentials for creator and version. The generating routine's name is passed in through `routine`. """ return {'creator'...
5,325,275
async def test_simple_raise(event_loop, rpc_peer): """Check basic error routing - RpcMethodError is raised and contains info about the actual remote error. """ REMOTE_EXCEPTIONS = [ ('RuntimeError', 'some message?'), ('ValueError', 'another message?') ] async with rpc_peer('util'...
5,325,276
def index_of(y): """ A helper function to get the index of an input to plot against if x values are not explicitly given. Tries to get `y.index` (works if this is a pd.Series), if that fails, return np.arange(y.shape[0]). This will be extended in the future to deal with more types of label...
5,325,277
def get_centered_box(center: np.ndarray, box_size: np.ndarray): """ Get box of size ``box_size``, centered in the ``center``. If ``box_size`` is odd, ``center`` will be closer to the right. """ start = center - box_size // 2 stop = center + box_size // 2 + box_size % 2 return start, stop
5,325,278
def save_all_editors(): """ Saves all editors. """ _window().save_all()
5,325,279
def _make_context(frames, cameras): """ Generate Context named tuple using camera, frame information Args: - cameras: - frames: Returns: A Context named tuple encapsulating given information """ return Context(cameras=cameras, frames=frames)
5,325,280
def test_shift_array_if_len_even(): """ test for if number of elements is even """ old_array = [0, 0, 0, 0] value = 1 old_array = shift_array.insert_shift_array(old_array, value) assert old_array[2] == 1
5,325,281
def isfile(hdfs_path, project=None): """ Return True if path refers to a file. Args: :hdfs_path: You can specify either a full hdfs pathname or a relative one (relative to your Project's path in HDFS). :project: If this value is not specified, it will get the path to your project. If you ne...
5,325,282
def get_list_from_file(filename): """ Returns a list of containers stored in a file (one on each line) """ with open(filename) as fh: return [_ for _ in fh.read().splitlines() if _]
5,325,283
def convert_hard_sigmoid(g, op, block): """Operator converter for hard_sigmoid.""" slope = op.attr("slope") x = g.get_node(op.input("X")[0]) dtype = infer_type(x).checked_type.dtype out = x * _expr.const(slope, dtype) + _expr.const(0.5, dtype) out = _op.clip(out, 0, 1) g.add_node(op.output(...
5,325,284
def import_recipe(): """Import recipe from base64 encoded text.""" form = Import() errors = None if form.validate_on_submit(): encoded = request.form["encoded"] try: decoded = loads(b64decode(encoded.encode("utf-8")).decode("utf-8")) # recipe table ti...
5,325,285
def parse_xyz(filename, nbits): """Read xyz format point data and return header, points and points data.""" pointstrings = [] with open(filename) as points_file: for line in points_file: if not line.startswith('#'): if not line.isspace(): line = line.r...
5,325,286
def compare_vecs(est, truth, zero_tol=0): """ Parameters ---------- est: array-like The estimated vector. truth: array-like The true vector parameter. zero_tol: float Zero tolerance for declaring an element equal to zero. Output ------ out: dict Di...
5,325,287
def accumulator(init, update): """ Generic accumulator function. .. code-block:: python # Simplest Form >>> a = 'this' + ' ' >>> b = 'that' >>> c = functools.reduce(accumulator, a, b) >>> c 'this that' # The type of the initial value determines outp...
5,325,288
def process_po_folder(domain, folder, extra=''): """ Process each PO file in folder """ result = True for fname in glob.glob(os.path.join(folder, '*.po')): basename = os.path.split(fname)[1] name = os.path.splitext(basename)[0] mo_path = os.path.normpath('%s/%s%s' % (MO_DIR, name, MO...
5,325,289
def create_service( *, db_session: Session = Depends(get_db), service_in: ServiceCreate = Body( ..., example={ "name": "myService", "type": "pagerduty", "is_active": True, "external_id": "234234", }, ), ): """ Create a new s...
5,325,290
def set_brightness_dimmed(deck_id: str, brightness_dimmed: int) -> None: """Sets the percentage value that will be used for dimming the full brightness""" state.setdefault(deck_id, {})["brightness_dimmed"] = brightness_dimmed _save_state()
5,325,291
def test_get_homography_matrx(): """ Test if the function gives exact homography matrix """ test_src = [[0, 6], [3, 40], [32, 54], [40, 60]] test_dst = [[0, 0], [0, 30], [30, 0], [30, 30]] result = get_homography_matrix(test_src, test_dst) expected_result = cv2.findHomography(np.array(test_s...
5,325,292
def GetBuildRevisions(src_dir, webkit_dir=None, revision_dir=None): """Parses build revisions out of the provided directories. Args: src_dir: The source directory to be used to check the revision in. webkit_dir: Optional WebKit directory, relative to src_dir. revision_dir: If provided, this dir will be...
5,325,293
def _get_scheme_dict(distribution_name: str) -> Dict[str, str]: """Calculate the scheme dictionary for the current Python environment.""" scheme_dict = sysconfig.get_paths() installed_base = sysconfig.get_config_var("base") assert installed_base # calculate 'headers' path, not currently in sysconf...
5,325,294
def biokit_data(filename, where=None): """Simple utilities to retrieve data sets from biokit/data directory""" import os import easydev biokit_path = easydev.get_package_location('biokit') share = os.sep.join([biokit_path , "biokit", 'data']) # in the code one may use / or \ if where: ...
5,325,295
def setup_module(): """ Build the required testing extension module """ global wrap # Check compiler availability first if not util.has_c_compiler(): pytest.skip("No C compiler available") if wrap is None: config_code = """ config.add_extension('test_a...
5,325,296
def get_handler(event, context): # pylint: disable=unused-argument """REST API GET method to get data about a Minecraft game server.""" # gather the server data name = event.get('pathParameters', {}).get('name') server = gather(name) # return the HTTP payload return { 'statusCode': 200...
5,325,297
def get_item(dataframe: DataFrame, col: str, new_col: str, index: any) -> DataFrame: """Return DF with a column that contains one item for an array :param str col: name of the column :param str new_col: type of the new column :param any index: the index key Examples: ``` SectionName: ...
5,325,298
def appdatadirectory(): """Attempt to retrieve the current user's app-data directory This is the location where application-specific files should be stored. On *nix systems, this will be the ${HOME}/.config directory. On Win32 systems, it will be the "Application Data" directory. Note that for ...
5,325,299