content
stringlengths
22
815k
id
int64
0
4.91M
def get_wikipedia_pages_by_list(titles_or_page_ids): """ Get Wikipedia pages using list of titles or page ids. @param titles_or_page_ids: List of titles or page ids. @return: List of pages. >>> titles_or_page_ids = 'Aromatics_byggnad' >>> pages = get_wikipedia_pages_by_list(titles_or_page_ids...
4,100
def probit(s: pd.Series, error: str = "warn") -> pd.Series: """ Transforms the Series via the inverse CDF of the Normal distribution. Each value in the series should be between 0 and 1. Use `error` to control the behavior if any series entries are outside of (0, 1). >>> import pandas as pd ...
4,101
def make_poem(token_nums, df, new_rowi): """ should return a series to be put at the end of the dataframe Having a list in a df cell is apparently a pain so words are joined with "_" """ print(token_nums) words = df.iloc[token_nums,0].to_list() words_out = [] for word in words: ...
4,102
def merge_multilinestrings(network): """Try to merge all multilinestring geometries into linestring geometries. Args: network (class): A network composed of nodes (points in space) and edges (lines) Returns: network (class): A network composed of nodes (points in space) and edges (lines) ...
4,103
def _read_yaml_definition(uarchdefs, path): """ :param uarchdefs: :param path: """ uarchdef = read_yaml(os.path.join(path, "microarchitecture.yaml"), SCHEMA) uarchdef["Path"] = path uarchdefs.append(uarchdef) _read_uarch_extensions(uarchdefs, path) baseuarch = read_yaml(DEFAULT...
4,104
def timestamp_old (): """ store timestamp field """ timestamp = {} timestamp['timestamp'] = False try: today = datetime.datetime.now() # print('Timestamp: {:%Y-%m-%d %H:%M:%S}'.format(today)) timestamp['timestamp'] = "{:%Y-%m-%d %H:%M:%S}".format(today) except Exception as e: ...
4,105
def download_model(model: str, saving_directory: str = None) -> str: """ Function that loads pretrained models from AWS. :param model: Name of the model to be loaded. :param saving_directory: RELATIVE path to the saving folder (must end with /). Return: - Path to model checkpoint. """ ...
4,106
def get_series(currency_id: str, interval: str) -> pd.DataFrame: """ Get the time series for the given currency_id. Timestamps and dates are given in UTC time. """ url = f"https://api.coincap.io/v2/assets/{currency_id}/history" js = request_and_jsonize_calm(url, params={'interval': interval}) times, p...
4,107
def write_interpolated_6hrly(data,z,file_name=None): """docstring for write_interpolated_6hrly""" outputq_file="interpolated_{}.nc" if file_name!=None: outputq_file="{}_"+file_name for k in data.keys(): if k!="z": mygis.write(outputq_file.format(k),data[k],varname=k)
4,108
def formatTitle(title): """ The formatTitle function formats titles extracted from the scraped HTML code. """ title = html.unescape(title) if(len(title) > 40): return title[:40] + "..." return title
4,109
def isPalindrome(x): """ :type x: int :rtype: bool """ def sub_judge(start, end, string): if start >= end: return True if string[start] == string[end]: return sub_judge(start + 1, end - 1, string) else: return False return sub_judge(0...
4,110
def count_partitions(n, m): """Count the partitions of n using parts up to size m. >>> count_partitions(6, 4) 9 >>> count_partitions(10, 10) 42 """ if n == 0: return 1 elif n < 0: return 0 elif m == 0: return 0 else: with_m = count_partitions(n-m,...
4,111
def parse_pairs(string): """ Converts string where are data wrote using such method: Key: Value To dictionary where "Key" is key and "Value" is value. If there's newline, space and dot or text - that must be added to previous value. :param string: string that contains data to convert :ret...
4,112
def check_yum_package(package_name, logger): """ check if a yum package is installed :param package_name: name to be checked :param logger: rs log obj :return: boolean """ logger.trace("Checking if package '{}' is installed.", package_name) command = "yum list installed {}".format(package_name) try: execute_...
4,113
def get(filename, name): """ Read a given element from an SVG file """ root = etree.parse(filename).getroot() return root.xpath("//*[@id='%s']" % name)[0].get("d")
4,114
def softmaxCostAndGradient(predicted, target, outputVectors, dataset): """ Softmax cost function for word2vec models Implement the cost and gradients for one predicted word vector and one target word vector as a building block for word2vec models, assuming the softmax prediction function and cross ...
4,115
def get_osf_meta_schemas(): """Returns the current contents of all known schema files.""" schemas = [ ensure_schema_structure(from_json(json_filename)) for json_filename in OSF_META_SCHEMA_FILES ] return schemas
4,116
def test_stop_after_success(): """ after resolving a cep the next provider groups should not be used """ working_provider, mock_cepaddress = create_mock_provider() next_provider, _ = create_mock_provider() cep_resolver = CEPResolver(providers=[{working_provider}, {next_provider}]) assert c...
4,117
def setup_platform( hass: HomeAssistant, config: ConfigType, add_entities: AddEntitiesCallback, discovery_info: DiscoveryInfoType | None = None, ) -> None: """Set up the configured Numato USB GPIO switch ports.""" if discovery_info is None: return api = hass.data[DOMAIN][DATA_API] ...
4,118
def update(request, bleep_id): """ Process a bleep form update """ if request.method == 'POST': form = BleepForm(request.POST) if form.is_valid(): # Process and clean the data # ... # update the form with current bleep data b = Bleep.objec...
4,119
def split_passports(file: Path) -> Iterator[Mapping]: """ Split a given passport file :param file: passport file to process :return: generator yielding a list of fields """ passport = {} for line in open(file): if line == '\n': yield passport passport = {} ...
4,120
def decode_header(header): """Decode a message header value without converting charset. Returns a list of (decoded_string, charset) pairs containing each of the decoded parts of the header. Charset is None for non-encoded parts of the header, otherwise a lower-case string containing the name of th...
4,121
def user_from_identity(): """Returns the User model object of the current jwt identity""" username = get_jwt_identity() return User.query.filter(User.username == username).scalar()
4,122
def test_write_output_file(): """ Test writing an output file """ npdf = 40 nbins = 21 pz_pdf = np.random.uniform(size=(npdf, nbins)) zgrid = np.linspace(0, 4, nbins) zmode = zgrid[np.argmax(pz_pdf, axis=1)] data_dict = dict(zmode=zmode, pz_pdf=pz_pdf) group, outf = io.initializeHdf5Wr...
4,123
async def test_check_segment_or_target( data_type, defined, missing, used, sequence_id, dbi ): """ Test that issues with `segment` or `target` fields in sequence editing requests are detected. """ await dbi.otus.insert_one({"_id": "foo", "schema": [{"name": "RNA1"}]}) await dbi.references....
4,124
def pdf2img(file_path): """ Transforming the pdf files to images. :param file_path: the path saving the raw material :return: """ formats = ['.pdf', '.PDF'] ## do not consider the situation like '.pDF', '.Pdf', etc. formats_recognize = ['.pdf', '.PDF', '.jpg', '.png'] if not os....
4,125
def combine(first: Set[T], second: Set[T]) -> Set[T]: """Combine two sets of tuples, prioritising the second.""" result = second.copy() for pf in first: include = True for pr in result: if pf[0] == pr[0]: include = False break if pf[1] ...
4,126
def minsize<VAL1>(event, context): """ AutoScalingGroup起動台数調整 """ """ Create Connection """ try: client = boto3.client('autoscaling', region_name = '<Region>') except: print('Connection Error') return 1 """ Update AutoScalingGroup """ try: client.update_...
4,127
def thin(image, n_iter=None): """ Perform morphological thinning of a binary image Parameters ---------- image : binary (M, N) ndarray The image to be thinned. n_iter : int, number of iterations, optional Regardless of the value of this parameter, the thinned image is r...
4,128
def test_return_quotes(): """test return an obj with more than one quote""" obj = quotes.get_quotes() assert len(obj) > 0
4,129
def rings(xgr): """ rings in the graph (minimal basis) """ xgrs = [bond_induced_subgraph(xgr, bnd_keys) for bnd_keys in rings_bond_keys(xgr)] return tuple(sorted(xgrs, key=frozen))
4,130
def test_pion_decay_kelner(particle_dists): """ test PionDecayKelner06 """ from ..radiative import PionDecayKelner06 as PionDecay ECPL,PL,BPL = particle_dists for pdist in [ECPL,PL,BPL]: pdist.amplitude = 1*(1/u.TeV) lum_ref = [5.54225481494e-13, 1.21723084093e-12, ...
4,131
def prior_search(binary, left_fit, right_fit, margin=50): """ searches within the margin of previous left and right fit indices Parameters: binary: np.ndarray, binary image from the video left_fit: list, left line curve fitting coefficients right_fit: list, right line curve fitting c...
4,132
def _parallel_iter(par, iterator): """ Parallelize a partial function and return results in a list. :param par: Partial function. :param iterator: Iterable object. :rtype: list :return: List of results. """ pool = mp.Pool(processes=mp.cpu_count(), maxtasksperchild=1) output = [] ...
4,133
def test_cpp_info_merge_with_components(): """If we try to merge a cpp info with another one and some of them have components, assert""" cppinfo = NewCppInfo() cppinfo.components["foo"].cxxflags = ["var"] other = NewCppInfo() other.components["foo2"].cxxflags = ["var2"] with pytest.raises(Cona...
4,134
def reassign_labels(class_img, cluster_centers, k=3): """Reassigns mask labels of t series based on magnitude of the cluster centers. This assumes land will always be less than thin cloud which will always be less than thick cloud, in HOT units""" idx = np.argsort(cluster_centers.sum(axis=1)) ...
4,135
def parse_args(): """parse args with argparse :returns: args """ parser = argparse.ArgumentParser(description="Daily Reddit Wallpaper") parser.add_argument("-s", "--subreddit", type=str, default=config["subreddit"], help="Example: art, getmotivated, wallpapers, ...") pars...
4,136
def gridarray(a, b): """ Given two arrays create an array of all possible pairs, a 2d grid. E.g. a = [1, 2], b = [2, 4, 5], gridarray(a,b) = [[1,2], [1,4], [1,5], [2,2], [2,4], [2,5]]. May be used repeatedly for increasing dimensionality. DEPRECIATED: Use A, B = np.meshgrid(a, b). ...
4,137
def spooler_get_task(path: str) -> Optional[dict]: """Returns a spooler task information. :param path: The relative or absolute path to the task to read. """
4,138
def has_alphanum(s): """ Return True if s has at least one alphanumeric character in any language. See https://en.wikipedia.org/wiki/Unicode_character_property#General_Category """ for c in s: category = unicodedata.category(c)[0] if category == 'L' or category == 'N': ...
4,139
def src_path_join(*kwargs): """ reutrns path to the file whose dir information are provided in kwargs similar to `os.path.join` :param kwargs: :return: """ return os.path.join(get_src_dir(), *kwargs)
4,140
def get_values_heatmap(entity, measurement, case_id, categorical_filter, categorical, numerical_filter_name, from1, to1, measurement_filter, date, r): """ Get numerical values from numerical table from database get_values use in heatmap, clustering r: connection with database ...
4,141
async def unwrap_pull_requests(prs_df: pd.DataFrame, precomputed_done_facts: PullRequestFactsMap, precomputed_ambiguous_done_facts: Dict[str, List[int]], with_jira: bool, branches: pd.DataFrame, ...
4,142
def load_images(image_files, resize=True): """Load images from files and optionally resize it.""" images = [] for image_file in image_files: with file_io.FileIO(image_file, 'r') as ff: images.append(ff.read()) if resize is False: return images # To resize, run a tf session so we can reuse 'dec...
4,143
def schemaGraph (ds, ns, ontology_uri=None): """ schemaGraph (datasource, namespace, [ontology_uri,]) Return an RDF graph filled with axioms describing the datasource. @param ds: the DataSource whose schema has to be converted @param ns: the namespace uri of the created cla...
4,144
def delete_log_dir(): """Delete current test logs""" delete_path(LOG_DIR)
4,145
def ugerest(): """ Test InfluxDB Connectivity and Accessibility """ print("Test UGE RestAPI Availability... ", end='', flush=True) ip_list = config.getUGE_Addr() port_list = config.getUGE_Port() try: for inx, ip in enumerate(ip_list): ugerest_url = "http://" + ip + "...
4,146
def write_results(char_vars_output, guppy, output): """ :param guppy: :param char_vars_output: Output of char_vars() i.e a dict where nt are keys & counter obj are values for each nt :param output: name of csv file to be produced :return: """ with open(output, 'w') as out: writer =...
4,147
def test_show(capsys): """Do we get the expected code for some snippet module? """ show(sieve_eratosthenes) captured = capsys.readouterr() assert captured.out.startswith("def sieve_of_eratosthenes(n):")
4,148
def is_remote(path): """Determine whether a file is in a remote location (which can be handled) based on prefix of connection string.""" for token in ["s3://", "http://", "https://"]: # add if path.startswith(token): return True return False
4,149
def saliency_map(output, input, name="saliency_map"): """ Produce a saliency map as described in the paper: `Deep Inside Convolutional Networks: Visualising Image Classification Models and Saliency Maps <https://arxiv.org/abs/1312.6034>`_. The saliency map is the gradient of the max element in outpu...
4,150
def pretty_tree(*, program: str = None, file: str = None) -> str: """Get a pretty-printed string of the parsed AST of the QASM input. The input will be taken either verbatim from the string ``program``, or read from the file with name ``file``. Use exactly one of the possible input arguments, passed b...
4,151
def get_models(datasets): """It obtains the models used into the experiments""" dataframe = pd.read_csv('../results/' + datasets[0] + '/results.csv', sep=';') models = dataframe['MODEL'].unique() return models.tolist()
4,152
def classify(infile, out, modeldir, n_classes, configpath): """Classify fasta sequences or TRrecords data to identify viral sequences Classify fasta files or TFrecords containing contigs to identify viral contigs. The classifier takes contigs and extracts features then makes predictions. It returns a t...
4,153
def Prepare(benchmark_spec): """Install Java, apache ant, authenticate vms Set up the client machine, backend machine, and frontend Args: benchmark_spec: The benchmark specification. Contains all data that is required to run the benchmark. """ frontend = benchmark_spec.vm_groups['frontend'][0]...
4,154
def _gr_xmin_ ( graph ) : """Get x-min for the graph >>> xmin = graph.xmin() """ # _size = len ( graph ) if 0 == _sise : return 0 # x_ = ROOT.Double(0) v_ = ROOT.Double(0) graph.GetPoint ( 0 , x_ , v_ ) # return x_
4,155
def test_http_request_invalid_schema_error(mocker_api_token, mock_base_http_request, demisto_version, client): """ When http request return invalid schema exception then appropriate error message should match. """ # Configure mock_base_http_request.side_effect = InvalidSchema mocker_api_toke...
4,156
def test_add_incoming_connection(): """ Tests the add_incoming_connection function :return: Test passes if all assertions are true. Tests do not pass if otherwise. """ center = Coordinates(4, 4) radius = 10 i = Intersection(center, radius, 15) empty_connections = i.get_connections() ...
4,157
def eliminate(values): """ Go through all the boxes, and whenever there is a box with a value, eliminate this value from the values of all its peers. Input: A sudoku in dictionary form. Output: The resulting sudoku in dictionary form. """ solved_values = [box for box in values.keys() if len(valu...
4,158
def route_distance(route): """ returns the distance traveled for a given tour route - sequence of nodes traveled, does not include start node at the end of the route """ dist = 0 prev = route[-1] for node in route: dist += node.euclidean_dist(prev) prev = node return dist
4,159
def adjust_matrix(matrix): """ Sorting matrix cols. matrix: can be a numpy 2d-array or pytorch 2d-Tensor Return ------ adjusted pytorch 2d-tensor """ if isinstance(matrix, np.ndarray): tmp = torch.from_numpy(matrix).clone() # ? else: tmp = matrix.clone() tmp /=...
4,160
def get_student_graph(pool, student, student_friends, friends_students, need_spinglass=False): """ Получение социального графа пользователя. :param pool: пул процессов (библиотека multiprocessing) :param student: идентификатор пользователя :param student_friends: список друзей пользователя :par...
4,161
def wdirectory(path): """ Change the work directory for a specific path of the data ___ path: string, data path in the system """ return os.chdir(path)
4,162
def ile_robil_czy_mial_dobe(dzien, zp, grafik): """Czy miał dobę danego dnia?""" godzin = 0 for wpis in Wpis.objects.filter(user=zp.user, grafik=grafik, dzien=dzien): godzin += wpis.pion.ile_godzin(dzien) return (godzin, godzin == 24)
4,163
def load_teacher(): """ load ready-to-go teacher from "https://towardsdatascience.com/advanced-dqns-playing-pac-man-with-deep-reinforcement-learning-3ffbd99e0814" :return: a trained teacher model trained with double dueling dqn with prioritized ER """ dqn = DQNPacman(input_size=dense_config.input_si...
4,164
async def test_service_call( hass, habitica_entry, common_requests, capture_api_call_success ): """Test integration setup, service call and unload.""" assert await hass.config_entries.async_setup(habitica_entry.entry_id) await hass.async_block_till_done() assert hass.services.has_service(DOMAIN, S...
4,165
def exception_logged(result_output: str, exc: Exception) -> bool: """Small utility to search click result output for a specific excpetion . Args: result_output: The click result output string to search. exc: The exception to search for. Returns: bool: Whether or not the exception wa...
4,166
def hello(world): """Hello, You!""" return "Hello, {}!".format(world)
4,167
def set_window_user_pointer(window, pointer): """ Sets the user pointer of the specified window. You may pass a normal python object into this function and it will be wrapped automatically. The object will be kept in existence until the pointer is set to something else or until the window is destroy...
4,168
def uniform_transition_matrix(p=0.01, N=24): """Computes uniform transition matrix Notebook: C5/C5S3_ChordRec_HMM.ipynb Args: p (float): Self transition probability (Default value = 0.01) N (int): Column and row dimension (Default value = 24) Returns: A (np.ndarray): Output tr...
4,169
def __is_connected__(g): """ Checks if a the directed acyclic graph is connected. :return: A boolean indicating if the graph is connected. """ u = __convert_to_undirected_graph__(g) return nx.is_connected(u)
4,170
def get_segments(tokens, max_seq_length): """Segments: 0 for the first sequence, 1 for the second""" if len(tokens)>max_seq_length: raise IndexError("Token length more than max seq length!") segments = [] current_segment_id = 0 for token in tokens: segments.append(current_segment_id)...
4,171
def GRUCell(input, hidden, w_ih, w_hh, b_ih=None, b_hh=None, linear_func=None): """ Copied from torch.nn._functions.rnn and modified """ if linear_func is None: linear_func = F.linear if input.is_cuda and linear_func is F.linear and fusedBackend is not None: gi = linear_func(input, w_ih) ...
4,172
def flush_socket(socks, lim=0): """remove the data present on the socket""" input_socks = [socks] cnt = 0 while True: i_socks = select.select(input_socks, input_socks, input_socks, 0.0)[0] if len(i_socks) == 0: break for sock in i_socks: sock.recv...
4,173
def ensure_fov(env): """ Ensures that the field of view is consistent with robot's orientation """ yaw_radian = convert_angle(quaternion_to_euler(env.robot.get_orientation())) yaw_degree = degrees(yaw_radian) print('yaw: ', yaw_degree) p.resetDebugVisualizerCamera(cameraDistance=cdist, camer...
4,174
def test_requisites_require_no_state_module(state, state_tree): """ Call sls file containing several require_in and require. Ensure that some of them are failing and that the order is right. """ sls_contents = """ # Complex require/require_in graph # # Relative order of C>E is given by ...
4,175
def _toggle_debug_mode() -> bool: """Set debug to true or false. Can be used for debugging purposes such that exceptions are raised (including the stack trace) instead of suppressed. Note: the debug status is always printed when executing this method. Returns: Boolean indicating the statu...
4,176
def GetAppBasename(): """Returns the friendly basename of this application.""" return os.path.basename(sys.argv[0])
4,177
def fetch_and_publish_results(run_once=False): """ Harvest data and deploy cards """ require('settings', provided_by=['production', 'staging']) try: with settings(warn_only=True): main(run_once) except KeyboardInterrupt: sys.exit(0)
4,178
def test_get_signal_external_language_poisonous(): """ Test that getting the signal for a population with external language gives a specific signal for edible mushrooms """ sim = Simulation(4, 5, 6, 7, "External") angle = 0 mush = 0b1111100000 population = [] viewer = False sign...
4,179
def connect(dbtype: str, **kwargs) -> subprocess.Popen: """ Creates a connection to the database server """ # create subprocess process = subprocess.Popen('/bin/bash', shell=True, stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.PIPE, bufsize=10) # connect process to database server ...
4,180
def min_requirements(args=None): """ Prints a pip install command to install the minimal supported versions of a requirement file. Uses requirements_production.txt by default. """ import pip def get_lowest_versions(requirements_file): for line in pip.req.parse_requirements(require...
4,181
def client(mock_settings) -> StructurizrClient: """Provide a client instance with the mock settings.""" return StructurizrClient(settings=mock_settings)
4,182
def mean_iou(y_true, y_pred, **kwargs): """ Compute mean Intersection over Union of two segmentation masks, via Keras. Calls metrics_k(y_true, y_pred, metric_name='iou'), see there for allowed kwargs. """ return seg_metrics(y_true, y_pred, metric_name='iou', drop_last = False, **kwargs)
4,183
def reset_config(): """create a new config.ini file in the user home dir/.pyhdx folder""" with open(config_file_path, 'w') as target: version_string = '; pyhdx configuration file ' + __version__ + '\n\n' target.write(version_string) with open(current_dir / 'config.ini') as source: ...
4,184
async def bluetext(bt_e): """Believe me, you will find this useful.""" if bt_e.is_group: await bt_e.edit( "/CORES_PRECISO_CLICAR\n" "/VOCE_E_UM_ANIMAL_ESTUPIDO_QUE_E_ATRAIDO_A_CORES\n" "/CLIQUE_AQUI" )
4,185
def _write_blast_summary(seqs, path_sum): """Write a summary blast results """ # Summarize results with open(path_sum, 'w') as f_o: header = ['Contig ID', 'Sample ID', 'Contig Length', 'Aligned Length', 'Aligned coverage of ...
4,186
def pages_to_csv(filename, pages, path=""): """Writes a csv file with information about the webpages. Raises PermissionError if the file is already open. """ filename = add_extension(filename, ".csv") if not path: filename = os.path.join(os.pardir, filename) else: filename = path...
4,187
def get_python_function(target_kwargs_function,func_name,func_spec): """Convert a argparse spec into a python function This function provides a python function with a signature indicated by the ``fun_spec`` dictionary With the conventions of the :f:mod:`yaml_argparse` modules. The :py:func:`futile.Util...
4,188
def ydbdr2rgb(ydbdr, *, channel_axis=-1): """YDbDr to RGB color space conversion. Parameters ---------- ydbdr : (..., 3, ...) array_like The image in YDbDr format. By default, the final dimension denotes channels. channel_axis : int, optional This parameter indicates which a...
4,189
def _migrate_activity_log(logs, **kwargs): """For migrate_activity_log.py script.""" for log in logs: action = _action_map(log.action) # Create thread. thread, tc = CommunicationThread.objects.safer_get_or_create( addon=log.arguments[0], version=log.arguments[1]) # ...
4,190
def execute( connection_info: NodeConnectionInfo, block_id: typing.Union[None, bytes, str, int] = None ) -> dict: """Returns current auction system contract information. :param connection_info: Information required to connect to a node. :param block_id: Identifier of a finalised block. :ret...
4,191
def main(): """Parse command-line args, pass into process""" cmd_parser = create_cmd_parser() kwargs = vars(cmd_parser.parse_args()) process(**kwargs)
4,192
def subscriber(pipeline): """Joystick subscriber thread """ cmd = {} while True: # clear command cmd.clear() # collect gamepad events (blocking) events = inputs.get_gamepad() # parse all events for event in events: if event.ev_type ...
4,193
def direction_to_point(pos1: IntVector2D, pos2: IntVector2D) -> Grid4TransitionsEnum: """ Returns the closest direction orientation of position 2 relative to position 1 :param pos1: position we are interested in :param pos2: position we want to know it is facing :return: direction NESW as int N:0 E:...
4,194
def test_prime_data_ranking() -> None: """Test prime data ranking.""" pass
4,195
def handle_nullboolean(field, request_get): """Build a list of chips for NullBooleanField field.""" value = yesno( field.value(), pgettext_lazy('Possible values of boolean filter', 'yes,no,all')) return [{ 'content': CHIPS_PATTERN % (field.label, value), 'link': get_cancel_ur...
4,196
def rob(nums): """ :type nums: List[int] :rtype: int """ if nums == [] or len(nums) == 0: return 0 elif len(nums) == 1: return nums[0] runningTotal = [-1, -1] runningTotal[0] = nums[0] runningTotal[1] = max(nums[0], nums[1]) for i in range(2, len(nums)): ...
4,197
def test_rest_plugins(mock_post, mock_get): """ API: REST Based Plugins() """ # Disable Throttling to speed testing plugins.NotifyBase.request_rate_per_sec = 0 # Define how many characters exist per line row = 80 # Some variables we use to control the data we work with body_len = ...
4,198
def _transform_collaborators(collaborators: Dict, repo_url: str, transformed_collaborators: Dict) -> None: """ Performs data adjustments for outside collaborators in a GitHub repo. Output data shape = [{permission, repo_url, url (the user's URL), login, name}, ...] :param collaborators: See cartography....
4,199