content
stringlengths
22
815k
id
int64
0
4.91M
def capitalize_title(title): """Convert the first letter of each word in the title to uppercase if needed. :param title: str - title string that needs title casing. :return: str - title string in title case (first letters capitalized). """ pass
5,335,700
def persist_bra(con: Connection, bra: List[Dict]): """ This function is dumb, because it does not take care of the case when bra already exist """ with con.begin(): for entities in bra: for e, data in entities.items(): # https://docs.sqlalchemy.org/en/13/core/tutorial...
5,335,701
def compare_dicts(cloud1, cloud2): """ Compare the dicts containing cloud images or flavours """ if len(cloud1) != len(cloud2): return False for item in cloud1: if item in cloud2: if cloud1[item] != cloud2[item]: return False else: ret...
5,335,702
def ajax_stats(): """ 获取客户统计 :return: """ time_based = request.args.get('time_based', 'hour') result_customer_middleman = customer_middleman_stats(time_based) result_customer_end_user = customer_end_user_stats(time_based) line_chart_data = { 'labels': [label for label, _ in resu...
5,335,703
def check_output(dut, trace): """Check data written to the output FIFO for correctness. The coroutine monitors the data written to the FIFO and checks whether it matches the data of the input trace file. """ # get trace size trace_size = trace.size() # check data written to fifo for correc...
5,335,704
def str2int(string_with_int): """ Collect digits from a string """ return int("".join([char for char in string_with_int if char in string.digits]) or 0)
5,335,705
def grid_to_3d(reward: np.ndarray) -> np.ndarray: """Convert gridworld state-only reward R[i,j] to 3D reward R[s,a,s'].""" assert reward.ndim == 2 reward = reward.flatten() ns = reward.shape[0] return state_to_3d(reward, ns, 5)
5,335,706
def find_routes(paths) -> list: """returns routes as tuple from path as list\ like 1,2,3 --> (1,2)(2,3)""" routes = [] for path in paths: for i in range(len(path)): try: route = (path[i], path[i + 1]) if route not in routes: r...
5,335,707
def plot_class_distributions( training_data_filepath, test_data_filepath, figures_folderpath ): """Plots the training set and test set class distributions""" # Load the training and test data project_dir = Path(__file__).resolve().parents[2] train_set_path = str(project_dir) + training_data_filepath...
5,335,708
def z_step_ncg_hess_(Z, v, Y, F, phi, C_Z, eta_Z): """A wrapper of the hess-vector product for ncg calls.""" return z_step_tron_hess(v, Y, F, phi, C_Z, eta_Z)
5,335,709
def test_table_no_envvar(): """Tests that `table()` raises an exception in the absence of the table name env var.""" assert 'DYNAMODB_TABLE' not in os.environ dynamodb._table = None with pytest.raises(RuntimeError): dynamodb.table()
5,335,710
def list_servers(**kwargs) -> "list[NovaServer]": """List all servers under the current project. Args: kwargs: Keyword arguments, which will be passed to :func:`novaclient.v2.servers.list`. For example, to filter by instance name, provide ``search_opts={'name': 'my-instance'}`` ...
5,335,711
def resolve_xref( app: Sphinx, env: BuildEnvironment, node: nodes.Node, contnode: nodes.Node, ) -> Optional[nodes.reference]: """ Resolve as-yet-unresolved XRefs for :rst:role:`tconf` roles. :param app: The Sphinx application. :param env: The Sphinx build environment. :param node: The cross reference no...
5,335,712
def deploy_tester_contract( web3, contracts_manager, deploy_contract, contract_deployer_address, get_random_address, ): """Returns a function that can be used to deploy a named contract, using conract manager to compile the bytecode and get the ABI""" def f(contract_n...
5,335,713
def ccsValidator(results=None): """ Persist standard file patterns, e.g., '*.fits', 'pd-values*.txt', 'Photo*.txt', using lcatr.schema. """ if results is None: results = [] files = glob.glob('*/*.fits') files += glob.glob('*/*.txt') files += glob.glob('pd-values*.txt') files ...
5,335,714
def make_hashable_params(params): """ Checks to make sure that the parameters submitted is hashable. Args: params(dict): Returns: """ tuple_params = [] for key, value in params.items(): if isinstance(value, dict): dict_tuple = tuple([(key2, value2) for key2, ...
5,335,715
def check_member_role(member: discord.Member, role_id: int) -> bool: """ Checks if the Member has the Role """ return any(role.id == role_id for role in member.roles)
5,335,716
def test_to_graph_should_return_dct_identifier_as_graph() -> None: """It returns a dct_identifier graph isomorphic to spec.""" simpletype = SimpleType() simpletype.identifier = "http://example.com/simpletypes/1" simpletype.dct_identifier = "123456789" src = """ @prefix dct: <http://purl.org/dc/...
5,335,717
def tag_bedpe(b, beds, verbose=False): """ Tag each end of a BEDPE with a set of (possibly many) query BED files. For example, given a BEDPE of interacting fragments from a Hi-C experiment, identify the contacts between promoters and ChIP-seq peaks. In this case, promoters and ChIP-seq peaks of int...
5,335,718
def my_example_serial(datadir="./data", firstfile=0, lastfile=11): """ Calculates the mean for numbers across different data files. Is only run on one process to validate the results of `my_example()`. If the data files do not exist, creates files containing random numbers. Parameters -------...
5,335,719
def point(x: float, y: float, z: float) -> Tuple: """Create a point.""" return Tuple(x, y, z, 1.0)
5,335,720
def partial_pipeline_data(backend, user=None, *args, **kwargs): # pragma: no cover """ Add the session key to a signed base64 encoded signature on the email request. """ data = backend.strategy.request_data() if 'signature' in data: try: signed_details = signing.loads(data['sign...
5,335,721
def arrayinv(F, Fx): """ Args: F: dx.ds function value at x Fx: dx.dx.ds derivative of function at x Returns: """ return np.array([np.linalg.solve(a, b) for a, b in zip(Fx.swapaxes(0,2), F.T)]).T
5,335,722
def schedule_list(req): """List scheduled jobs """ schedule = [] if os.path.exists(SCHEDULE): with open(SCHEDULE) as f: for n, a, t in csv.reader(f): schedule.append({'Name': n, 'Timer': t, 'Action': a}) return {'Err': '', 'Schedule': schedule}
5,335,723
def mil(val): """convert mil to mm""" return float(val) * 0.0254
5,335,724
def ask_number(question, low, high): """Poproś o podanie liczby z określonego zakresu.""" response = None while type(response) != int: try: response = int(input(question)) while response not in range(low, high): response = int(input(question)) except V...
5,335,725
def CheckGypFile(gypfile): """Check |gypfile| for common mistakes.""" if not os.path.exists(gypfile): # The file has been deleted. return with open(gypfile) as fp: return CheckGypData(gypfile, fp.read())
5,335,726
def _beams_longitude_latitude( ping_header: PingHeader, along_track: numpy.ndarray, across_track: numpy.ndarray ) -> Tuple[numpy.ndarray, numpy.ndarray]: """ Calculate the longitude and latitude for each beam. https://en.wikipedia.org/wiki/Geographic_coordinate_system For lonitude and latitude calc...
5,335,727
def true_range_nb(high: tp.Array2d, low: tp.Array2d, close: tp.Array2d) -> tp.Array2d: """Calculate true range.""" prev_close = generic_nb.fshift_nb(close, 1) tr1 = high - low tr2 = np.abs(high - prev_close) tr3 = np.abs(low - prev_close) tr = np.empty(prev_close.shape, dtype=np.float_) for ...
5,335,728
def laplacian_operator(data): """ apply laplacian operator on data """ lap = [] lap.append(0.0) for index in range(1, len(data) - 1): lap.append((data[index + 1] + data[index - 1]) / 2.0 - data[index]) lap.append(0.0) return lap
5,335,729
def _stringmatcher(pattern): """ accepts a string, possibly starting with 're:' or 'literal:' prefix. returns the matcher name, pattern, and matcher function. missing or unknown prefixes are treated as literal matches. helper for tests: >>> def test(pattern, *tests): ... kind, pattern, ...
5,335,730
def enu_to_ecef(ref_lat_rad, ref_lon_rad, ref_alt_m, e_m, n_m, u_m): """Convert ENU coordinates relative to reference location to ECEF coordinates. This converts local east-north-up (ENU) coordinates relative to a given reference position to earth-centered, earth-fixed (ECEF) cartesian coordinates. The...
5,335,731
def yield_nodes(sitemap): """Generator for all node specifications in a sitemap. It yields tuples `(code, depth)` whereas `code` is a string representation of the node and `depth` is a number corresponding to the depth the node corresponds to. """ max_headline_depth = 6 headline_re = r"(={1,...
5,335,732
def is_file_url(share_url: str) -> bool: """判断是否为文件的分享链接""" base_pat = r'https?://[a-zA-Z0-9-]*?\.?lanzou[a-z].com/.+' # 子域名可个性化设置或者不存在 user_pat = r'https?://[a-zA-Z0-9-]*?\.?lanzou[a-z].com/i[a-zA-Z0-9]{5,}/?' # 普通用户 URL 规则 if not re.fullmatch(base_pat, share_url): return False elif re.fu...
5,335,733
def get_compton_fraction_artis(energy): """Gets the Compton scattering/absorption fraction and angle following the scheme in ARTIS Parameters ---------- energy : float Energy of the gamma-ray Returns ------- float Scattering angle float Compton scattering fr...
5,335,734
def ConfigureNoOpAuthIfNeeded(): """Sets up no-op auth handler if no boto credentials are configured.""" if not HasConfiguredCredentials(): if (config.has_option('Credentials', 'gs_service_client_id') and not HAS_CRYPTO): if system_util.InvokedViaCloudSdk(): raise CommandException('\n'.joi...
5,335,735
def is_argspec_compatible_with_types(argspec, *args, **kwargs): """Determines if functions matching 'argspec' accept given 'args'/'kwargs'. Args: argspec: An instance of inspect.ArgSpec to verify agains the arguments. *args: Zero or more positional arguments, all of which must be instances of computa...
5,335,736
def get_span_feats_stopwords(stopwords): """Get a span dependency tree unary function""" return partial(get_span_feats, stopwords=stopwords)
5,335,737
def get_argument_parser(argparser): """Augments the given ArgumentParser for use with the Bonobo ETL framework.""" return bonobo.get_argument_parser(parser=argparser)
5,335,738
def input_file_path(directory: str, file_name: str) -> Path: """Given the string paths to the result directory, and the input file return the path to the file. 1. check if the input_file is an absolute path, and if so, return that. 2. if the input_file is a relative path, combine it with the result_di...
5,335,739
def identify_in_large_person_group(subscription_key): """IdentifyInLargePersonGroup. This will identify faces in a large person group. """ face_base_url = "https://{}.api.cognitive.microsoft.com".format(FACE_LOCATION) face_client = FaceClient(endpoint=face_base_url, credentials=CognitiveServicesCr...
5,335,740
def loss(S, K, n_samples=None): """Loss function for time-varying graphical lasso.""" if n_samples is None: n_samples = np.ones(S.shape[0]) return sum( -ni * logl(emp_cov, precision) for emp_cov, precision, ni in zip(S, K, n_samples))
5,335,741
def test_depth(): """Node.depth.""" root = Node("root") s0 = Node("sub0", parent=root) s0b = Node("sub0B", parent=s0) s0a = Node("sub0A", parent=s0) s1 = Node("sub1", parent=root) s1c = Node("sub1C", parent=s1) s1ca = Node("sub1Ca", parent=s1c) eq_(root.depth, 0) eq_(s0.depth, 1...
5,335,742
def flat_dict(df): """ Add each key-value of a nested dictionary that is saved in a dataframe, as a new column """ for col in df.columns: if type(df[col][0]) == dict: df = pd.concat( [df.drop([col], axis=1), df[col].apply(pd.Series)], axis=1) # sometim...
5,335,743
def train_agent(agent, environment, plot_flag=True, *args, **kwargs): """Train an agent in an environment. Parameters ---------- agent: AbstractAgent environment: AbstractEnvironment plot_flag: bool, optional. Other Parameters ---------------- See rollout_agent. """ agent.t...
5,335,744
async def run_setup_pys( targets_with_origins: TargetsWithOrigins, setup_py_subsystem: SetupPySubsystem, console: Console, python_setup: PythonSetup, distdir: DistDir, workspace: Workspace, union_membership: UnionMembership, ) -> SetupPy: """Run setup.py commands on all exported targets ...
5,335,745
def test_safety_check(mocker, url, safety_check, should_error): """ Test kf_utils.dataservice.delete.safe_delete """ # Setup mocks mock_session = mocker.patch("kf_utils.dataservice.delete.Session")() mock_resp = MagicMock() mock_session.delete.return_value = mock_resp kfids = [f"PT_{i}" ...
5,335,746
def list_tasks(): """ 显示所有任务列表,方便管理任务 :return: """ try: task_id = request.args.get("task_id") task_status = request.args.get('status') # 构造条件查询元组 task_info_list = list() tasks = TaskService.get_tasks_url_num(task_id=task_id, task_status=task_status) f...
5,335,747
def CRUD_remote_followers(author: Author, follower_dict_list: list): """ This will create, update or delete followers based on the remote responses args: author - The author to update the followers on follower_dict_list - The list of followers in private dict form to add to the author's lis...
5,335,748
def make_fixed_size( protein, shape_schema, msa_cluster_size, extra_msa_size, num_res=0, num_templates=0, ): """Guess at the MSA and sequence dimension to make fixed size.""" pad_size_map = { NUM_RES: num_res, NUM_MSA_SEQ: msa_cluster_size, NUM_EXTRA_SEQ: extra_ms...
5,335,749
def codegen_reload_data(): """Parameters to codegen used to generate the fn_urlhaus package""" reload_params = {"package": u"fn_urlhaus", "incident_fields": [], "action_fields": [], "function_params": [u"urlhaus_artifact_type", u"urlhaus_artifact_val...
5,335,750
def urls(page, baseurl=auto, direct=True, prev=True, next=True): """ Return a list of pagination URLs extracted form the page. When baseurl is None relative URLs are returned; pass baseurl to get absolute URLs. ``prev``, ``next`` and ``direct`` arguments control whether to return 'next page', '...
5,335,751
def sinc_filter(audio: tf.Tensor, cutoff_frequency: tf.Tensor, window_size: int = 512, sample_rate: int = None, padding: Text = 'same') -> tf.Tensor: """Filter audio with sinc low-pass filter. Args: audio: Input audio. Tensor of shape [batch, audi...
5,335,752
def _getDataFlows(blocks): """ Given a block dictonary from bifrost.proclog.load_by_pid(), return a list of chains that give the data flow. """ # Find out what rings we have to work with and which blocks are sources # or sinks rings = [] sources, sourceRings = [], [] sinks, sinkRin...
5,335,753
def find_lowest_cost_node(costs: dict, processed: list) -> dict: """Return the node with the lowest cost""" lowest_cost = float("inf") # Infinity lowest_cost_node = None for node in costs: cost = costs[node] if cost < lowest_cost and node not in ...
5,335,754
def main(options): """Parse options and find out what to do""" if options.graph=='numsites': tms=[] sites=[] import pylab for sitenum in range(1,10): options.kin_sites=sitenum options.plot=False xs,ys,Tm=kinetic(options) pylab.plot(...
5,335,755
def scale_img(image, random_coordinate=False): """ 对原图大小进行处理, :param image: :param random_coordinate: :return: """ h, w, c = image.shape if max(h, w) > 640: f_scale = min(640./h, 640./w) # scale factor image = cv2.resize(src=image, dsize=None, fx=f_scale, fy=f_scale, in...
5,335,756
def magnitude(v: Vector) -> float: """computes the magnitude (length) of a vector""" return math.sqrt(sum_of_squares(v))
5,335,757
def pew(text): """PEW -- Percentage of Echomimetic (onomatopoeic) Words.""" pew = None onomatopoeic_words_num = 0 path = '/tmp/onomatopoeic_words_en-1.0.txt' if not os.path.exists(path): url = 'https://raw.githubusercontent.com/korniichuk/phd/master/resources/onomatopoeic_words_en-1.0.txt'...
5,335,758
def topngbytes(name, rows, x, y, **k): """ Convenience function for creating a PNG file "in memory" as a string. Creates a :class:`Writer` instance using the keyword arguments, then passes `rows` to its :meth:`Writer.write` method. The resulting PNG file is returned as bytes. `name` is used to...
5,335,759
def supply_domes1finesk(): """ Real Name: b'"Supply Domes-1Finesk"' Original Eqn: b'MIN("Domes-1 Demad finesk" (Time), (outflow Finesk) )' Units: b'MCM/Month' Limits: (None, None) Type: component b'' """ return np.minimum(domes1_demad_finesk(time()), (outflow_finesk()))
5,335,760
def poll(handle): """ Polls an push_pull handle to determine whether underlying asynchronous operation has completed. After `poll()` returns `True`, `synchronize()` will return without blocking. Arguments: handle: A handle returned by an push_pull asynchronous operation. ...
5,335,761
def _increase_explicit_hydrogen_for_bond_atom( rwmol: Chem.rdchem.RWMol, remove_bidx: bool, bidx: int, remove_eidx: bool, eidx: int, ai_to_remove: list, ) -> Tuple[Chem.rdchem.RWMol, list]: """Increase number of explicit hydrogens for atom in a bond. Args: rwmol: An RDKit RWmolecule...
5,335,762
def maybe_download(filename, work_directory, source_url): """Download the data from source url, unless it's already here. Args: filename: string, name of the file in the directory. work_directory: string, path to working directory. source_url: url to download from if file doesn't exist. Return...
5,335,763
def step_i_get_the_entity_with_params_in_filename( context, service_name, filename ): """ :type context: behave.runner.Context :type service_name: str :type filename: str """ location = context.json_location data = read_json_from_file(filename, location) keys = data.keys() suffi...
5,335,764
def plot_historical_actuals_forecast(e, title=None, ylabel='', include_pred_int=False, years_prior_include=2, forecast_display_start=None, e2=None): """Produce a plot of...
5,335,765
def f2(a, b): """ concurrent_num = 600 不用怕,因为这是智能线程池,如果函数耗时短,不会真开那么多线程。 这个例子是测试函数耗时是动态变化的,这样就不可能通过提前设置参数预估函数固定耗时和搞鬼了。看看能不能实现qps稳定和线程池自动扩大自动缩小 要说明的是打印的线程数量也包含了框架启动时候几个其他的线程,所以数量不是刚好和所需的线程计算一样的。 ## 可以在运行控制台搜索 新启动线程 这个关键字,看看是不是何时适合扩大线程数量。 ## 可以在运行控制台搜索 停止线程 这个关键字,看看是不是何时适合缩小线程数量。 """ res...
5,335,766
def minimize_loss_single_machine_manual(loss, accuracy, layer_collection, device=None, session_config=None): """Minimize loss with K-FAC on a single machine(I...
5,335,767
def downgrade(): """"Downgrade database schema and/or data back to the previous revision.""" op.drop_column('workflows', 'repeat_multiplier') op.drop_column('workflows', 'unit') op.drop_column('workflows', 'repeat_every')
5,335,768
def bass_call_0(function, *args): """Makes a call to bass and raises an exception if it fails. Does not consider 0 an error.""" res = function(*args) if res == -1: code = BASS_ErrorGetCode() raise BassError(code, get_error_description(code)) return res
5,335,769
def saveFigures(folder, name, summaryDict): """ :param folder: the folder where we want to save it :param name: the name of the figures :param summaryDict: the data of the training we want to plot Save the plot of the evolution of the training loss and the testing loss through the epochs ...
5,335,770
def port_speed(value : str | None = None) -> int | None: """Port speed -> Mb/s parcer""" if value is None: return None elif value == "X": return 0 elif value == "M": return 100 elif value == "G": return 1000 elif value == "Q": return 2500 else: ...
5,335,771
def convert_flag_frame_to_strings(flag_frame, sep=', ', empty='OK'): """ Convert the `flag_frame` output of :py:func:`~convert_mask_into_dataframe` into a pandas.Series of strings which are the active flag names separated by `sep`. Any row where all columns are false will have a value of `empty`. P...
5,335,772
def pp_file_to_dataframe(pp_filename): """ read a pilot point file to a pandas Dataframe Parameters ---------- pp_filename : str pilot point file Returns ------- df : pandas.DataFrame a dataframe with pp_utils.PP_NAMES for columns """ df = pd.read_csv(pp_filename...
5,335,773
def get_ps_lib_dirs(): """ Add directory to list as required """ polysync_install = os.path.join('/', 'usr', 'local', 'polysync') polysync_lib = os.path.join(polysync_install, 'lib') polysync_vendor = os.path.join(polysync_install, 'vendor', 'lib') return [ polysync_lib, pol...
5,335,774
def edit_product(request, product_id): """ Edit a product in the store """ if not request.user.is_superuser: messages.error(request, 'Sorry, only store owners can do that.') return redirect(reverse('home')) product = get_object_or_404(Product, pk=product_id) if request.method == 'POST':...
5,335,775
def _resolve_target(target, target_frame='icrs'): """Return an `astropy.coordinates.SkyCoord` form `target` and its frame.""" if target_frame == 'icrs': return parse_coordinates(target) return SkyCoord(target, frame=target_frame)
5,335,776
def iter_fragments(fragiter, start_frag_id = None, stop_frag_id = None): """Given a fragment iterator and a start and end fragment id, return an iterator which yields only fragments within the range. """ if start_frag_id and stop_frag_id: dpred = lambda f: fragment_id_lt(f.fragment_id, start_fra...
5,335,777
def _remove_candidate(cells, candidate: int, SUDOKU_SIZE: int) -> None: """ Remove the candidate from the cells in place cells: an object supporting __len__ and __getitem__ (np.ndarray or np.flatiter) """ for i in range(len(cells)): if cells[i] == -1: continue # Example...
5,335,778
def evaluate_gpt_with_distgen(settings, archive_path=None, merit_f=None, gpt_input_file=None, distgen_input_file=None, workdir=None, use_tempdir=True, gpt_bin='$GPT_BIN', timeout=2500, auto_phase=Fal...
5,335,779
def bst_right_imbalanced(): """Bst that extends right.""" from bst import BST test_bst = BST((1, 2, 3, 4, 5, 6, 7, 8, 9, 10)) return test_bst
5,335,780
def retry(exception_to_check, tries=4, delay=0.5, backoff=2, logger=None): """Retry calling the decorated function using an exponential backoff. Args: exception_to_check (Exception): the exception to check. may be a tuple of exceptions to check tries (int)...
5,335,781
def create_wham_whamr_csv( datapath, savepath, fs, version="min", savename="whamr_", set_types=["tr", "cv", "tt"], add_reverb=True, ): """ This function creates the csv files to get the speechbrain data loaders for the whamr dataset. Arguments: datapath (str) : path for ...
5,335,782
def test_FUNC_call_WITH_not_existing_endpoint_EXPECT_not_found() -> None: """ Check whether the call failed. :return: No return. """ with pook.use(): pook.get("https://example.com/does-not-exist", status=404) with pytest.raises(InternalError, match="Http call failed with status: 404...
5,335,783
def bio_ner_to_tsv(dataDir, readFile, wrtDir, transParamDict, isTrainFile=False): """ This function transforms the BIO style data and transforms into the tsv format required for NER. Following transformed files are written at wrtDir, - NER transformed tsv file. - NER label map joblib file. Fo...
5,335,784
def read_key_value_pairs_from_file(*path): """ Read key value pairs from a file (each pair on a separate line). Key and value are separated by ' ' as often used by the kernel. @return a generator of tuples """ with open(os.path.join(*path)) as f: for line in f: yield line.spl...
5,335,785
def HESSIAN_DIAG(fn): """Generates a function which computes per-argument partial Hessians.""" def h_fn(*args, **kwargs): args = (args,) if not isinstance(args, (tuple, list)) else tuple(args) ret = [ jaxm.hessian( lambda arg: fn(*args[:i], arg, *args[i + 1 :], **kwa...
5,335,786
def match_xy(x1, y1, x2, y2, neighbors=1): """Match x1 & y1 to x2 & y2, neighbors nearest neighbors. Finds the neighbors nearest neighbors to each point in x2, y2 among all x1, y1.""" from scipy.spatial import cKDTree vec1 = numpy.array([x1, y1]).T vec2 = numpy.array([x2, y2]).T kdt = cKDTr...
5,335,787
def make_doc(): """ Only used for sphinx documentation """ doc_app = Flask(__name__) doc_app.register_blueprint(blueprint()) return doc_app
5,335,788
def test_class_named_argument_default_value(): """Allow classes as default argument values if argument name ends with `_class`.""" class Foo: pass class Bar: def __init__(self, foo_class=Foo): self.foo_class = foo_class class Container(Injector): bar = Bar ass...
5,335,789
def get_participants(reaction): """ get iterator for the reaction participants (reactants + products) @type reaction: libsbml.Reaction @rtype: Iterator """ for s in reaction.getListOfReactants(): yield s for s in reaction.getListOfProducts(): yield s
5,335,790
def logout(request): """Logs out the user""" user_logout(request) return redirect(auth_views.login)
5,335,791
def test_cannot_start_in_midworkflow(sample_data1): """Ensures that intermediate fates do not create labors when no labor exists. Given a Fate C -> D, and intermediate Fate D -> E, Throw event D and ensure Labor D is not created since Labor C does not exist. """ labors = sample_data1.query(La...
5,335,792
def test_invalid_not_square(): """ Tests that an error is raised when constructing an operator with a matrix which is not square. """ with pytest.raises(ValueError): sr.RealSpaceOperator([[0, 1]])
5,335,793
def to_pydot(obj): """Specify either of the following options: a dot string (filename or text), a networkx graph, a pydot graph, an igraph graph, or a callable function. The function will be called with a filename to write it's dot output to.""" if isinstance(obj, pydot.Graph): return obj ...
5,335,794
def workout_train_chunk_length(inp_len: int, resampling_factor: int = 1, num_encoders: int = 5, kernel: int = 8, stride: int = 2) -> int: """ Given inp_len, return the chunk size for train...
5,335,795
def asin(e): """ :rtype: Column """ return col(Asin(parse(e)))
5,335,796
def display_summary(codebase, scan_names, processes, errors, echo_func=echo_stderr): """ Display a scan summary. """ error_messages, summary_messages = get_displayable_summary( codebase, scan_names, processes, errors) for msg in error_messages: echo_func(msg, fg='red') for msg i...
5,335,797
def gs_exists(gs_url): """Check if gs_url points to a valid file we can access""" # If gs_url is not accessible, the response could be one of: # 1. "You aren't authorized to read ..." # 2. "No URLs matched: ..." # and it would have a non-0 status, which would be raised. # # Otherwise, it...
5,335,798
def unblock_expired_blacklistings(): """ Some timestamps are set on blacklisted until their time stamp is hit. This task is for unblocking those at their given date within whatever time interval you choose to perform the task. """ blacklisted_emails = BlacklistEmail.objects.filter( is_bl...
5,335,799