content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
def GetMappingKeyName(run, user): """Returns a str used to uniquely identify a mapping.""" return 'RunTesterMap_%s_%s' % (run.key().name(), str(user.user_id()))
b4eb80ca5f084ea956f6a458f92de1b85e722cda
2,811
def year_from_operating_datetime(df): """Add a 'year' column based on the year in the operating_datetime. Args: df (pandas.DataFrame): A DataFrame containing EPA CEMS data. Returns: pandas.DataFrame: A DataFrame containing EPA CEMS data with a 'year' column. """ df['year'] = df.operating_datetime_utc.dt.year return df
1c7bbc6465d174465151e5e777671f319ee656b7
2,812
def get_seats_percent(election_data): """ This function takes a lists of lists as and argument, with each list representing a party's election results, and returns a tuple with the percentage of Bundestag seats won by various political affiliations. Parameters: election_data (list): A list of lists, each representing a party's election results Returns: A tuple with percentage of Bundestag seats won by various political affiliations """ left_seats = 0 right_seats = 0 extreme_seats = 0 center_seats = 0 total_bundestag_seats = 0 for party in election_data[1:]: total_bundestag_seats += int(party[1]) if 'far' in party[2]: extreme_seats += party[1] else: center_seats += party[1] if 'left' in party[2]: left_seats += party[1] else: right_seats += party[1] left_percent = round((left_seats / total_bundestag_seats * 100), 2) right_percent = round((right_seats / total_bundestag_seats * 100), 2) extreme_percent = round((extreme_seats / total_bundestag_seats * 100), 2) center_percent = round((center_seats / total_bundestag_seats * 100), 2) return left_percent, right_percent, extreme_percent, center_percent
a131d64747c5c0dde8511e9ec4da07252f96a6ec
2,815
import random def random_choice(gene): """ Randomly select a object, such as strings, from a list. Gene must have defined `choices` list. Args: gene (Gene): A gene with a set `choices` list. Returns: object: Selected choice. """ if not 'choices' in gene.__dict__: raise KeyError("'choices' not defined in this gene, please include a list values!") return random.choice(gene.choices)
8a01a2039a04262aa4fc076bdd87dbf760f45253
2,817
from random import shuffle def shuffle_list(*ls): """ shuffle multiple list at the same time :param ls: :return: """ l = list(zip(*ls)) shuffle(l) return zip(*l)
ec46e4a8da2c04cf62da2866d2d685fc796887e5
2,820
def nodes(G): """Returns an iterator over the graph nodes.""" return G.nodes()
3a1a543f1af4d43c79fd0083eb77fedd696547ec
2,821
def process_input(input_string, max_depth): """ Clean up the input, convert it to an array and compute the longest array, per feature type. """ # remove the quotes and extra spaces from the input string input_string = input_string.replace('"', '').replace(', ', ',').strip() # convert the string to an array and also track the longest array, so # we know how many levels for the feature type. tmp = [] if input_string: tmp = input_string.split(',') if max_depth < len(tmp): max_depth = len(tmp) # return the array and the depth return tmp, max_depth
ca0fddd0b3bf145c7fc0654212ae43f02799b466
2,822
def construct_tablepath(fmdict, prefix=''): """ Construct a suitable pathname for a CASA table made from fmdict, starting with prefix. prefix can contain a /. If prefix is not given, it will be set to "ephem_JPL-Horizons_%s" % fmdict['NAME'] """ if not prefix: prefix = "ephem_JPL-Horizons_%s" % fmdict['NAME'] return prefix + "_%.0f-%.0f%s%s.tab" % (fmdict['earliest']['m0']['value'], fmdict['latest']['m0']['value'], fmdict['latest']['m0']['unit'], fmdict['latest']['refer'])
95041aab91ac9994ef2068d5e05f6cd63969d94e
2,823
def recursiveUpdate(target, source): """ Recursively update the target dictionary with the source dictionary, leaving unfound keys in place. This is different than dict.update, which removes target keys not in the source :param dict target: The dictionary to be updated :param dict source: The dictionary to be integrated :return: target dict is returned as a convenience. This function updates the target dict in place. :rtype: dict """ for k, v in source.items(): if isinstance(v, dict): target[k] = recursiveUpdate(target.get(k, {}), v) else: target[k] = v return target
e1c11d0801be9526e8e73145b1dfc7be204fc7d0
2,825
def get_module_id_from_event(event): """ Helper function to get the module_id from an EventHub message """ if "iothub-connection-module_id" in event.message.annotations: return event.message.annotations["iothub-connection-module-id".encode()].decode() else: return None
e183824fff183e3f95ef35c623b13245eb68a8b7
2,828
from typing import Collection def A006577(start: int = 0, limit: int = 20) -> Collection[int]: """Number of halving and tripling steps to reach 1 in '3x+1' problem, or -1 if 1 is never reached. """ def steps(n: int) -> int: if n == 1: return 0 x = 0 while True: if n % 2 == 0: n //= 2 else: n = 3 * n + 1 x += 1 if n < 2: break return x return [steps(n) for n in range(start, start + limit)]
47829838af8e2fdb191fdefa755e728db9c09559
2,831
def parabolic(f, x): """ Quadratic interpolation in order to estimate the location of a maximum https://gist.github.com/endolith/255291 Args: f (ndarray): a vector a samples x (int): an index on the vector Returns: (vx, vy): the vertex coordinates of a parabola passing through x and its neighbors """ xv = 1/2. * (f[x-1] - f[x+1]) / (f[x-1] - 2 * f[x] + f[x+1]) + x yv = f[x] - 1/4. * (f[x-1] - f[x+1]) * (xv - x) return (xv, yv)
4373ee6390f3523d0fd69487c27e05522bd8c230
2,839
import re def get_better_loci(filename, cutoff): """ Returns a subset of loci such that each locus includes at least "cutoff" different species. :param filename: :param cutoff: :return: """ f = open(filename) content = f.read() f.close() loci = re.split(r'//.*|', content) better_loci = [] for locus in loci: found_species = set() for line in locus.strip().split("\n"): if line == "": continue (individual, sequence) = line[1:].split() found_species.add(individual.split("_")[-1]) if len(found_species) >= cutoff: better_loci.append(locus) return better_loci
e2d563c9d0568cef59ea0280aae61a78bf4a6e7b
2,840
import six def canonicalize_monotonicity(monotonicity, allow_decreasing=True): """Converts string constants representing monotonicity into integers. Args: monotonicity: The monotonicities hyperparameter of a `tfl.layers` Layer (e.g. `tfl.layers.PWLCalibration`). allow_decreasing: If decreasing monotonicity is considered a valid monotonicity. Returns: monotonicity represented as -1, 0, 1, or None. Raises: ValueError: If monotonicity is not in the set {-1, 0, 1, 'decreasing', 'none', 'increasing'} and allow_decreasing is True. ValueError: If monotonicity is not in the set {0, 1, 'none', 'increasing'} and allow_decreasing is False. """ if monotonicity is None: return None if monotonicity in [-1, 0, 1]: if not allow_decreasing and monotonicity == -1: raise ValueError( "'monotonicities' must be from: [0, 1, 'none', 'increasing']. " "Given: {}".format(monotonicity)) return monotonicity elif isinstance(monotonicity, six.string_types): if monotonicity.lower() == "decreasing": if not allow_decreasing: raise ValueError( "'monotonicities' must be from: [0, 1, 'none', 'increasing']. " "Given: {}".format(monotonicity)) return -1 if monotonicity.lower() == "none": return 0 if monotonicity.lower() == "increasing": return 1 raise ValueError("'monotonicities' must be from: [-1, 0, 1, 'decreasing', " "'none', 'increasing']. Given: {}".format(monotonicity))
a9d0870d03f11d7bdff4c8f673cd78d072fa8478
2,843
def add_gdp(df, gdp, input_type="raw", drop=True): """Adds the `GDP` to the dataset. Assuming that both passed dataframes have a column named `country`. Parameters ---------- df : pd.DataFrame Training of test dataframe including the `country` column. gdp : pd.DataFrame Mapping between `country` and `GDP` input_type : {"raw", "aggregated"} Whether the operation should run on the raw, or the aggregated dataset. drop : bool Whether the old country columns should be droped. Returns ------- pd.DataFrame The passed `df` with a new column corresponding to the mapped GDP. """ def stringify(maybe_string): # Handles Unicode country names like "Côte d’Ivoire" , "Réunion" etc, as well as countries only existing # in one of the two dataframes. try: return str(maybe_string) except UnicodeEncodeError: return "Unknown" if input_type == "aggregated": country_cols = [col for col in df.columns if col.startswith("country") and col != "country"] def inverse_ohe(row): for c in country_cols: if row[c] == 1: return c.split("_")[1] df["country"] = df.apply(inverse_ohe, axis=1) if drop: df = df.drop(country_cols, axis=1) elif input_type != "raw": msg = "Only {} and {} are supported. \n" + \ "\tThe former assumes the original form where only the JSON has been flattened.\n" + \ "\tThe latter assumes that OHE has already occured on top." raise ValueError(msg) df["country"] = df["country"].fillna("Unknown").apply(stringify) result = df.merge(gdp, on="country", how='left') if drop: result.drop("country", axis=1, inplace=True) return result
72e2b5fe839f3dbc71ca2def4be442535a0adb84
2,844
def ravel_group_params(parameters_group): """Take a dict(group -> {k->p}) and return a dict('group:k'-> p) """ return {f'{group_name}:{k}': p for group_name, group_params in parameters_group.items() for k, p in group_params.items()}
4a768e89cd70b39bea4f658600690dcb3992a710
2,847
def _parse_path(**kw): """ Parse leaflet `Path` options. http://leafletjs.com/reference-1.2.0.html#path """ color = kw.pop('color', '#3388ff') return { 'stroke': kw.pop('stroke', True), 'color': color, 'weight': kw.pop('weight', 3), 'opacity': kw.pop('opacity', 1.0), 'lineCap': kw.pop('line_cap', 'round'), 'lineJoin': kw.pop('line_join', 'round'), 'dashArray': kw.pop('dash_array', None), 'dashOffset': kw.pop('dash_offset', None), 'fill': kw.pop('fill', False), 'fillColor': kw.pop('fill_color', color), 'fillOpacity': kw.pop('fill_opacity', 0.2), 'fillRule': kw.pop('fill_rule', 'evenodd'), 'bubblingMouseEvents': kw.pop('bubbling_mouse_events', True), }
02d3810ad69a1a0b8f16d61e661e246aea5c09cc
2,851
from typing import Optional import time from datetime import datetime def time_struct_2_datetime( time_struct: Optional[time.struct_time], ) -> Optional[datetime]: """Convert struct_time to datetime. Args: time_struct (Optional[time.struct_time]): A time struct to convert. Returns: Optional[datetime]: A converted value. """ return ( datetime.fromtimestamp(time.mktime(time_struct)) if time_struct is not None else None )
705b09428d218e8a47961e247b62b9dfd631a41f
2,853
import time def wait_for_compute_jobs(nevermined, account, jobs): """Monitor and wait for compute jobs to finish. Args: nevermined (:py:class:`nevermined_sdk_py.Nevermined`): A nevermined instance. account (:py:class:`contracts_lib_py.account.Account`): Account that published the compute jobs. jobs (:obj:`list` of :obj:`tuple`): A list of tuples with each tuple containing (service_agreement_id, compute_job_id). Returns: :obj:`list` of :obj:`str`: Returns a list of dids produced by the jobs Raises: ValueError: If any of the jobs fail """ failed = False dids = set() while True: finished = 0 for i, (sa_id, job_id) in enumerate(jobs): status = nevermined.assets.compute_status(sa_id, job_id, account) print(f"{job_id}: {status['status']}") if status["status"] == "Failed": failed = True if status["status"] == "Succeeded": finished += 1 dids.add(status["did"]) if failed: for i, (sa_id, job_id) in enumerate(jobs): logs = nevermined.assets.compute_logs(sa_id, job_id, account) for line in logs: print(f"[{line['podName']}]: {line['content']}") raise ValueError("Some jobs failed") if finished == len(jobs): break # move up 4 lines print("\u001B[4A") time.sleep(5) return list(dids)
98370b8d596f304630199578a360a639507ae3c3
2,855
def find_balanced(text, start=0, start_sep='(', end_sep=')'): """ Finds balanced ``start_sep`` with ``end_sep`` assuming that ``start`` is pointing to ``start_sep`` in ``text``. """ if start >= len(text) or start_sep != text[start]: return start balanced = 1 pos = start + 1 while pos < len(text): token = text[pos] pos += 1 if token == end_sep: if balanced == 1: return pos balanced -= 1 elif token == start_sep: balanced += 1 return start
15c17a216405028b480efa9d12846905a1eb56d4
2,858
def gather_along_dim_with_dim_single(x, target_dim, source_dim, indices): """ This function indexes out a target dimension of a tensor in a structured way, by allowing a different value to be selected for each member of a flat index tensor (@indices) corresponding to a source dimension. This can be interpreted as moving along the source dimension, using the corresponding index value in @indices to select values for all other dimensions outside of the source and target dimensions. A common use case is to gather values in target dimension 1 for each batch member (target dimension 0). Args: x (torch.Tensor): tensor to gather values for target_dim (int): dimension to gather values along source_dim (int): dimension to hold constant and use for gathering values from the other dimensions indices (torch.Tensor): flat index tensor with same shape as tensor @x along @source_dim Returns: y (torch.Tensor): gathered tensor, with dimension @target_dim indexed out """ assert len(indices.shape) == 1 assert x.shape[source_dim] == indices.shape[0] # unsqueeze in all dimensions except the source dimension new_shape = [1] * x.ndimension() new_shape[source_dim] = -1 indices = indices.reshape(*new_shape) # repeat in all dimensions - but preserve shape of source dimension, # and make sure target_dimension has singleton dimension expand_shape = list(x.shape) expand_shape[source_dim] = -1 expand_shape[target_dim] = 1 indices = indices.expand(*expand_shape) out = x.gather(dim=target_dim, index=indices) return out.squeeze(target_dim)
06fbba5478ddb21cda9a555c41c94c809244537c
2,861
def extract_p(path, dict_obj, default): """ try to extract dict value in key path, if key error provide default :param path: the nested dict key path, separated by '.' (therefore no dots in key names allowed) :param dict_obj: the dictinary object from which to extract :param default: a default return value if key error :return: extracted value """ if dict_obj is None: return default keys = path.split('.') tmp_iter = dict_obj for key in keys: try: # dict.get() might make KeyError exception unnecessary tmp_iter = tmp_iter.get(key, default) except KeyError: return default return tmp_iter
1a563212e229e67751584885c5db5ac19157c37f
2,863
def group_bars(note_list): """ Returns a list of bars, where each bar is a list of notes. The start and end times of each note are rescaled to units of bars, and expressed relative to the beginning of the current bar. Parameters ---------- note_list : list of tuples List of notes to group into bars. """ bar_list = [] current_bar = [] current_bar_start_time = 0 for raw_note in note_list: if raw_note[0] != -1: current_bar.append(raw_note) elif raw_note[0] == -1: quarter_notes_per_bar = raw_note[2] - current_bar_start_time current_bar_scaled = [] for note in current_bar: current_bar_scaled.append((note[0], note[1], min([(note[2] - current_bar_start_time) / quarter_notes_per_bar, 1]), min([(note[3] - current_bar_start_time) / quarter_notes_per_bar, 1]))) bar_list.append(current_bar_scaled) current_bar = [] current_bar_start_time = raw_note[2] return bar_list
3b12a7c7e2395caa3648abf152915ece4b325599
2,865
import re def sample(s, n): """Show a sample of string s centered at position n""" start = max(n - 8, 0) finish = min(n + 24, len(s)) return re.escape(s[start:finish])
565f69224269ed7f5faa538d40ce277714144577
2,868
import math def encode_integer_compact(value: int) -> bytes: """Encode an integer with signed VLQ encoding. :param int value: The value to encode. :return: The encoded integer. :rtype: bytes """ if value == 0: return b"\0" if value < 0: sign_bit = 0x40 value = -value else: sign_bit = 0 n_bits = value.bit_length() n_bytes = 1 + int(math.ceil((n_bits - 6) / 7)) buf = bytearray(n_bytes) for i in range(n_bytes - 1, 0, -1): buf[i] = 0x80 | (value & 0x7F) value >>= 7 buf[0] = 0x80 | sign_bit | (value & 0x3F) buf[-1] &= 0x7F return bytes(buf)
daf9ed4a794754a3cd402e8cc4c3e614857941fe
2,869
def get_html_subsection(name): """ Return a subsection as HTML, with the given name :param name: subsection name :type name: str :rtype: str """ return "<h2>{}</h2>".format(name)
2e0f37a7bb9815eda24eba210d8518e64595b9b7
2,872
import random def shuffle(answers): """ Returns mixed answers and the index of the correct one, assuming the first answer is the correct one. """ indices = list(range(len(answers))) random.shuffle(indices) correct = indices.index(0) answers = [answers[i] for i in indices] return answers, correct
e597b4aeb65fecf47f4564f2fddb4d76d484707a
2,875
from typing import List from pathlib import Path def get_requirements(req_file: str) -> List[str]: """ Extract requirements from provided file. """ req_path = Path(req_file) requirements = req_path.read_text().split("\n") if req_path.exists() else [] return requirements
3433cd117bbb0ced7ee8238e36f20c69e15c5260
2,876
def align_dataframes(framea, frameb, fill_value = 0.0): """Use pandas DataFrame structure to align two-dimensional data :param framea: First pandas dataframe to align :param frameb: Other pandas dataframe to align :param fill_value: default fill value (0.0 float) return: tuple of aligned frames """ zeroframe = frameb.copy() zeroframe[:] = fill_value aligneda = framea.add(zeroframe, fill_value = fill_value) zeroframe = framea.copy() zeroframe[:] = fill_value alignedb = frameb.add(zeroframe, fill_value = fill_value) return aligneda, alignedb
86a5e8c399ab47a10715af6c90d0901c2207597c
2,878
def dm2skin_normalizeWeightsConstraint(x): """Constraint used in optimization that ensures the weights in the solution sum to 1""" return sum(x) - 1.0
79024cb70fd6cbc3c31b0821baa1bcfb29317043
2,884
import glob def find_pkg(pkg): """ Find the package file in the repository """ candidates = glob.glob('/repo/' + pkg + '*.rpm') if len(candidates) == 0: print("No candidates for: '{0}'".format(pkg)) assert len(candidates) == 1 return candidates[0]
ac91f34ed7accd2c81e1c68e143319998de9cdf3
2,888
def _check_eq(value): """Returns a function that checks whether the value equals a particular integer. """ return lambda x: int(x) == int(value)
4d2a02727afd90dbc012d252b01ed72f745dc564
2,891
def calcPhase(star,time): """ Calculate the phase of an orbit, very simple calculation but used quite a lot """ period = star.period phase = time/period return phase
4b282d9e4fdb76a4358d895ba30b902328ce030c
2,893
def inv(n: int, n_bits: int) -> int: """Compute the bitwise inverse. Args: n: An integer. n_bits: The bit-width of the integers used. Returns: The binary inverse of the input. """ # We should only invert the bits that are within the bit-width of the # integers we use. We set this mask to set the other bits to zero. bit_mask = (1 << n_bits) - 1 # e.g. 0b111 for n_bits = 3 return ~n & bit_mask
5be1eaf13490091096b8cd13fdbcdbbbe43760da
2,895
def check_for_features(cmph5_file, feature_list): """Check that all required features present in the cmph5_file. Return a list of features that are missing. """ aln_group_path = cmph5_file['AlnGroup/Path'][0] missing_features = [] for feature in feature_list: if feature not in cmph5_file[aln_group_path].keys(): missing_features.append(feature) return missing_features
2d51e1389e6519607001ad2b0006581e6a876ddd
2,899
import re def compress_sparql(text: str, prefix: str, uri: str) -> str: """ Compress given SPARQL query by replacing all instances of the given uri with the given prefix. :param text: SPARQL query to be compressed. :param prefix: prefix to use as replace. :param uri: uri instance to be replaced. :return: compressed SPARQL query. """ bordersremv = lambda matchobj: prefix + ":" + re.sub(f"[<>]|({uri})", "", matchobj.group(0)) return re.sub(f"<?({uri}).*>?", bordersremv, text)
b86ceebadb262730fb4dec90b43e04a09d9c9541
2,901
def use(*authenticator_classes): """ A decorator to attach one or more :class:`Authenticator`'s to the decorated class. Usage: from thorium import auth @auth.use(BasicAuth, CustomAuth) class MyEngine(Endpoint): ... OR @auth.use(BasicAuth) @auth.use(CustomAuth) class MyEngine(Endpoint): ... :param authenticator_classes: One or more :class:`Authenticator` class definitions. """ def wrapped(cls): if not cls._authenticator_classes: cls._authenticator_classes = [] cls._authenticator_classes.extend(authenticator_classes) return cls return wrapped
27aeb7711c842540a1ed77a76cebeb61e0342f1e
2,905
import math def mutual_information(co_oc, oi, oj, n): """ :param co_oc: Number of co occurrences of the terms oi and oj in the corpus :param oi: Number of occurrences of the term oi in the corpus :param oj: Number of occurrences of the term oi in the corpus :param n: Total number of words in the corpus :return: """ e = (oi * oj)/n return math.log2(co_oc/e)
76c27295c7e757282573eab71f2bb7cfd3df74cb
2,906
def merge_options(custom_options, **default_options): """ Utility function to merge some default options with a dictionary of custom_options. Example: custom_options = dict(a=5, b=3) merge_options(custom_options, a=1, c=4) --> results in {a: 5, b: 3, c: 4} """ merged_options = default_options merged_options.update(custom_options) return merged_options
a1676c9304f3c231aefaeb107c8fb6f5a8251b26
2,909
def _filter_nones(centers_list): """ Filters out `None` from input list Parameters ---------- centers_list : list List potentially containing `None` elements Returns ------- new_list : list List without any `None` elements """ return [c for c in centers_list if c is not None]
031e878ebc8028deea238f5ac902ca55dba72a6d
2,910
def isolate_integers(string): """Isolate positive integers from a string, returns as a list of integers.""" return [int(s) for s in string.split() if s.isdigit()]
cc95f7a37e3ae258ffaa54ec59f4630c600e84e1
2,911
import json def store_barbican_secret_for_coriolis( barbican, secret_info, name='Coriolis Secret'): """ Stores secret connection info in Barbican for Coriolis. :param barbican: barbican_client.Client instance :param secret_info: secret info to store :return: the HREF (URL) of the newly-created Barbican secret """ payload = json.dumps(secret_info) secret = barbican.secrets.create( name=name, payload=payload, payload_content_type='application/json') secret_ref = secret.store() return secret_ref
218bf941203dd12bc78fc7a87d6a2f9f21761d57
2,912
def normalize(features): """ Scale data in provided series into [0,1] range. :param features: :return: """ return (features - features.min()) / (features.max() - features.min())
a85d77e37e71c732471d7dcd42ae1aef2181f6dc
2,915
from datetime import datetime import time def dateToUsecs(datestring): """Convert Date String to Unix Epoc Microseconds""" dt = datetime.strptime(datestring, "%Y-%m-%d %H:%M:%S") return int(time.mktime(dt.timetuple())) * 1000000
cba081ae63523c86572463249b4324f2183fcaaa
2,917
def find_vertical_bounds(hp, T): """ Finds the upper and lower bounds of the characters' zone on the plate based on threshold value T :param hp: horizontal projection (axis=1) of the plate image pixel intensities :param T: Threshold value for bound detection :return: upper and lower bounds """ N = len(hp) # Find lower bound i = 0 while ~((hp[i] <= T) & (hp[i+1] > T)) & (i < int(N/2)): i += 1 lower_bound = 0 if i == int(N/2) else i # Find superior bound i = N-1 while ~((hp[i-1] > T) & (hp[i] <= T)) & (i > int(N/2)): i -= 1 upper_bound = i return [lower_bound, upper_bound]
8520c3b638cafe1cfb2d86cc7ce8c3f28d132512
2,921
def cost_n_moves(prev_cost: int, weight: int = 1) -> int: """ 'g(n)' cost function that adds a 'weight' to each move.""" return prev_cost + weight
77a737d68f2c74eaba484b36191b95064b05e1a9
2,924
def meh(captcha): """Returns the sum of the digits which match the next one in the captcha input string. >>> meh('1122') 3 >>> meh('1111') 4 >>> meh('1234') 0 >>> meh('91212129') 9 """ result = 0 for n in range(len(captcha)): if captcha[n] == captcha[(n + 1) % len(captcha)]: result += int(captcha[n]) return result
2ff68455b7bb826a81392dba3bc8899374cbcc3e
2,927
def goodput_for_range(endpoint, first_packet, last_packet): """Computes the goodput (in bps) achieved between observing two specific packets""" if first_packet == last_packet or \ first_packet.timestamp_us == last_packet.timestamp_us: return 0 byte_count = 0 seen_first = False for packet in endpoint.packets: if packet == last_packet: break if packet == first_packet: seen_first = True if not seen_first: continue # Packet contributes to goodput if it was not retransmitted if not packet.is_lost(): byte_count += packet.data_len time_us = last_packet.timestamp_us - first_packet.timestamp_us return byte_count * 8 * 1E6 / time_us
aea56993771c1a250dacdfccf8328c7a0d3ce50b
2,929
def get_string_from_bytes(byte_data, encoding="ascii"): """Decodes a string from DAT file byte data. Note that in byte form these strings are 0 terminated and this 0 is removed Args: byte_data (bytes) : the binary data to convert to a string encoding (string) : optional, the encoding type to use when converting """ string_bytes = byte_data[0:(len(byte_data) - 1)] # strip off the 0 at the end of the string string = string_bytes.decode(encoding) return string
c07523139e2509fcc19b2ce1d9a933fcb648abfd
2,931
def is_free(board: list, pos: int) -> bool: """checks if pos is free or filled""" return board[pos] == " "
64b75aa5d5b22887495e631e235632e080646422
2,933
def serialize_measurement(measurement): """Serializes a `openff.evaluator.unit.Measurement` into a dictionary of the form `{'value', 'error'}`. Parameters ---------- measurement : openff.evaluator.unit.Measurement The measurement to serialize Returns ------- dict of str and str A dictionary representation of a openff.evaluator.unit.Measurement with keys of {"value", "error"} """ return {"value": measurement.value, "error": measurement.error}
69eedd9006c63f5734c762d6113495a913d5a8c4
2,935
def rename_record_columns(records, columns_to_rename): """ Renames columns for better desc and to match Socrata column names :param records: list - List of record dicts :param columns_to_rename: dict - Dict of Hasura columns and matching Socrata columns """ for record in records: for column, rename_value in columns_to_rename.items(): if column in record.keys(): record[rename_value] = record.pop(column) return records
41d5cc90a368f61e8ce138c54e9f5026bacd62b9
2,936
def remove_list_by_name(listslist, name): """ Finds a list in a lists of lists by it's name, removes and returns it. :param listslist: A list of Twitter lists. :param name: The name of the list to be found. :return: The list with the name, if it was found. None otherwise. """ for i in range(len(listslist)): if listslist[i].name == name: return listslist.pop(i)
356a7d12f3b2af9951327984ac6d55ccb844bf72
2,939
def is_int(var): """ is this an integer (ie, not a float)? """ return isinstance(var, int)
09924c6ea036fc7ee1add6ccbefc3fb0c9696345
2,944
def returnstringpacket(pkt): """Returns a packet as hex string""" myString = "" for c in pkt: myString += "%02x" % c return myString
866ef7c69f522d4a2332798bdf97a966740ea0e4
2,945
def get_conversion_option(shape_records): """Prompts user for conversion options""" print("1 - Convert to a single zone") print("2 - Convert to one zone per shape (%d zones) (this can take a while)" % (len(shape_records))) import_option = int(input("Enter your conversion selection: ")) return import_option
7608c588960eb3678970e0d4467c67ff9f17a331
2,952
from functools import reduce import operator def product_consec_digits(number, consecutive): """ Returns the largest product of "consecutive" consecutive digits from number """ digits = [int(dig) for dig in str(number)] max_start = len(digits) - consecutive return [reduce(operator.mul, digits[i:i + consecutive]) for i in range(max_start + 1)]
2df16f7445e6d579b632e86904b77ec93e52a1f3
2,953
def generate_legacy_dir(ctx, config, manifest, layers): """Generate a intermediate legacy directory from the image represented by the given layers and config to /image_runfiles. Args: ctx: the execution context config: the image config file manifest: the image manifest file layers: the list of layer tarballs Returns: The filepaths generated and runfiles to be made available. config: the generated config file. layers: the generated layer tarball files. temp_files: all the files generated to be made available at runtime. """ # Construct image runfiles for input to pusher. image_files = [] + layers if config: image_files += [config] if manifest: image_files += [manifest] path = "image_runfiles/" layer_files = [] # Symlink layers to ./image_runfiles/<i>.tar.gz for i in range(len(layers)): layer_symlink = ctx.actions.declare_file(path + str(i) + ".tar.gz") layer_files.append(layer_symlink) ctx.actions.run_shell( outputs = [layer_symlink], inputs = [layers[i]], command = "ln {src} {dst}".format( src = layers[i].path, dst = layer_symlink.path, ), ) # Symlink config to ./image_runfiles/config.json config_symlink = ctx.actions.declare_file(path + "config.json") ctx.actions.run_shell( outputs = [config_symlink], inputs = [config], command = "ln {src} {dst}".format( src = config.path, dst = config_symlink.path, ), ) return { "config": config_symlink, "layers": layer_files, "temp_files": [config_symlink] + layer_files, }
6001820e63ac3586625f7ca29311d717cc1e4c07
2,954
def workflow_key(workflow): """Return text search key for workflow""" # I wish tags were in the manifest :( elements = [workflow['name']] elements.extend(workflow['tags']) elements.extend(workflow['categories']) elements.append(workflow['author']) return ' '.join(elements)
57347705b605e68a286dd953de5bb157ac50628e
2,955
import locale import re def parse_price(price): """ Convert string price to numbers """ if not price: return 0 price = price.replace(',', '') return locale.atoi(re.sub('[^0-9,]', "", price))
bb90aa90b38e66adc73220665bb5e6458bfe5374
2,958
def zscore(dat, mean, sigma): """Calculates zscore of a data point in (or outside of) a dataset zscore: how many sigmas away is a value from the mean of a dataset? Parameters ---------- dat: float Data point mean: float Mean of dataset sigma: flaot Sigma of dataset """ zsc = (dat-mean)/sigma return zsc
b11216e50632e2024af0a389184d5e1dba7ed4fd
2,963
def unused(attr): """ This function check if an attribute is not set (has no value in it). """ if attr is None: return True else: return False
febc225f3924fdb9de6cfbf7eba871cce5b6e374
2,965
def get_evaluate_SLA(SLA_terms, topology, evaluate_individual): """Generate a function to evaluate if the flow reliability and latency requirements are met Args: SLA_terms {SLA} -- an SLA object containing latency and bandwidth requirements topology {Topology} -- the reference topology object for the flow evaluate_individual {function}: a cost function, which returns the metric for a given individual individual {DEAP individual (list)} -- the individual Returns: evaluate_SLA {Function}: a function returning True if the requirements are met, False otherwise """ def evaluate_SLA(individual): evaluation = evaluate_individual(individual) if evaluation[3] > SLA_terms.latency or evaluation[1] > 1: return False return True return evaluate_SLA
81fdaa07e3fc21066ab734bef0cc71457d40fb5b
2,966
def latest_consent(user, research_study_id): """Lookup latest valid consent for user :param user: subject of query :param research_study_id: limit query to respective value If latest consent for user is 'suspended' or 'deleted', this function will return None. See ``consent_withdrawal_dates()`` for that need. :returns: the most recent consent based on given criteria, or None if no match is located """ # consents are ordered desc(acceptance_date) for consent in user.valid_consents: if consent.research_study_id != research_study_id: continue if consent.status == 'consented': return consent return None
2295b592a0c1fdaf3b1ed21e065f39e73a4bb622
2,967
from typing import Tuple def find_next_tag(template: str, pointer: int, left_delimiter: str) -> Tuple[str, int]: """Find the next tag, and the literal between current pointer and that tag""" split_index = template.find(left_delimiter, pointer) if split_index == -1: return (template[pointer:], len(template)) return (template[pointer:split_index], split_index)
82d091ef6738ffbe93e8ea8a0096161fc359e9cb
2,968
def hamiltonian_c(n_max, in_w, e, d): """apply tridiagonal real Hamiltonian matrix to a complex vector Parameters ---------- n_max : int maximum n for cutoff in_w : np.array(complex) state in d : np.array(complex) diagonal elements of Hamiltonian e : np.array(complex) off diagonal elements of Hamiltonian Returns ------- out_w : np.array(complex) application of Hamiltonian to vector """ n_max = int(n_max) out_w = in_w[:n_max]*d[:n_max] out_w[:(n_max-1)] += e[:(n_max-1)]*in_w[1:n_max] out_w[1:n_max] += e[:n_max-1] * in_w[:n_max-1] return out_w
9b78d86592622100322d7a4ec031c1bd531ca51a
2,970
def grow_population(initial, days_to_grow): """ Track the fish population growth from an initial population, growing over days_to_grow number of days. To make this efficient two optimizations have been made: 1. Instead of tracking individual fish (which doubles every approx. 8 days which will result O(10^9) fish over 256 days), we instead compute the sum of fish with the same due date and use the due date as the offset into the current popluation list. For example, if 5 fish have a timer of 1 and 2 fish have a timer of 4 the population would be tracked as: [0, 5, 0, 0, 2, 0, 0, 0, 0] 2. Modulo arithmetic is used instead of fully iterating through the entire list to decrement the due date of each fish every day. Using modula arithmetic provides a projection into the fish data that looks like its changing each day without needing O(n) operations and instead we can update the list in constant time regardless of the number of different ages for fish. """ current = list(initial) if days_to_grow == 0: return current for day in range(0, days_to_grow): due_index = day % 9 due_count = current[due_index] current[(day+7)%9] += due_count current[(day+9)%9] += due_count current[due_index] = max(0, current[due_index] - due_count) return current
88b8283e5c1e6de19acb76278ef16d9d6b94de00
2,974
import six def _ensure_list(alist): # {{{ """ Ensure that variables used as a list are actually lists. """ # Authors # ------- # Phillip J. Wolfram, Xylar Asay-Davis if isinstance(alist, six.string_types): # print 'Warning, converting %s to a list'%(alist) alist = [alist] return alist
bd8115dad627f4553ded17757bfb838cfdb0200b
2,975
def showgraphwidth(context, mapping): """Integer. The width of the graph drawn by 'log --graph' or zero.""" # just hosts documentation; should be overridden by template mapping return 0
6e2fad8c80264a1030e5a113d66233c3adc28af8
2,980
def merge_two_sorted_array(l1, l2): """ Time Complexity: O(n+m) Space Complexity: O(n+m) :param l1: List[int] :param l2: List[int] :return: List[int] """ if not l1: return l2 if not l2: return l1 merge_list = [] i1 = 0 i2 = 0 l1_len = len(l1) - 1 l2_len = len(l2) - 1 while i1 <= l1_len and i2 <= l2_len: if l1[i1] < l2[i2]: merge_list.append(l1[i1]) i1 += 1 else: merge_list.append(l2[i2]) i2 += 1 while i1 <= l1_len: merge_list.append(l1[i1]) i1 += 1 while i2 <= l2_len: merge_list.append(l2[i2]) i2 += 1 return merge_list
2671d21707056741bbdc4e3590135e7e1be4c7e9
2,987
def check_similarity(var1, var2, error): """ Check the simulatiry between two numbers, considering a error margin. Parameters: ----------- var1: float var2: float error: float Returns: ----------- similarity: boolean """ if((var1 <= (var2 + error)) and (var1 >= (var2 - error))): return True else: return False
305fd08cf4d8b1718d8560315ebf7bd03a4c7e2a
2,989
def getCasing(word): """ Returns the casing of a word""" if len(word) == 0: return 'other' elif word.isdigit(): #Is a digit return 'numeric' elif word.islower(): #All lower case return 'allLower' elif word.isupper(): #All upper case return 'allUpper' elif word[0].isupper(): #is a title, initial char upper, then all lower return 'initialUpper' return 'other'
2af70926c0cbbde6310abb573ccc3ee8260b86bd
2,990
def normalize_angle(deg): """ Take an angle in degrees and return it as a value between 0 and 360 :param deg: float or int :return: float or int, value between 0 and 360 """ angle = deg while angle > 360: angle -= 360 while angle < 360: angle += 360 return angle
cd4788819bbc8fce17ca7c7b1b320499a3893dee
2,991
def makeFields(prefix, n): """Generate a list of field names with this prefix up to n""" return [prefix+str(n) for n in range(1,n+1)]
435571557ef556b99c4729500f372cc5c9180052
2,992
def process_input_dir(input_dir): """ Find all image file paths in subdirs, convert to str and extract labels from subdir names :param input_dir Path object for parent directory e.g. train :returns: list of file paths as str, list of image labels as str """ file_paths = list(input_dir.rglob('*.png')) file_path_strings = [str(path) for path in file_paths] label_strings = [path.parent.name for path in file_paths] return file_path_strings, label_strings
569d4539368888c91a12538156c611d311da03b6
2,993
def fak(n): """ Berechnet die Fakultaet der ganzen Zahl n. """ erg = 1 for i in range(2, n+1): erg *= i return erg
9df6f4fa912a25535369f4deb0a06baef8e6bdcc
2,994
import re def create_sequences_sonnets(sonnets): """ This creates sequences as done in Homework 6, by mapping each word to an integer in order to create a series of sequences. This function specifically makes entire sonnets into individual sequences and returns the list of processed sonnets back to be used in the basic HMM notebook for generation. """ sequences = [] obs_counter = 0 obs_map = {} for sonnet in sonnets: sequence = [] for i, line in enumerate(sonnet): split = line.split() for word in split: word = re.sub(r'[^\w]', '', word).lower() if word not in obs_map: # Add unique words to the observations map. obs_map[word] = obs_counter obs_counter += 1 # Add the encoded word. sequence.append(obs_map[word]) # Add the encoded sequence. sequences.append(sequence) return obs_map, sequences
56087140fe5ed8934b64a18567b4e9023ddc6f59
2,995
def load_subspace_vectors(embd, subspace_words): """Loads all word vectors for the particular subspace in the list of words as a matrix Arguments embd : Dictonary of word-to-embedding for all words subspace_words : List of words representing a particular subspace Returns subspace_embd_mat : Matrix of word vectors stored row-wise """ subspace_embd_mat = [] ind = 0 for word in subspace_words: if word in embd: subspace_embd_mat.append(embd[word]) ind = ind+1 return subspace_embd_mat
5eb1db8be8801cf6b1fe294a6f2c93570e9a9fe1
3,000
import codecs import binascii def decode_hex(data): """Decodes a hex encoded string into raw bytes.""" try: return codecs.decode(data, 'hex_codec') except binascii.Error: raise TypeError()
115e89d6f80a6fc535f44d92f610a6312edf6daf
3,001
def generate_headermap(line,startswith="Chr", sep="\t"): """ >>> line = "Chr\\tStart\\tEnd\\tRef\\tAlt\\tFunc.refGene\\tGene.refGene\\tGeneDetail.refGene\\tExonicFunc.refGene\\tAAChange.refGene\\tsnp138\\tsnp138NonFlagged\\tesp6500siv2_ea\\tcosmic70\\tclinvar_20150629\\tOtherinfo" >>> generate_headermap(line) {'Chr': 0, 'Start': 1, 'End': 2, 'Ref': 3, 'Alt': 4, 'Func.refGene': 5, 'Gene.refGene': 6, 'GeneDetail.refGene': 7, 'ExonicFunc.refGene': 8, 'AAChange.refGene': 9, 'snp138': 10, 'snp138NonFlagged': 11, 'esp6500siv2_ea': 12, 'cosmic70': 13, 'clinvar_20150629': 14, 'Otherinfo': 15} """ if not line.startswith(startswith): raise Exception("Header line should start with \"{0}\"".format(startswith)) else: if line.startswith("#"): line = line[1:] return dict([(v, i) for i,v in enumerate(line.rstrip().split(sep))])
16bbbc07fa13ff9bc8ec7af1aafc4ed65b20ec4c
3,016
import math def log_density_igaussian(z, z_var): """Calculate log density of zero-mean isotropic gaussian distribution given z and z_var.""" assert z.ndimension() == 2 assert z_var > 0 z_dim = z.size(1) return -(z_dim/2)*math.log(2*math.pi*z_var) + z.pow(2).sum(1).div(-2*z_var)
a412b9e25aecfc2baed2d783a2d7cd281fadc9fb
3,017
def _get_crop_frame(image, max_wiggle, tx, ty): """ Based on on the max_wiggle, determines a cropping frame. """ pic_width, pic_height = image.size wiggle_room_x = max_wiggle * .5 * pic_width wiggle_room_y = max_wiggle * .5 * pic_height cropped_width = pic_width - wiggle_room_x cropped_height = pic_height - wiggle_room_y left = int(tx * wiggle_room_x) top = int(ty * wiggle_room_y) right = left + cropped_width bottom = top + cropped_height return left, top, right, bottom
18442a97544d6c4bc4116dc43811c9fcd0d203c6
3,019
def l2sq(x): """Sum the matrix elements squared """ return (x**2).sum()
c02ea548128dde02e4c3e70f9280f1ded539cee9
3,020
def comp_number_phase_eq(self): """Compute the equivalent number of phase Parameters ---------- self : LamSquirrelCage A LamSquirrelCage object Returns ------- qb: float Zs/p """ return self.slot.Zs / float(self.winding.p)
f4679cf92dffff138a5a96787244a984a11896f9
3,021
from typing import Optional from typing import Iterable def binidx(num: int, width: Optional[int] = None) -> Iterable[int]: """ Returns the indices of bits with the value `1`. Parameters ---------- num : int The number representing the binary state. width : int, optional Minimum number of digits used. The default is the global value `BITS`. Returns ------- binidx : list """ fill = width or 0 return list(sorted(i for i, char in enumerate(f"{num:0{fill}b}"[::-1]) if char == "1"))
70d1895cf0141950d8e2f5efe6bfbf7bd8dbc30b
3,024
def _get_object_description(target): """Return a string describing the *target*""" if isinstance(target, list): data = "<list, length {}>".format(len(target)) elif isinstance(target, dict): data = "<dict, length {}>".format(len(target)) else: data = target return data
57ad3803a702a1199639b8fe950ef14b8278bec1
3,027
def computeStatistic( benchmarks, field, func ): """ Return the result of func applied to the values of field in benchmarks. Arguments: benchmarks: The list of benchmarks to gather data from. field: The field to gather from the benchmarks. func: The function to apply to the data, must accept a list and return a single value. """ results = [] for benchmark in benchmarks: results.append( benchmark[ field ] ) return func( results )
7eced912d319a3261170f8274c4562db5e28c34c
3,028
def flat_list_of_lists(l): """flatten a list of lists [[1,2], [3,4]] to [1,2,3,4]""" return [item for sublist in l for item in sublist]
c121dff7d7d9a4da55dfb8aa1337ceeea191fc30
3,031
def multiVecMat( vector, matrix ): """ Pronásobí matici vektorem zprava. Parametry: ---------- vector: list Vektor matrix: list Pronásobená matice. Její dimenze se musí shodovat s dimenzí vektoru. Vrací: list Pole velikosti vektoru. """ # Vytvoří pole o velikosti vektoru result = [0] * len( matrix[0] ) # Projde matici po řádcích for r, row in enumerate( matrix ): # Pokud nesedí rozměry, končíme if len(row) != len(vector): return None # Projde každý prvek v řádku for i, elem in enumerate( row ): # K poli s výsledkem přičte na index aktuálního řádku výsledek # násobení aktuálního prvku v řádku a jemu odpovídajícího # prvku z vektoru. result[r] += elem * vector[i] return result
8a10241173ab981d6007d8ff939199f9e86806e5
3,033
def etaCalc(T, Tr = 296.15, S = 110.4, nr = 1.83245*10**-5): """ Calculates dynamic gas viscosity in kg*m-1*s-1 Parameters ---------- T : float Temperature (K) Tr : float Reference Temperature (K) S : float Sutherland constant (K) nr : float Reference dynamic viscosity Returns ------- eta : float Dynamic gas viscosity in kg*m-1*s-1 """ eta = nr * ( (Tr + S) / (T+S) )*(T/Tr)**(3/2) return eta
3f8182ea29fd558e86280477f2e435247d09798e
3,037
def sharpe_ratio(R_p, sigma_p, R_f=0.04): """ :param R_p: 策略年化收益率 :param R_f: 无风险利率(默认0.04) :param sigma_p: 策略收益波动率 :return: sharpe_ratio """ sharpe_ratio = 1.0 * (R_p - R_f) / sigma_p return sharpe_ratio
d197df7aa3b92f3a32cc8f11eb675012ffe8af57
3,039
def _inline_svg(svg: str) -> str: """Encode SVG to be used inline as part of a data URI. Replacements are not complete, but sufficient for this case. See https://codepen.io/tigt/post/optimizing-svgs-in-data-uris for details. """ replaced = ( svg .replace('\n', '%0A') .replace('#', '%23') .replace('<', '%3C') .replace('>', '%3E') .replace('"', '\'') ) return 'data:image/svg+xml,' + replaced
4e3c25f5d91dd7691f42f9b9ace4d64a297eb32f
3,040
import click def implemented_verified_documented(function): """ Common story options """ options = [ click.option( '--implemented', is_flag=True, help='Implemented stories only.'), click.option( '--unimplemented', is_flag=True, help='Unimplemented stories only.'), click.option( '--verified', is_flag=True, help='Stories verified by tests.'), click.option( '--unverified', is_flag=True, help='Stories not verified by tests.'), click.option( '--documented', is_flag=True, help='Documented stories only.'), click.option( '--undocumented', is_flag=True, help='Undocumented stories only.'), click.option( '--covered', is_flag=True, help='Covered stories only.'), click.option( '--uncovered', is_flag=True, help='Uncovered stories only.'), ] for option in reversed(options): function = option(function) return function
8c1dd5aaa0b962d96e9e90336183a29e2cf360db
3,041
import json def get_config(config_path): """ Open a Tiler config and return it as a dictonary """ with open(config_path) as config_json: config_dict = json.load(config_json) return config_dict
72a2133b44ffc553ad72d6c9515f1f218de6a08c
3,049
import binascii def fmt_hex(bytes): """Format the bytes as a hex string, return upper-case version. """ # This is a separate function so as to not make the mistake of # using the '%X' format string with an ints, which will not # guarantee an even-length string. # # binascii works on all versions of Python, the hex encoding does not. hex = binascii.hexlify(bytes) hex = hex.decode() # Returns bytes, which makes no sense to me return hex.upper()
d25379ec333a653549c329932e304e61c57f173d
3,050
import json import six def _HandleJsonList(response, service, method, errors): """Extracts data from one *List response page as JSON and stores in dicts. Args: response: str, The *List response in JSON service: The service which responded to *List request method: str, Method used to list resources. One of 'List' or 'AggregatedList'. errors: list, Errors from response will be appended to this list. Returns: Pair of: - List of items returned in response as dicts - Next page token (if present, otherwise None). """ items = [] response = json.loads(response) # If the request is a list call, then yield the items directly. if method == 'List': items = response.get('items', []) # If the request is an aggregatedList call, then do all the # magic necessary to get the actual resources because the # aggregatedList responses are very complicated data # structures... elif method == 'AggregatedList': items_field_name = service.GetMethodConfig( 'AggregatedList').relative_path.split('/')[-1] for scope_result in six.itervalues(response['items']): # If the given scope is unreachable, record the warning # message in the errors list. warning = scope_result.get('warning', None) if warning and warning['code'] == 'UNREACHABLE': errors.append((None, warning['message'])) items.extend(scope_result.get(items_field_name, [])) return items, response.get('nextPageToken', None)
db87c9ed87df1268e1187f74c193b5f96f9e10f7
3,054
def clip(x, min_, max_): """Clip value `x` by [min_, max_].""" return min_ if x < min_ else (max_ if x > max_ else x)
3ad7625fa3dc5a0c06bb86dc16698f6129ee9034
3,055
def coordinateToIndex(coordinate): """Return a raw index (e.g [4, 4]) from board coordinate (e.g. e4)""" return [abs(int(coordinate[1]) - 8), ("a", "b", "c", "d", "e", "f", "g", "h").index(coordinate[0])]
d3dcf6d01c4bec2058cffef88867d45ba51ea560
3,069
def get_parent(inst, rel_type='cloudify.relationships.contained_in'): """ Gets the parent of an instance :param `cloudify.context.NodeInstanceContext` inst: Cloudify instance :param string rel_type: Relationship type :returns: Parent context :rtype: :class:`cloudify.context.RelationshipSubjectContext` or None """ for rel in inst.relationships: if rel_type in rel.type_hierarchy: return rel.target return None
06bc76ec55735a47a3cf26df2daa4346290671ee
3,071
def get_shared_keys(param_list): """ For the given list of parameter dictionaries, return a list of the dictionary keys that appear in every parameter dictionary >>> get_shared_keys([{'a':0, 'b':1, 'c':2, 'd':3}, {'a':0, 'b':1, 'c':3}, {'a':0, 'b':'beta'}]) ['a', 'b'] >>> get_shared_keys([{'a':0, 'd':3}, {'a':0, 'b':1, 'c':2, 'd':3}, {'a':0, 'b':1, 'c':2}]) ['a'] """ if not param_list: return keys = set(param_list[0].keys()) for i in range(1, len(param_list)): keys = keys.intersection(param_list[i].keys()) keys = list(keys) keys.sort() return keys
0f6aa0df4d61ba166ac7d660be80a98fdbc29080
3,074