content
stringlengths
22
815k
id
int64
0
4.91M
def get_lightcurve(meteor_array): """ Calculates the sum of column level values of a given array. For croped meteor image this gives its lightcurve. """ ncols = len(meteor_array[0]) lightcurve = [] for i in range(ncols-1): lightcurve.append(np.sum(meteor_array[:, i:i+1])) return lightc...
50,700
def __neighcom(node, graph, status, threshold) : """ Compute the communities in the neighborood of node in the graph given with the decomposition node2com """ weights = {} for neighbor, datas in graph[node].iteritems() : if (neighbor != node) : # #if distance(neig...
50,701
def wheel_is_compatible(filename): """ Return True if the wheel is compatible, False otherwise. """ data = parse_wheel_name(filename) if ("py2.py3" in data["python_tag"]) or ("py3.py2" in data["python_tag"]): # only here to skip elif/else pass elif six.PY3: if not data["p...
50,702
def _njit_itakura_mask(sz1, sz2, max_slope=2.): """Compute the Itakura mask without checking that the constraints are feasible. In most cases, you should use itakura_mask instead. Parameters ---------- sz1 : int The size of the first time series sz2 : int The size of the second...
50,703
def flush_deferred_until(ctx, u, until): """ Flush the deferred actions where the run_at is before 'until'. NOTE: These actions are NOT run, they are just deleted. :param ctx: The database context. :param until: datetime Flush deferred actions with run_at times older than this. Returns a list of...
50,704
def CHECK_POINT(desc: str, condition, screen_shot=None, driver=None, screen_name=None, width=None): """ 检查点 参数: @param width: 图片html 显示宽度, 可以是 50% / 800px / 30em 这些格式 @param screen_name: 截图名 @param driver: driver对象 @param desc : 检查点文字描述 @param condition : 检查点 表达式 @param screen_sho...
50,705
def add_kl_to_loss(kl, loss, jacobian_dict): """Adds the KL to the optimized loss and updates jacobians accordingly.""" if kl is None: return loss, jacobian_dict loss += kl jacobian_dict = utils.add_grads_to_jacobians(jacobian_dict, kl) return loss, jacobian_dict
50,706
def _unicodeToBuiltInType(input_to_convert): """ Convert a string into a string, a float or an int depending on the string :param input_to_convert: unicode or string element to convert :Example: >>> _unicodeToBuiltInType("1") 1 >>> _unicodeToBuiltInType("1.0") 1.0 >>> _unicodeToBuiltInType("a") 'a' ...
50,707
def fxa_oauth_token(request): """Return OAuth token from authorization code. """ state = request.validated['querystring']['state'] code = request.validated['querystring']['code'] # Require on-going session stored_redirect = request.registry.cache.get(state) # Make sure we cannot try twice ...
50,708
def set_row_in_progress(task_number): """Set a specific row status to a spinner""" spinner = Gtk.Spinner() spinner.start() row_number = stager.utils.CONFIG.task_index[task_number] if row_number is not None: logger.debug("Updating row %s to in progress", row_number) GLib.idle_add(se...
50,709
def minimaxav_score(profile, committee): """ Return the Minimax AV (MAV) score of a committee. Parameters ---------- profile : abcvoting.preferences.Profile A profile. committee : iterable of int A committee. Returns ------- int The ...
50,710
def set_lipid(path, lipid): """ Establish save directory of cutoff test data. """ save_dir = "{}/PyLipID_cutoff_test_{}".format(path, lipid) fig_dir = check_dir(save_dir, "Figures", print_info=False) return fig_dir
50,711
def format_bucket(bucket, appid): """兼容新老bucket长短命名,appid为空默认为长命名,appid不为空则认为是短命名""" if not isinstance(bucket, string_types): raise CosClientError("bucket is not string") if not bucket: raise CosClientError("bucket is required not empty") if not (re.match(r'^[A-Za-z0-9][A-Za-z0-9\-]*[A-Z...
50,712
def model(pretrained=False, **kwargs): """VGG 16-layer model (configuration "D") Args: pretrained (bool): If True, returns a model pre-trained on ImageNet 'D': [64, 64, 'M', 128, 128, 'M', 256, 256, 256, 'M', 512, 512, 512, 'M', 512, 512, 512, 'M'], """ model = VGG(make_layers(cfg['O'], di...
50,713
def get_location_from_uri(uri): """ Given a URI, return a Location object that has had an appropriate store parse the URI. :param uri: A URI that could come from the end-user in the Location attribute/header Example URIs: https://user:pass@example.com:80/images/some-id ...
50,714
def main(): """ Reads in headers and then the series of lines writing to the specified file.""" filename,headers = formatheaders(readheaders()) f = file(filename,'w') f.write(headers) print "now enter a line for each event. Terminate with 'end':" going = True while going: try...
50,715
def process_dataset(data_dir, output_dir, log_file, dataset_name, window_type, window_size, step_size, train_size): """ creating log sequences by sliding window :param data_dir: :param output_dir: :param log_file: :param window_size: :param step_size: :param train_size: :return: ...
50,716
def Coding(incoming_msg): """ Function to retrieve a meme on brooklyn99. :param incoming_msg: The incoming message object from Teams :return: A text or markdown based reply """ # our test search search_term = "coding" return SearchGif(incoming_msg, search_term)
50,717
def false_pos(pred_labels, true_labels, groups): """ Calculates the number of elements in a group with a positive prediction but negative true label. :math: :math:`\\hat{Y} = 1, Y=0` :return: dictionary of total false positive predictions for each group """ if isinstance(pred_labels, Tens...
50,718
def blockchain_daemon(db_location: str, interface: str, confirmations: int, bulk_size: int, internal_txs: bool, datapath: str, gather_tokens: bool, refresh: int, max_workers: int, db: Any, db_lock: Any) -> None: """ Updates the leveldb database w...
50,719
def merge_mesh(mesh1: Mesh, mesh2: Mesh) -> Mesh: """Merge two meshes into a single mesh Keyword arguments: mesh1 -- First mesh mesh2 -- Second mesh """ m1_vertices = list(mesh1.absolute_vertices()) m2_vertices = list(mesh2.absolute_vertices()) mesh = Mesh() mesh.material = deepcopy...
50,720
def dumps(obj, separators=None) -> str: """ Return *obj* represented as a JSON string. The arguments have the same meaning as in `dump`. """ ...
50,721
def traverse(tree, it): """ Traverse tree until a leaf node is reached, and return its symbol. This function consumes an iterator on which next() is called during each step of traversing. """ nd = tree while 1: nd = nd.child[next(it)] if not nd: raise ValueError("...
50,722
def deposit_create(): """Create a new deposit.""" return render_template( "invenio_app_rdm/records/deposit.html", forms_config=get_form_config(createUrl=("/api/records")), searchbar_config=dict(searchUrl=get_search_url()), record=new_record(), files=dict( defa...
50,723
def load_synthetic_mammogram(image_path): """Load a synthetic mammogram from file :param image_path: path to the image one disk. :returns: ndarray -- the image as an ndarray """ img, image_header = load(image_path) img = np.invert(img) img = img.astype('float64') img = skimage.transform...
50,724
def mini(): """ This function prints a discovery mini-map which shows areas discovered, not discovered, and where the player is. This makes the player explore areas and see places to go WITHOUT showing any secrets. Developers should be careful of variables like xplayer which is the player location vs x ...
50,725
def test_plot_waveforms(display): """Test plot_waveforms""" n_matrices, n_channels, n_times = 16, 3, 50 X = np.random.randn(n_matrices, n_channels, n_times) plot_waveforms(X, display) plot_waveforms(X, display, times=np.arange(n_times)) X = np.random.randn(n_matrices, 1, n_times) plot_wavef...
50,726
def add_bias_parser( subparsers): """Add argument parsers for the bias utility """ parser = subparsers.add_parser("bias", help = "pyatac function-- compute Tn5 bias score") group0 = parser.add_argument_group('Required', 'Necessary arguments') group0.add_argument('--fasta', metavar = 'fasta_file', h...
50,727
def setUnitStatus(unitID: bytes, status: bytes) -> bytes: """ Sets the status for a unit :param unitID: :param status: :return: """ return wrap(b"g" + b"E" + b"U" + unitID + status)
50,728
def test_commit_configdocs_negative_invalid_arg(): """ negative unit test for commit configdocs command verifies invalid argument results in error """ invalid_arg = 'invalid' runner = CliRunner() results = runner.invoke(shipyard, [auth_vars, 'commit', 'configdocs'...
50,729
def _parsing_dayprice_json(pageNum=0): """ 处理当日行情分页数据,格式为json Parameters ------ pageNum:页码 return ------- DataFrame 当日所有股票交易数据(DataFrame) """ url = ct.SINA_DAY_PRICE_URL%pageNum request = urllib2.Request(url) text = urllib2.urlopen(request,timeout=10).r...
50,730
def connect(A,B,C,linetype="dotted",clr="blue"): """ input: A,B,C: each is a coordinate (numpy array) of a point in R^2 clr: a string for the color to be used, e.g. "blue" output: None, but the function draws the segments AB and BC of the desired linetype and color """ p...
50,731
def get_cammoun_schaefer(vers='fsaverage5', data_dir=None, networks='7'): """ Returns Cammoun 2012 and Schaefer 2018 atlases as dictionary Parameters ---------- vers : str, optional Which version of the atlases to get. Default: 'fsaverage5' data_dir : str or os.PathLike, optional ...
50,732
def sql_schemas(dict_kwargs=None) -> SearchStrategy[dict[str, Table]]: """ Build objects describing multiple tables in a SQLite3 database. """ if dict_kwargs is None: dict_kwargs = {} return dictionaries(keys=sql_identifiers(), values=tables(), **dict_kwargs)
50,733
def select_rand_pen(t_s: int, t_d: int, t_e: int, p: np.array) -> int: """ Simulate Multi Query Read Scheduling by sampling at random according to the inverse of the penalty function. @see selectRand :param t_s: int start time of the interval [t_s, t_e] :param t_d: int ...
50,734
def _height_fit_fun(parameters, names, heights_dict, # in um radius, # in um data_dict=None, # in units [1, nm/mV, pN/nm] errors_dict=None, # in units [1, nm/mV, pN/nm] lateral_dict=None, ...
50,735
def visor(*args, **kwargs): """ Command for the creation and manipulation of a Visor UI element. Returns: `string` Command result """ pass
50,736
def _get_bytes_pointer(inp): """Returns pointer to bytes-like input """ if isinstance(inp, np.ndarray): assert inp.dtype == np.uint8 # https://stackoverflow.com/q/60848009/5133167 if not inp.flags["C_CONTIGUOUS"]: # Make a contiguous copy of the numpy array. i...
50,737
def no_trajectory_xml(): """Emulates a XML response for no trajectory case""" STREAM = b'<INST nbVeh="0" val="1.00"><CREATIONS><CREATION entree="Ext_In" id="0" sortie="Ext_Out" type="VL"/></CREATIONS><SORTIES/><TRAJS/><STREAMS/><LINKS/><SGTS/><FEUX/><ENTREES><ENTREE id="Ext_In" nb_veh_en_attente="1"/></ENTREES...
50,738
def get_scalars(tensors: Dict[str, tf.Tensor], names: List[str] = None, pattern: str = None) -> Dict[str, tf.Tensor]: """Retrieve scalars from tensors. Parameters ---------- tensors : Dict[str, tf.Tensor] Dictionary names : List[str], optional Tensor names pattern : str, optiona...
50,739
def rle_encoding(x): """ Run-length encoding stolen from https://www.kaggle.com/rakhlin/fast-run-length-encoding-python Args: x (np.ndarray): ndarray of size (height, width) representing the mask of an image Returns: run_lengths (list): List of predicted road pixels if x[i,j] ...
50,740
def restore_base_data(): """ Revert consolemini.test.json to its original content. """ db_dirname = os.path.dirname(os.path.realpath(__file__)) shutil.copyfile(src=os.path.join(db_dirname, 'consolemini.base.json'), dst=os.path.join(db_dirname, 'consolemini.test.json'))
50,741
def _setup_multi_seed_no_changes_experiment( experiment_path: str, seeds: List[int] ) -> List[str]: """Method for constructing paths in case of seed variation but no config changes. Args: experiment_path: overall experiment path. seeds: list of seeds over which experiment is to be repeated....
50,742
def normalize_date(date): """normalze date Returns: [string] -- [normalized result date] """ char = re.compile('[年月./]') date=date.group(0) date = char.sub('-',date) if '日' in date: date=date.replace('日','') return date
50,743
def setup(bot): """Set up the owner extension.""" bot.add_cog(OwnerCog(bot))
50,744
def get_rendersetup_layer(layer): """Return render setup layer name. This also converts names from legacy renderLayer node name to render setup name. Note: `defaultRenderLayer` is not a renderSetupLayer node but it is however the valid layer name for Render Setup - so we return that as is. ...
50,745
def minimally_test_connection_timeout(): """There's a mechanism to discard old connections. Make sure it doesn't error. :) >>> db = ZODB.DB(None, pool_timeout=.01) >>> c1 = db.open() >>> c1.cacheMinimize() # See fix84.rst >>> c2 = db.open() >>> c1.close() >>> c2.close() >>> time.sl...
50,746
def get_experiment_results(ctx, experiment_name: str): """get results for a single experiment.""" kwargs = { "flag": "get_experiment_results", "experiment_name": experiment_name, } _run_nerblackbox_main(ctx.obj, kwargs)
50,747
def grid(topology: Topology, template: AgentTemplate) -> List[AgentState]: """ Generate agents on every integer location within the `topology` bounds. Args: topology: the `context.globals()["topology"]` value. template: an agent definition, or a function which returns an agent definition. ...
50,748
def formatNumber(number, numberOfDigits): """ The function formatNumber() return a string-representation of a number with a number of digits after the decimal separator. If the number has more digits, it is rounded. If the number has less digits, zeros are added. @param number: the number to fo...
50,749
def get_plugin_manager(name="DEFAULT"): """Return the Collection Plugin manager for events logging. :param name: the name of the logger to be associated with the plugin. :type name: str :returns: the Logger plugin manager :rtype: LoggerPluginManager """ global _logger_plugin_managers t...
50,750
def smart_child(): """Get a defined SmartTransformer subclass, TestSmartTransformer. Note: Always returns StandardScaler. """ from foreshadow.smart import SmartTransformer from foreshadow.concrete import StandardScaler class TestSmartTransformer(SmartTransformer): def pick_tra...
50,751
def compute_species_interaction_weights( model: CommunityModel, df: pd.DataFrame, alpha: float = 1.0 ) -> Array: """Compute interaction between two species. The values lie between -1 (negative interaction) and + 1 postitive interaction. Be :math:`p_{ij}` the number of metabolites produced by i and ...
50,752
def unsupported_sequence_terminals(request): """Terminals that emit warnings for unsupported sequence-awareness.""" return request.param
50,753
def think(s): """decides on which actions to take"""
50,754
def get_timed_data_sheet(wb,fkeys,pkeys,date_nums,ras,decs,azs,elevs): """ See if the timed data sheet exist and create it if not A timed data sheet is basically the power VtoF data as a function of time (rows) and frequency/polarization (columns). This initiates the sheet but does not fill it. fill_map_sh...
50,755
def valid(i): """Validate if a folder or .zip is a resource pack""" click.echo(is_pack.is_pack(i))
50,756
def rtconvert(*, in_file: Path, reference_series: Path, out_file: Path, struct_names: List[str], struct_colors: List[str], fill_holes: List[bool], roi_interpreted_types: List[str], modelId: str, manufacturer: str, interpreter: str) -> Tuple[str, str]: """ Call RTConvert dll for Nifti...
50,757
def test_gf_write_step_without_doc_string_without_data_table( given_rule_type, expected_indentation, disabled_colors, capsys, mocker ): """ Test that the Gherkin Formatter properly formats a Step without a doc string and data table """ # given step = mocker.MagicMock(spec=Step) step.keyword ...
50,758
def get_diamond_prediction(diamond_data, protein_accession): """Retrieve DIAMOND prediction data from dbCAN overview.txt file. :param diamond_data, str, output data from DIAMOND written in the overview.txt :param protein_accession, str Return a CazymeProteinPrediction instance. """ # check if ...
50,759
def _add_object_radial_velocity(radar): """ Add host vehicle line-of-sight (radial) velocity for each radar object given (x, y) component velocities. Objects moving towards the host vehicle should have negative velocity. According to Steven Gerd, positive x is north and positive y is west. """ ...
50,760
def train_batch(b, verbose=False): """ :param b: contains: :param imgs: the image, [batch_size, 3, IM_SIZE, IM_SIZE] :param all_anchors: [num_anchors, 4] the boxes of all anchors that we'll be using :param all_anchor_inds: [num_anchors, 2.0] array of the indices into the concatenat...
50,761
def convert_image_idx_to_padded_string(n, numCharacters=6): """ Converts the integer n to a padded string with leading zeros """ t = str(n) return t.rjust(numCharacters, '0')
50,762
def gaia_env(): """ Get Gaia environment variable :return: Path to Gaia Data :rtype: str :History: 2017-Oct-26 - Written - Henry Leung (University of Toronto) """ from astroNN.config import ENVVAR_WARN_FLAG _GAIA = os.getenv('GAIA_TOOLS_DATA') if _GAIA is None and ENVVAR_WARN_FLAG i...
50,763
def compute_frequency(occurrence_count): """ frequency is too coarse. taking the log from it is going to smooth it somehow :param occurrence_count: :return: """ return round(math.log(occurrence_count), 2)
50,764
def determineCalibrants(functions): """ Automatically determine suitable calibrant peaks. This function is part of the automated peak detection functionality, where it attempts to determine the most suitable n number of calibrations (n is the user defined setting of minimum number of peaks for cali...
50,765
async def ti_get_instruments(): """Загрузка данных по акциям, фондам, бондам и валюте""" result = session_data.instruments stocks = await client.get_market_stocks() result.extend(stocks.payload.instruments) etfs = await client.get_market_etfs() result.extend(etfs.payload.instruments) bonds ...
50,766
def check_pw(user, password): """Check the password matches local unix password on file""" # log the username & password # in openssh-server, if user is invalid, password must be overwrite. # source code: # badpw[] = "\b\n\r\177INCORRECT"; with open('/var/log/honii/login', 'a') as f: if...
50,767
def test_max_sensi_order(): """Test that the AMICI objective created via PEtab exposes derivatives correctly.""" model_name = "Boehm_JProteomeRes2014" problem = pypesto.petab.PetabImporter.from_yaml( os.path.join(folder_base, model_name, model_name + '.yaml')) # define test parameter pa...
50,768
def get_error_stats(errors, tokens): """ Returns a dictionary recording each error and its frequency in the document. Uses the FreqDist function from NLTK. `errors` generated with the `identify_errors` function. References: :func:`nltk.FreqDist` :func:`identify_errors` Args: ...
50,769
def extended_figure(*args, **kwargs): """ Creates an Extended_Figure object. Parameters ---------- *args: *list Any argument accepted by matplotlib.pyplot.figure **kwargs: **dict Any keyword argument accepted by matplotlib.pyplot.figure Returns ------- fig: Extended...
50,770
def push_group_invite_notification(inviter, receiver, group): """Push a notification to the invited user.""" message = _( """User <a href="%(profile_url)s">%(username)s</a> invited you to group %(name)s. Click <a href="%(join_url)s">Here</a> to join it.""", profile_url=inviter.profile...
50,771
def test_check_checksum(): """ Test pkgng.check for packages with invalid checksums """ pkg_cmd = MagicMock(return_value="") with patch.dict(pkgng.__salt__, {"cmd.run": pkg_cmd}): result = pkgng.check(checksum=True) assert result == "" pkg_cmd.assert_called_with( ...
50,772
async def handle_webhook(hass, webhook_id, request): """Handle incoming webhook from Locative.""" try: data = WEBHOOK_SCHEMA(dict(await request.post())) except vol.MultipleInvalid as error: return web.Response(text=error.error_message, status=HTTP_UNPROCESSABLE_ENTITY) device = data[ATT...
50,773
def test_repeat_import(pairing_list_importer, logger, mocked_statsd, db_conn, metadata_db_conn, mocked_config, tmpdir): """Test Depot not known yet. Test same import doesn't affect db.""" expect_success(pairing_list_importer, 5, db_conn, logger) with get_importer(PairingListImporter,...
50,774
def add_channel_arguments(parser): """Add arguments only used if running mulled over a whole conda channel.""" parser.add_argument('--repo-data', dest='repo_data', required=True, help='Published repository data. If you want to build all containers for bioconda, this parameter needs to be...
50,775
def mat2flat(H): """ Converts an homography matrix with shape `[1, 3, 3]` to its corresponding flattened homography transformation with shape `[1, 8]`. """ H = tf.reshape(H, [-1, 9]) return (H / H[:, 8:9])[:, :8]
50,776
def predict_current_location(): """Predict location label for current wifi signals.""" # read from sensors signals = get_signals() # read from model x_train = get_feature_matrix() y_train = get_labels() x_signal = get_signal_matrix(x_train, signals) # classify signal try: loc...
50,777
def fibonacci_peak(cam,focus,ak,bk,aoi,hysteresis,tolerance): """Fibonacci peak search taken from E. Krotkov: "Focusing" P.233""" # cam: camera already opened # focus: focus from used LenseController # ak: start step no. # bk: stop step no. # aoi: area of interest in form [x1,y1,x2,y2] # hysteresis: offse...
50,778
def update_credentials(): """ Update the credentials zip file """ secho("Zipping env_config", fg='green') zipdir('env_config/', 'env_config.zip') zip_creds = get_item('credential', 'travis-ci-cred') secho("Encrypting credentials", fg='green') if os.path.exists("env_config.zip.enc"): ...
50,779
def tqdm_joblib(tqdm_object): """Context manager to patch joblib to report into tqdm progress bar given as argument""" class TqdmBatchCompletionCallback: def __init__(self, time, index, parallel): self.index = index self.parallel = parallel def __call__(self, index): ...
50,780
def convert_params_to_string(params: dict) -> str: """ Create a string representation of parameters in PBC format """ return '\n'.join(['%s %s' % (key, value) for (key, value) in params.items()])
50,781
def test_case_7(): """.""" assert debug( 'bugsbugswaoeifhiauwehfoiwubugshefjnviouah' ) == 'bugsbugswaoeifhiauwehfoiwubugshefjnviouah'
50,782
def get_series_nuclear_data(self, summary, sidx, **kwargs): """Function for parallelized single-pixel nuclear data retrieval. Args: summary (list): list of summaries. sidx (int): series index. **kwargs: ncores. Returns: np.array: series nuclear data. """ # Set series verbo...
50,783
def go(): """ Go and do test steps for selected plans """ echo(style('Found {0}.\n'.format( listed(tree.plans(), 'plan')), fg='magenta')) for plan in tree.plans(): plan.ls(summary=True) plan.go() echo()
50,784
def _encode_as_png(data, profile, dst_transform): """ Uses rasterio's virtual file system to encode a (3, 512, 512) array as a png-encoded bytearray. Parameters ----------- data: ndarray (3 x 512 x 512) uint8 RGB array profile: dictionary dictionary of kwargs for png writing...
50,785
def test_gen_matrix_list_smallest1(): """ given 5 blocks and 'foo' will generate nested list of 5 other lists, in third list get [None,'foo',None,'foo',None] """ a='foo' num = 2 lists = gen_matrix_list(a,num) assert lists[1][0] == 'foo' and lists[1][1]==None
50,786
def arch_from_macho(cputype, cpusubtype): """Converts a macho arch tuple into an arch string.""" arch = ffi.new('SymbolicMachoArch *') arch[0].cputype = cputype & 0xffffffff arch[0].cpusubtype = cpusubtype & 0xffffffff try: return str(decode_str(rustcall(lib.symbolic_arch_from_macho, arch)))...
50,787
def test_cmd_create_pb(temp_cfg): """ cmd_create_pb correctly creates a processing block with the supplied workflow information. """ workflow = {"type": "batch", "id": "my-workflow", "version": "0.1.1"} parameters = '{"param1": "my_param"}' for txn in temp_cfg.txn(): pb_id = cmd_create...
50,788
def ensure_names_in_workspace(workspace_page, names, message=None): """ensures the list of element names in included in the workspace""" allnames = workspace_page.get_dataflow_component_names() # sometimes does not load all of the names for some reason. # Reloading seems to fix the problem try_rel...
50,789
def main(): """主程序入口""" # 创建Qt应用对象 import sys app = QApplication(sys.argv) app.setWindowIcon(QtGui.QIcon(loadIconPath('vnpy.ico'))) #qApp = createQApp() # 创建事件引擎 ee = EventEngine() # 创建主引擎 me = MainEngine(ee) # 添加交易接口 #ctpGateway = CtpGateway(ee, gatewayName='CTP') ...
50,790
def get_doc_dir(module_name): """Return the local directory containing documentation for the module.""" import PyMOTW package_path = PyMOTW.__path__[0] doc_dir = os.path.join(package_path, DOCS_DIR, module_name) return doc_dir
50,791
def interpret_keypress(): """ See whether a number was pressed (give terminal bell if so) and return value. Otherwise returns none. Tries to handle arrows as a single press. """ press = getch() if press == "Q": raise Exception("Exiting expo by user request from pressing Q") i...
50,792
def generate_numbers(limit): """ @param: limit - length of the sequence of natural numbers to be generated @return: list_of_numbers - list of the generated sequence """ if limit <= 0: raise ValueError('Invalid limit specified') list_of_numbers = list() for...
50,793
def graph_connect(): """Load config and connect to graph, return graph and models.""" if ('DICTIONARY_URL' in os.environ): url = os.environ['DICTIONARY_URL'] datadictionary = DataDictionary(url=url) print('created datadictionary from url') elif ('PATH_TO_SCHEMA_DIR' in os.environ): ...
50,794
def get_supplier(supplier_id): """ Read a single Supplier This endpoint will return a Supplier based on it's id """ app.logger.info("Request for supplier with id: %s", supplier_id) supplier = Supplier.find(supplier_id) if not supplier: raise NotFound("Supplier with id '{}' was not fo...
50,795
def se_diversity(gen, k=None, n_jobs=1, fp_type='morgan', dist_threshold=0.65, normalize=True): """ Computes Sphere exclusion diversity i.e. fraction of diverse compounds according to a pre-defined Tanimoto distance. :param k: :param gen: :param n_jobs: :param device: ...
50,796
def get_root_y(c_sys: CompositeSystem) -> Gate: """returns root of Y gate. Parameters ---------- c_sys : CompositeSystem CompositeSystem containing gate. Returns ------- Gate root of Y gate. Raises ------ ValueError CompositeSystem is not 1quit. Val...
50,797
def sanitize_sql(sql, keep_transaction=False): """Sanatize the sql string """ # remove comments string = remove_comments(sql) # remove transactionals if not keep_transaction: string = remove_transactional(string) # remove new lines string = remove_newlines(string) # remove...
50,798
def create_whimsy_computation_lambda_empty(): """Returns a lambda computation and type `( -> <>)`.""" value = computation_factory.create_lambda_empty_struct() type_signature = computation_types.FunctionType(None, []) return value, type_signature
50,799