content
stringlengths
39
9.28k
sha1
stringlengths
40
40
id
int64
8
710k
import re def str_find_all(str_input, match_val): """ Function returns indexes of all occurrences of matchVal inside of str_input """ return [m.start() for m in re.finditer(match_val, str_input)]
7a41f874806b4bcdcbd8791cdcf6f4f8292d5dc0
223,215
def is_midday(this_t): """ Return true if this_t is "mid-day" in North America. "Mid-day" is defined as between 15:00 and 23:00 UTC, which is 10:00 EST to 15:00 PST. INPUTS this_t: a datetime.datetime object OUTPUTS True or False """ return ((this_t.hour >= 15) and (this_t.hour <= 23))
4fbe87ec65c3943d18d4b0ad7eb3b106f0b14ced
306,210
def string_like(value, name, optional=False, options=None, lower=True): """ Check if object is string-like and raise if not Parameters ---------- value : object Value to verify. name : str Variable name for exceptions. optional : bool Flag indicating whether None is allowed. options : tuple[str] Allowed values for input parameter `value`. lower : bool Convert all case-based characters in `value` into lowercase. Returns ------- str The validated input Raises ------ TypeError If the value is not a string or None when optional is True. ValueError If the input is not in ``options`` when ``options`` is set. """ if value is None: return None if not isinstance(value, str): extra_text = " or None" if optional else "" raise TypeError("{0} must be a string{1}".format(name, extra_text)) if lower: value = value.lower() if options is not None and value not in options: extra_text = "If not None, " if optional else "" options_text = "'" + "', '".join(options) + "'" msg = "{0}{1} must be one of: {2}".format( extra_text, name, options_text ) raise ValueError(msg) return value
17c95e147684e0d0fc473f66c7e1e0597bec9111
465,856
from typing import Iterator from typing import Sequence def head_reader( rows: Iterator[Sequence[str]] ) -> Iterator[Sequence[str]]: """Consumes three header rows and returns the iterator.""" r0 = next(rows) r1 = next(rows) r2 = next(rows) assert set(r2) == {"x", "y"}, set(r2) return rows
bfbc453cf57cae3d3b3f39e22db70a3eb5ddaeed
247,071
def grouper(list_, n): """ Collect data into fixed-length chunks or blocks Adapt from https://docs.python.org/3/library/itertools.html#itertools-recipes >>> list(grouper('ABCDEF', 3)) [("A", "B", "C"), ("D", "E")] """ assert len(list_) % n == 0 args = [iter(list_)] * n return zip(*args)
f438a247b60597775bdaa4859de55d2cafb925d9
240,278
def set_active_editor(oDesign, editorname="3D Modeler"): """ Set the active editor. Parameters ---------- oDesign : pywin32 COMObject The HFSS design upon which to operate. editorname : str Name of the editor to set as active. As of this writing "3D Modeler" is the only known valid value. Returns ------- oEditor : pywin32 COMObject The HFSS Editor object. """ oEditor = oDesign.SetActiveEditor(editorname) return oEditor
906cc753c5b6acb9e8e26dfa71986c4c41a4d6f6
135,807
from typing import List from typing import Dict def str_to_sql_dict(tables: List[str]) -> List[Dict]: """ Transforms a list of tables/procedures names into a list of dictionaries with keys schema and name :param tables: list ot table names :return: list of table dictionaries """ return [dict(zip(['schema', 'name'], t.lower().split('.'))) for t in tables]
03249755df54b86b288116b62fe3775ff044f303
231,005
import functools def _register_style(style_list, cls=None, *, name=None): """Class decorator that stashes a class in a (style) dictionary.""" if cls is None: return functools.partial(_register_style, style_list, name=name) style_list[name or cls.__name__.lower()] = cls return cls
e186f3e9cd54fbf9a8f3191b6ec7bc930fa8b4f8
519,431
from typing import Optional from typing import List def compact(array: Optional[List]) -> Optional[List]: """Compact an list by removing `None` elements. If the result is an empty list, return `None` :param array: Inital list to compact :type array: List :return: Final compacted list or None :rtype: Optional[List] """ if isinstance(array, dict): array = list(array.values()) if isinstance(array, List): array = [e for e in array if e is not None] if len(array) > 0: return array return None
20271464dd9b1c312be6bd12f7df40dfc10076d5
574,731
def split_str_to_list(input_str, split_char=","): """Split a string into a list of elements. Args: input_str (str): The string to split split_char (str, optional): The character to split the string by. Defaults to ",". Returns: (list): The string split into a list """ # Split a string into a list using `,` char split_str = input_str.split(split_char) # For each element in split_str, strip leading/trailing whitespace for i, element in enumerate(split_str): split_str[i] = element.strip() return split_str
2b13868aed1869310a1398886f6777ddceb6c777
708,964
def returnListWithoutOutliers(data, outlierRange): """ An outlier is defiend as a datapoint not in [Q1 - 1.5*IQR*outlierRange, Q3 + 1.5*IQR*outlierRange], where IQR is the interquartile range: Q3 - Q1 """ data.sort() dataPointsBefore = len(data) Q1 = data[dataPointsBefore//4] Q3 = data[3*dataPointsBefore//4] IQR = Q3 - Q1 lowerFence = Q1 - 1.5 * IQR * outlierRange upperFence = Q3 + 1.5 * IQR * outlierRange filteredData = [i for i in data if i >= lowerFence and i <= upperFence] dataPointsAfter = len(filteredData) print('Removed ' + str(dataPointsBefore - dataPointsAfter) + ' outliers') return filteredData
1c8dc965af7057dddeec7e44cd95f21702e5fd99
112,529
def validate(img): """ validate correct numpy.ndarray shape for get_prediction function - Input one arguments: image read as numpy.ndarray - Output True/False if the array has shape (x, y, 3) """ if img.shape[2] == 3: return True else: return False
634ee537694bf045688d2dc91cc27bb00ad68cf0
383,377
import six import base64 def nice64(src): """ Returns src base64-encoded and formatted nicely for our XML, as Unicode. """ # If src is a Unicode string, we encode it as UTF8. if isinstance(src, six.text_type): src = src.encode('utf8') return base64.b64encode(src).decode('utf8').replace('\n', '')
0e9c9861ef05e612c564bd535d6278a6410c5c2f
435,190
def p_count(value): """ Jinja2 custom filter to use for Peewee query count """ return value.count()
8958f3ab6b3bf9b2359ae4ef7628c4bd14c5c858
299,279
import re def _collapse_impacted_interfaces(text): """Removes impacted interfaces details, leaving just the summary count.""" return re.sub( r"^( *)([^ ]* impacted interfaces?):\n(?:^\1 .*\n)*", r"\1\2\n", text, flags=re.MULTILINE)
504bf7170ea4624d1703ff7ed25106a5bb671834
115,774
def area_triangle(base: float, height: float) -> float: """ Calculate the area of a triangle given the base and height. >>> area_triangle(10, 10) 50.0 >>> area_triangle(-1, -2) Traceback (most recent call last): ... ValueError: area_triangle() only accepts non-negative values >>> area_triangle(1, -2) Traceback (most recent call last): ... ValueError: area_triangle() only accepts non-negative values >>> area_triangle(-1, 2) Traceback (most recent call last): ... ValueError: area_triangle() only accepts non-negative values """ if base < 0 or height < 0: raise ValueError("area_triangle() only accepts non-negative values") return (base * height) / 2
33520e4457a027157886ab14f1822b1675b2fa92
22,726
def lpad(s, l): """ add spaces to the beginning of s until it is length l """ s = str(s) return " "*max(0, (l - len(s))) + s
f903e9beea4cbc43bd2453f9f768923b3e088a07
655,365
import string def lstrip(s): """strip whitespace from the left hand side of a string, returning a tuple (string, number_of_chars_stripped) for S""" num_stripped = 0 for i in s: # for bytes char = chr(i) if type(i) == int else i if char in string.whitespace: s = s[1:] num_stripped += 1 else: break return (s, num_stripped)
5330e27709bbf5078396662c0978310bf2946e02
336,388
import re def check_for_masked_bases(seq, max_masked=20): """Check sequence has runs of masked bases.""" return bool(re.search(r"[acgtnN]{" + str(max_masked) + "}", seq))
86a09d5e53068716b6a9e700f4e6829daa26c169
392,867
def node_access(G, node, degree=1, direction="backward"): """ Return the set of nodes which lead to "node" (direction = backaward) or the set o nodes which can be accessed from "node" (direction = forward) Parameters: G - Networkx muldigraph node - Node whose accessibility will be tested degree - Number of hops (backwards or forwards) direction - Test forwards or backwards Return: set of backward/forward nodes """ # Access can be forward or backwards func = (G.successors if direction == "forward" else G.predecessors) access_set = set() access = [node] access_set = access_set.union(access) for i in range(0, degree): # Predecessors i degrees away access_i = set() for j in access: access_i = access_i.union(set(func(j))) access = access_i access_set = access_set.union(access) return access_set
e0fd2c6693480684b46dbad188efc36dd7a27fe7
266,528
def chunk(value, size=2): """ size=2: 'abcdefg' -> ['ab', 'cd', 'ef', 'gh'] """ return [value[0 + i:size + i] for i in range(0, len(value), size)]
b4c32503074cf6d85f80a3ca046f348065bcbe0d
129,241
import requests def getHTML(url, needPretty=False): """ 获取网页 HTML 返回字符串 Args: url: str, 网页网址 needPretty: bool, 是否需要美化(开发或测试时可用) Returns: HTML 字符串 """ headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) ' 'Chrome/84.0.4147.125 Safari/537.36 ' } response = requests.get(url, headers=headers) return response.text
49c2f5066bf52f97ed88c204e2ed3703f47df960
281,621
def tell_me_about(s): """Return a tuple containing the type of the input string and the input string itself. """ return (type(s), s)
5f3e30966a130d587f23fbb89b8db91e1b942bee
179,864
def get_datastore_for_server(server): """ Given a server, return its datastore based on its first disk. """ root_disk = server.disks.first() if root_disk: return root_disk.cast().datastore return None
d235dcf6e0f5e87133da378d6aef5288b139ce4b
465,275
def build_pathnet_graph(p_inputs, p_labels, p_task_id, pathnet, training): """Builds a PathNet graph, returns input placeholders and output tensors. Args: p_inputs: (tf.placeholder) placeholder for the input image. p_labels: (tf.placeholder) placeholder for the target labels. p_task_id: (tf.placeholder) placeholder for the task id. pathnet: (pn.PathNet) PathNet model to use. training: (bool) whether the graph is being created for training. Returns: A pair of (`train_step_op`, `out_logits`), where `train_step_op` is the training op, and `out_logits` is the final network output (classification logits). """ end_state = pathnet({ 'in_tensor': p_inputs, 'labels': p_labels, 'task_id': p_task_id, 'training': training }) # The train op is the same for all tasks. Note that the last layer in # PathNet models contains heads that compute the task losses, with one head # per task. The head is chosen depending on `task_id`, so the loss for # the current task is always under `task_loss` key in `end_state`. train_step_op = end_state['train_op'] out_logits = end_state['in_tensor'] return train_step_op, out_logits
c283ac433ea8ec8864b61c7943af8735c9da6045
657,905
def convert_value(value): """ None and boolean values are not accepted by the Transip API. This method converts - None and False to an empty string, - True to 1 """ if isinstance(value, bool): return 1 if value else '' if not value: return '' return value
6c6a05df64c59185c610399dbe1d9dc9888e2086
274,770
import logging import pickle def _load_data_pickle(fname, kind="data"): """Load generic data in pickle format.""" logging.info('Loading %s and info from %s' % (kind, fname)) try: with open(fname, 'rb') as fobj: result = pickle.load(fobj) return result except Exception as e: raise Exception("{0} failed ({1}: {2})".format('_load_data_pickle', type(e), e))
48da9c4abf9d84056e754c0fce84114ccf8368f5
434,625
def get_field_value_for_record(record_cls, record_pid, field_name): """Return the given field value for a given record PID.""" record = record_cls.get_record_by_pid(record_pid) if not record or field_name not in record: message = "{0} not found in record {1}".format(field_name, record_pid) raise KeyError(message) return record[field_name]
ff32fdd481a4c191f48ac95ac4c7a505e7ed61c8
214,743
def instance_group(group_type, instance_type, instance_count, name=None): """ Construct instance group :param group_type: instance group type :type group_type: ENUM {'Master', 'Core', 'Task'} :param instance_type :type instance_type: ENUM {'g.small', 'c.large', 'm.medium', 's.medium', 'c.2xlarge'} :param instance_count :type instance_count: int :param name: instance group name :type name: string """ instance_group = { 'type': group_type, 'instanceCount': instance_count, 'instanceType': instance_type } if name is not None: instance_group['name'] = name return instance_group
b8f42f49a7cc5455cf57ce5c14d523fb85189b8f
667,691
def delimit(delimiters, content): """ Surround `content` with the first and last characters of `delimiters`. >>> delimit('[]', "foo") [foo] >>> delimit('""', "foo") '"foo"' """ if len(delimiters) != 2: raise ValueError( "`delimiters` must be of length 2. Got %r" % delimiters ) return ''.join([delimiters[0], content, delimiters[1]])
a393e2a8330c05d29855505fe679bfda4665500f
651,266
import torch def smooth_l1_loss_augmix(pred, target, beta=1.0): """Smooth L1 loss. Args: pred (torch.Tensor): The prediction. target (torch.Tensor): The learning target of the prediction. beta (float, optional): The threshold in the piecewise function. Defaults to 1.0. Returns: torch.Tensor: Calculated loss """ pred_orig, _, _ = torch.chunk(pred, 3) target, _, _ = torch.chunk(target, 3) assert beta > 0 if target.numel() == 0: return pred_orig.sum() * 0 assert pred_orig.size() == target.size() diff = torch.abs(pred_orig - target) loss_orig = torch.where(diff < beta, 0.5 * diff * diff / beta, diff - 0.5 * beta) return loss_orig
1dd60e6199160567eb3c9520186898eaae057c72
516,470
def check_multi_single(filenames): """ Check if multiple or single file is chosen. Args: filenames (list): A list of all the filepaths or string of filepath Returns: single (bool): Return whether it is a single file (True) or multiple files (False) """ num = len(filenames) if num == 1: single = bool(1) else: single = bool(0) return single
b5019bc8c644c60ad862f5868a1cd1b807006ed7
380,033
import re def StripComments(line): """Strips comments from a line and return None if the line is empty or else the contents of line with leading and trailing spaces removed and all other whitespace collapsed""" commentIndex = line.find('//') if commentIndex is -1: commentIndex = len(line) line = re.sub(r'\s+', ' ', line[:commentIndex].strip()) if line == '': return None else: return line
bc0094efd57e44c56080ec6471f1f34c9d5eae60
303,914
def largest_number(seq_seq): """ Returns the largest number in the subsequences of the given sequence of sequences. Returns None if there are NO numbers in the subsequences. For example, if the given argument is: [(3, 1, 4), (13, 10, 11, 7, 10), [1, 2, 3, 4]] then this function returns 13. As another example, if the given argument is: ([], [-1111111111111111], []) then this function returns -1111111111111111. As yet another example, if the given argument is: ([], [], []) then this function returns None. Preconditions: :type seq_seq: (list, tuple) and the given argument is a sequence of sequences, where each subsequence contains only numbers. """ # ------------------------------------------------------------------------- # DONE: 3. Implement and test this function. # Note that you should write its TEST function first (above). # ------------------------------------------------------------------------- largest = 0 for k in range(len(seq_seq)): for j in range(len(seq_seq[k])): if seq_seq[k][j] > largest or -seq_seq[k][j] > largest: largest = seq_seq[k][j] if largest != 0: return largest
5a2418e1f8ee0413e8306a04d3ee17a909b7b0c3
702,295
def error_message(e, message=None, cause=None): """ Formats exception message + cause :param e: :param message: :param cause: :return: formatted message, includes cause if any is set """ if message is None and cause is None: return None elif message is None: return '%s, caused by %r' % (e.__class__, cause) elif cause is None: return message else: return '%s, caused by %r' % (message, cause)
8017f426f8d6b94bbed729e91b48aad8f36e9fad
72,569
from typing import Iterable from typing import Callable from typing import Tuple from typing import List import itertools def partition(items: Iterable, predicate: Callable) -> Tuple[List, List]: """ :param items: iterable of items to split :param predicate: predicate to split by :return: a tuple of lists, first list does not satisfy the predicate, second list does """ a, b = itertools.tee((predicate(item), item) for item in items) return ([item for pred, item in a if not pred], [item for pred, item in b if pred])
a00e28149254e9ccede3392397fae9c5ad87cede
215,672
import copy def badmatch(match, badfn): """Make a copy of the given matcher, replacing its bad method with the given one. """ m = copy.copy(match) m.bad = badfn return m
f9937a4076ede88b25735a0b095e63d7082da620
75,889
def escape_attribute(value, encoding): """Escape an attribute value using the given encoding.""" if "&" in value: value = value.replace("&", "&amp;") if "<" in value: value = value.replace("<", "&lt;") if '"' in value: value = value.replace('"', "&quot;") return value.encode(encoding, "xmlcharrefreplace")
2a3ff495a5082e130b8a59af1bff82a4a4ca6430
628,768
from typing import List import shlex def _clean_command_arguments(*, args: str) -> List[str]: """Clean args from input for execution.""" return [shlex.quote(i) for i in shlex.split(args)]
61f8cff69e2d7a6df0de6538cec48160f53f7576
422,439
import torch def recoLossGaussian(predicted_x, x, gaussian_noise_std, data_std): """ Compute reconstruction loss for a Gaussian noise model. This is essentially the MSE loss with a factor depending on the standard deviation. Parameters ---------- predicted_x: Tensor Predicted signal by DivNoising decoder. x: Tensor Noisy observation image. gaussian_noise_std: float Standard deviation of Gaussian noise. data_std: float Standard deviation of training and validation data combined (used for normailzation). """ reconstruction_error = torch.mean((predicted_x - x)**2) / (2.0 * (gaussian_noise_std / data_std)**2) return reconstruction_error
0ce87fb200ccd601356944199e9df41a857d30ed
147,663
def prod(lst): """Computes the product of a list of numbers.""" p = 1.0 for i in lst: p *= i return p
58e89b14dde96e52d9b8e445fd8cf912edc7c440
362,477
def _threat_intel_handler(options, config): """Configure Threat Intel from command line Args: options (argparse.Namespace): The parsed args passed from the CLI config (CLIConfig): Loaded StreamAlert config Returns: bool: False if errors occurred, True otherwise """ config.add_threat_intel(vars(options)) return True
2e2bec4a87271bd7f79c9d1fdc5488d39334a2f0
512,623
def square(var_x): # 在文档字符串中添加doctest测试的内容:此函数在命令行下成功运行的过程 """ Squares a number and returns the results. >>> square(2) 4 >>> square(3) 9 """ return var_x * var_x
badd41ba524aafdcd602c7596696f804753a95c4
141,225
import pickle def dumps_content(content): """ pickle 序列化响应对象 :param content: 响应对象 :return: 序列化内容 """ return pickle.dumps(content)
f88159b9d016a6e39744e7af09a76705c9f4e76f
10,125
def prompt_choice(length, select_action, per_page): """ Prompt the user for a choice of entry, to continue or to quit. An invalid choice will repeat the prompt. @param length: the largest choosable value @param select_action: description of what choosing an entry will result in. @param per_page: number of results to offer next. Set to 0 to hide "next" option. """ prompt = 'What do you want to do? [{0}] to {1}, {2}[Q]uit: '.format( '1' if length == 1 else '1–{length}', select_action, '[N]ext {per_page}, ' if per_page else '') while True: choice = input(prompt.format(length=length, per_page=per_page)) try: int_choice = int(choice) except ValueError: int_choice = None if choice.lower() == 'n' and per_page: return None elif choice.lower() == 'q': exit(0) elif int_choice and (1 <= int_choice <= length): return int_choice else: print('Invalid choice. Try again!')
4b957479d96e5b8c642db4e888faf92c8c9cf945
10,570
def train_step(model, features, targets, optimizer, loss_function): """Computes an optimizer step and updates NN weights. Parameters ---------- model : NeuralNetwork instance features : torch.Tensor Input features. targets : torch.Tensor Targets to compare with in loss function. optimizer : torch.optim optimizer Optimizer to compute the step. loss_function : torch.nn loss function Loss function to compute loss. Returns ------- loss : torch.Tensor The computed loss value. output : torch.Tensor The compute NN output. """ model.zero_grad() output = model(features) loss = loss_function(output, targets) loss.backward() optimizer.step() return loss, output
e15f1cba2212d52d41e32e464d7af62695e59a4f
229,526
from typing import Tuple from typing import List def get_mpcs(model, mpc_id: int, consider_mpcadd: bool=True, stop_on_failure: bool=True) -> Tuple[List[int], List[str]]: """ Gets the MPCs in a semi-usable form. Parameters ---------- mpc_id : int the desired MPC ID stop_on_failure : bool; default=True errors if parsing something new Returns ------- nids : List[int] the constrained nodes comps : List[str] the components that are constrained on each node Considers: - MPC - MPCADD """ mpcs = model.get_reduced_mpcs( mpc_id, consider_mpcadd=consider_mpcadd, stop_on_failure=stop_on_failure) nids = [] comps = [] for mpc in mpcs: if mpc.type == 'MPC': for nid, comp, unused_coefficient in zip(mpc.nodes, mpc.components, mpc.coefficients): nids.append(nid) comps.append(comp) else: if stop_on_failure: model.log.error('not considering:\n%s' % str(mpc)) raise NotImplementedError(mpc) model.log.warning('not considering:\n%s' % str(mpc)) return nids, comps
0e9ba03352c6f48a8cdfc37e12e270d3890401f3
152,721
import re def _get_custom_metric_name(name): """Make a metric suitable for sending to Cloud Monitoring's API. Metric names must not exceed 100 characters. For now we limit to alphanumeric plus dot and underscore. Invalid characters are converted to underscores. """ # Don't guess at automatic truncation. Let the caller decide. prefix = 'custom.googleapis.com/' maxlen = 100 - len(prefix) if len(name) > maxlen: raise ValueError('Metric name too long: %d (limit %d): %s' % (len(name), maxlen, name)) return ('%s%s' % (prefix, re.sub(r'[^\w_.]', '_', name)))
abf927893c5393a735eb6d90a2cc87fcbcfa8e36
402,127
from datetime import datetime def calc_delta_days(d1, d2): """Calculate the day difference between datetime objects.""" if isinstance(d1, datetime) and isinstance(d2, datetime): return (d2 - d1).days else: raise TypeError("d1 and d2 must be datetime.datetime objects")
b4ca090eaa500ecd8237903de4bf57a1bdf89b66
482,698
def extract_sample_name_from_sam_reader(sam_reader): """Returns the sample name as derived from the BAM file of reads. Args: sam_reader: Already opened sam_reader to use to extract the sample names from. This sam_reader will not be closed after this function returns. Returns: The sample ID annotated in the read group. Raises: ValueError: There is not exactly one unique sample name in the SAM/BAM. """ samples = { rg.sample_id for rg in sam_reader.header.read_groups if rg.sample_id } if not samples: raise ValueError( 'No non-empty sample name found in the input reads. Please provide the ' 'name of the sample with the --sample_name argument.') elif len(samples) > 1: raise ValueError( 'Multiple samples ({}) were found in the input reads. DeepVariant can ' 'only call variants from a BAM file containing a single sample.'.format( ', '.join(sorted(samples)))) return next(iter(samples))
f0be6306f8a107e874baec36b94b74ae9a5e0a1c
79,863
def column_spec(name, func, width, padding_right=5, padding_left=5, align='right', vertical_align='middle'): """ Returns a function html_table_cell(item, header=False) that generates HTML for table cells <td> for header == False and <th> for header == True according to the specification defined by the input arguments, see below for more detail. :param name: name of the column, this will be the string displayed in a header cell, in case header == True :param func: callable. The value returned by func(item) will be displayed in a table cell, in case header == False :param width: width of the column in pixels :param padding_right: right padding, in pixels of the table cell; default is 5 pixels :param padding_left: left padding, in pixels of the table cell; default is 5 pixels :param align: alignment of the table cell; default is 'right' :return: function """ def html_table_cell(item, header=False): if header: return '<th align={0} vertical-align={5} style="spacing:0;padding-left:{1}px;padding-right:{2}px;" width={3}>{4}</td>'.\ format(align, padding_left, padding_right, width, name, vertical_align) else: return '<td align={0} vertical-align={4} style="spacing:0;padding-left:{1}px;padding-right:{2}px;">{3}</td>'.\ format(align, padding_left, padding_right, func(item), vertical_align) return html_table_cell
6c1e7d73158e9c073e8bdd1866baf03cc80f6acf
429,089
def clean_query(this_object): """clean_query: remove `_version_` key""" this_object.pop('_version_', None) return this_object
db7129343a602c02e6e39b46c8cf04aee2be16dd
229,057
import requests def get_file_size(url, params, timeout=10): """Get file size from a given URL in bytes. Args: url: str. URL string. timeout: int, optional. Timeout in seconds. Returns: int. File size in bytes. #### Examples ```python get_file_size(url) ## 178904 ``` """ try: response = requests.get(url, params={}, stream=True) except (requests.exceptions.HTTPError) as e: print(e) return 0 try: file_size = int(response.headers["Content-Length"]) except (IndexError, KeyError, TypeError): return 0 return file_size
642e733a1385423f0f8a894e8e3bfb96ea15dda4
90,630
def clean_o365_license_list(df): """ This function takes in an Office 365 license list (as a DataFrame) and cleans various aspects and then returns the cleaned list. Parameters ---------- df : pandas DataFrame Returns ------- df : pandas DataFrame """ df['User principal name'] = df['User principal name'].str.lower().str.strip() return df
9774eb8a4055e30f63322619d3efe96d1d8095e1
559,071
import math def vector_of_angle(angle): """ Unit vector of an angle in degrees. """ return [[0.0, 0.0], [math.sin(math.radians(angle)), math.cos(math.radians(angle))]]
3ac8b4b4a04dc40cf533588a9bf17cb2b0220588
583,672
def _has_repeated_entity(tokens, token_strings, vocab_size, comma_id): """ Returns whether the same entity token is repeated back to back or separated by a comma. E.g. 'Obama Obama' or 'India, India'. """ for i in range(len(tokens) - 2): if tokens[i] < vocab_size: continue if token_strings[i] == token_strings[i + 1]: return True if token_strings[i] == token_strings[i + 2] and tokens[i + 1] == comma_id: return True if tokens[-2] >= vocab_size and token_strings[-2] == token_strings[-1]: return True return False
bb6f95cc9b68c50fb129cb0478b2733d702ea113
326,488
def _valid_source_node(node: str) -> bool: """Check if it is valid source node in BEL. :param node: string representing the node :return: boolean checking whether the node is a valid target in BEL """ # Check that it is an abundance if not node.startswith('a'): return False # check that the namespace is CHEBI and PUBMED if 'CHEBI' in node or 'PUBCHEM' in node: return True return False
d8f0e341c0f1ea4fffeea5193054cb9e9eec4b28
586,605
def roundodd(num): """ Round the given number to the nearest odd number. """ rounded = round(num) if rounded % 2 != 0: return rounded else: if rounded > num: return rounded - 1 else: return rounded + 1
b2c6a1205069fd4e7323a5e62814bd31ae0b4123
587,581
import json def get_json(json_path): """ Gets the JSON data. :param json_path: Path to JSON file. :return: JSON. """ with open(json_path, 'r') as json_file: data = json.load(json_file) return data
97ac2ec1010755c2222acb002409256af0e88980
526,101
def capitalize(text): """Capitalises the specified text: first letter upper case, all subsequent letters lower case.""" if not text: return '' return text[0].upper() + text[1:].lower()
25d1a0e1ad7211cefa6938ed3bf5a9e0386b704b
202,689
from bs4 import BeautifulSoup def scrape_links(domain_name, html): """Scrape all links from the html document Positional Arguments: domain_name (str): the domain name of the website you're scraping html (str): standard html document Return: list: all scraped links """ soup = BeautifulSoup(str(html), 'html.parser') link_list = [] for link in soup.find_all('a'): link = link.get('href') # If link only includes a path to a page on the website (internal link), # add the domain name here. if domain_name not in link: link = f'{domain_name}{link}' link_list.append(link) return link_list
8795430de17d7f02123a302af1c43ceee35b18a0
263,943
from typing import Dict from typing import Any from typing import List def handle_ruling_rows( card_data: Dict[str, Any], card_uuid: str ) -> List[Dict[str, Any]]: """ This method will take the card data and convert it, preparing for SQLite insertion :param card_data: Data to process :param card_uuid: UUID to be used as a key :return: List of dicts, ready for insertion """ rulings = [] for rule in card_data["rulings"]: rulings.append( { "uuid": card_uuid, "date": rule.get("date", ""), "text": rule.get("text", ""), } ) return rulings
d8d020caa223bb6f9be9f72f4711f72752601bb7
614,778
def create_firewall(context): """Creates a VPC firewall config. The VPC firewall config depends on the VPC network having been completely instantiated, so it includes a dependsOn reference to the list of resources generated by the network sub-template. Args: context: the DM context object. Returns: A resource instantiating the firewall.py sub-template. """ return [{ 'type': 'templates/firewall.py', 'name': 'fc-firewall', 'properties': { 'projectId': '$(ref.fc-project.projectId)', 'network': '$(ref.fc-network.selfLink)', 'dependsOn': '$(ref.fc-network.resourceNames)', 'rules': [ { 'name': 'allow-internal', 'description': 'Allow internal traffic on the network.', 'allowed': [{ 'IPProtocol': 'icmp', }, { 'IPProtocol': 'tcp', 'ports': ['0-65535'], }, { 'IPProtocol': 'udp', 'ports': ['0-65535'], }], 'direction': 'INGRESS', 'sourceRanges': ['10.128.0.0/9'], 'priority': 65534, }, { 'name': 'leonardo-ssl', 'description': 'Allow SSL traffic from Leonardo-managed VMs.', 'allowed': [{ 'IPProtocol': 'tcp', 'ports': ['443'], }], 'direction': 'INGRESS', 'sourceRanges': ['0.0.0.0/0'], 'targetTags': ['leonardo'], }, ], }, }]
b4d55379437c9de0dfbf3c3dd0c65c1b3aabedfb
611,638
def plot_number_of_structures_per_kinase(structures, top_n_kinases=30): """ Plot the number of structures per kinase (for the top N kinases with the most structures). Parameters ---------- structures : pandas.DataFrame Structures DataFrame from opencadd.databases.klifs module. top_n_kinases : int Plot only the top N kinases with the most structures. Returns ------- matplotlib.pyplot.axis Plot axis. """ plot_height = top_n_kinases / 5 n_structures_per_kinase = structures.groupby("kinase.klifs_name").size() ax = ( n_structures_per_kinase.sort_values(ascending=False) .head(top_n_kinases) .sort_values() .plot( kind="barh", figsize=(4, plot_height), title=f"Number of structures per kinase (top {top_n_kinases} kinases)", xlabel="KLIFS kinase name", ) ) return ax
0d674ce68ae1bf0e7690faa22a1907fac3c925d1
235,547
def string_dict(d, offset=30, desc='DICTIONARY'): """ transform dictionary to a formatted string :param dict d: :param int offset: length between name and value :param str desc: dictionary title :return str: >>> string_dict({'abc': 123}) #doctest: +NORMALIZE_WHITESPACE \'DICTIONARY: \\n"abc": 123\' """ s = desc + ': \n' tmp_name = '{:' + str(offset) + 's} {}' rows = [tmp_name.format('"{}":'.format(n), d[n]) for n in sorted(d)] s += '\n'.join(rows) return str(s)
9a60de18325c17082e0c0e985854442f13c83759
274,412
def strong(text: str) -> str: """ Return the *text* surrounded by strong HTML tags. >>> strong("foo") '<b>foo</b>' """ return f"<b>{text}</b>"
fa63f2b38cbb8841cd495e47a0085115ad3a75b9
87,704
def augmentToBeUnique(listOfItems): """Returns a list of [(x,index)] for each 'x' in listOfItems, where index is the number of times we've seen 'x' before. """ counts = {} output = [] for x in listOfItems: counts[x] = counts.setdefault(x, 0) + 1 output.append((x, counts[x]-1)) return output
eb5208bd89444f0b0c618bef1fb6ae7a584f467c
559,145
def smiles_to_folder_name(smiles): """ Encodes the SMILES containing special characters as URL encoding. Parameters ---------- smiles : str SMILES string describing a compound. Returns ------- str : The standard URL encoding of the SMILES if it contains special characters. Notes ----- : -> %3A \\ -> %5C (here backslash) / -> %2F * -> %2A Taken from: https://www.degraeve.com/reference/urlencoding.php """ url_encoded_smiles = ( smiles.replace(":", "%3A") .replace("\\", "%5C") .replace("/", "%2F") .replace("*", "%2A") ) return url_encoded_smiles
ae2c45cf7388094dfaa63f62ff33dcfa12da6f43
473,679
def determine_adjusted(adjusted): """Determines weather split adjusted closing price should be used.""" if adjusted == False: return 'close' elif adjusted == True: return 'adjClose'
c8c0ccc0284045d504595901506eb659f93b1cfb
169,643
def markdown_table(body, header=None): """ Generate a MultiMarkdown text table. :param body: The body as a list-of-lists :param header: The header to print """ s = "" def cellstr(cell): if type(cell) == float: return ("%.2f" % cell) if type(cell) in (list, tuple): return ', '.join(cellstr(e) for e in cell) return str(cell) def makerow(row): rowstrs = [cellstr(cell).rjust(maxlen[i]) for i,cell in enumerate(row)] return '| ' + ' | '.join(rowstrs) + ' |\n' if header: body = [header] + body maxlen = [max(len(cellstr(cell)) for cell in col) for col in zip(*body)] if header: s += makerow(body[0]) s += '|'+'|'.join('-'*(m+2) for m in maxlen)+'|\n' body = body[1:] for row in body: s += makerow(row) return s
53139c42a994ccc70c445e89e287a9f2a589b9a8
369,054
def get_lr(optimizer): """get learning rate from optimizer Args: optimizer (torch.optim.Optimizer): the optimizer Returns: float: the learning rate """ for param_group in optimizer.param_groups: return param_group['lr']
fc8293cc29c2aff01ca98e568515b6943e93ea50
11,358
def tower(n): """computes 2^(2^(2^...)) with n twos, using recursion""" if(n==0): return 1 return 2**tower(n-1)
30554f29eee5498d06910d580afaaa606894a83a
624,671
def start_target_to_space(start, target, length, width): """ Create a state space for RRT* search given a start, target and length / width buffer. Args: start: tuple of form (x, y) target: tuple of form (x, y), (range_x, range_y) length: float specifying length to buffer width: float specifying width to buffer Returns: state space tuple of form (origin_x, origin_y), (range_x, range_y) """ origin = (min(start[0], target[0][0] + length / 2) - length, min(start[1], target[0][1] + width / 2) - width) bounds = (max(start[0], target[0][0] + length / 2) - origin[0] + width, max(start[1], target[0][1] + width / 2) - origin[1] + width) return origin, bounds
e197c998ca8d401ae49cad9e96b8d074a8f28774
508,104
def predcedence(operator): """Return the predcedence of an operator.""" if operator in '+-': return 0 elif operator in '*/': return 1
6e67d4fd3a36e6c3fdd207d31edc80ebbe905fd3
429,764
def get_by_name(yaml, ifname): """Returns the interface or sub-interface by a given name, or None,None if it does not exist""" if "." in ifname: try: phy_ifname, subid = ifname.split(".") subid = int(subid) iface = yaml["interfaces"][phy_ifname]["sub-interfaces"][subid] return ifname, iface except ValueError: return None, None except KeyError: return None, None try: iface = yaml["interfaces"][ifname] return ifname, iface except KeyError: pass return None, None
1437d233ebdad7ee949b16e31df8497364f213e1
401,336
def sum_of_squared_digits(number): """ Returns the sum of squares of the digits of a number """ sum = 0 while number > 0: digit = number%10 number = number//10 sum += digit**2 return sum
014f336fd8f83f3e3bba0a92b8106771f31d9365
133,462
import random def flip_coin(p): """Flip biased coint p(True) = p.""" r = random.random() return r < p
21a1c1e186c9aad030fcb1706853dae6af1668e4
219,882
def r(b, p, alpha): """ Function to calculate the r coeficient of the Massman frequency correction. """ r = ((b ** alpha) / (b ** alpha + 1)) * \ ((b ** alpha) / (b ** alpha + p ** alpha)) * \ (1 / (p ** alpha + 1)) return r
ddffac7b5af40147d6653501a72fd7c5c501a2fa
692,435
def create_rules(lines): """ Given the list of line rules, create the rules dictionary. """ rules = dict() for line in lines: sline = line.split() rules[sline[0]] = sline[-1] return rules
3ae3555f08fa4aa2cb147172ad4d584025c35133
100,215
def get_int_icode(res_seq): """ Return tuple (int, icode) with integer residue sequence number and single char icode from PDB residue sequence string such as '60A' or '61' etc. Parameters: res_seq - PDB resisue sequence number string, with or without icode Return value: tuple (int, icode) where int is integer part of res_seq, and icode is char insertino code or None """ if not res_seq[-1].isdigit(): int1 = int(res_seq[0:len(res_seq)-1]) icode = res_seq[-1] else: int1 = int(res_seq) icode = None return (int1, icode)
ec7380c85dcced668b2e359ec9a11b24246a9dcc
359,795
def _have_common_proto(origin_meta, destination_meta): """ Takes two VersionMeta objects, in order of test from start version to next version. Returns a boolean indicating if the given VersionMetas have a common protocol version. """ return origin_meta.max_proto_v >= destination_meta.min_proto_v
6bf9f3fe0752319bb65cebc7e9eb5a8888de1819
320,002
import itertools def interleave_lists(a, b): """ Interleaves the values of two lists. The length is equal to the shorter of the two lists x 2 :param a: first list e.g., ['a', 'b', 'c', 'd', 'e'] :param b: second list e.g., [1, 2, 3] :return: interleaved list ['a', 1, 'b', 2, 'c', 3] """ return list(itertools.chain(*zip(a, b)))
45a96c07ce748d7e0caef62ab87e6ead6dd830c5
236,502
def _generate_overlaps(sequence, order): """ This function takes an input sequence & generates overlapping subsequences of length order + 1, returned as a tuple. Has no dependencies & is called by the wrapper compute() Parameters ---------- sequence : string String containing nucleotide sequence. order : int Order of Markov Transition Probability Matrix for computing overlaps Returns ------- tuple Contains all overlapping sub-sequences (of length order + 1) for given order. Total number of sub-sequences is len(sequence) - (order + 1) """ # Initialize aggregator aggregator = [] # Increment order by 1 as the Markov model includes the current state, such # that the length of sequence corresponding to a state is order + 1 order += 1 # Iteratively store sequences shifted to the left by 1 step for idx in range(order): aggregator.append(sequence[idx : idx - order]) # Join the shifted sequences through element-wise concatenation & return return tuple(map("".join, zip(*aggregator)))
134c130c6ff5173cc914b556899a2f04d1afd2e2
559,518
def _add_indent(string, indent): """Add indent of ``indent`` spaces to ``string.split("\n")[1:]`` Useful for formatting in strings to already indented blocks """ lines = string.split("\n") first, lines = lines[0], lines[1:] lines = ["{indent}{s}".format(indent=" " * indent, s=s) for s in lines] lines = [first] + lines return "\n".join(lines)
cf7c90702a2664cc2088740758675911ed60a37c
322,552
def all_taxa_have_attribute(phylogeny, attribute): """Do all taxa in the given phylogeny have the given attribute? Args: phylogeny (networkx.DiGraph): graph object that describes a phylogeny attribute (str): a possible attribute/descriptor for a taxa (node) in phylogeny Returns: True if all taxa (nodes) in the phylogeny have the given attribute and False otherwise. """ for node in phylogeny.nodes: if not (attribute in phylogeny.nodes[node]): return False return True
14ebbe774caa580911ef811228b26d7af5cdf9b7
335,986
def FivePointsDiff(fx, x, h=0.001): """ FivePointsDiff(@fx, x, h); Use five points difference to approximatee the derivative of function fx in points x, and with step length h The function fx must be defined as a function handle with input parameter x and the derivative as output parameter Parameters ---------- fx : function A function defined as fx(x) x : float, list, numpy.ndarray The point(s) of function fx to compute the derivatives h : float, optional The step size Returns ------- float, list, numpy.ndarray: The numerical derivatives of fx at x with the same size as x and the type if from fx() """ return (-fx(x+2*h) + 8*fx(x+h) - 8*fx(x-h) + fx(x-2*h)) / (12.0*h)
3b2ff6eca789e5cdf8c1ac2eba556b4994ca8e54
442,871
def _get_num_ve_sve_and_max_num_cells(cell_fracs): """ Calculate the num_ve, num_sve and max_num_cells Parameters ---------- cell_fracs : structured array, optional A sorted, one dimensional array, each entry containing the following fields: :idx: int The volume element index. :cell: int The geometry cell number. :vol_frac: float The volume fraction of the cell withing the mesh ve. :rel_error: float The relative error associated with the volume fraction. Returns ------- num_ve : int Number of the total voxels num_sve : int Number of the total subvoxels, eqaul to or greater than num_ve max_num_cells : int Max number of cells (subvoxels) in a voxel """ num_sve = len(cell_fracs) num_ve = len(set(cell_fracs["idx"])) max_num_cells = -1 for i in range(num_sve): max_num_cells = max(max_num_cells, len(cell_fracs[cell_fracs["idx"] == i])) return num_ve, num_sve, max_num_cells
c0d154898bbfeafd66d89a2741dda8c2aa885a9a
706,040
def getlenDict(data, keys=None): """Get len of a dict of lists""" l = 0 if keys == None: keys = data.keys() for i in keys: l += len(data[i]) return l
369b8a32b59cbbfc60df512279c8758224a08fab
612,073
def get_target_ns(xml_tree): """Extract the target namespace for the XML doc. Returns: str: Extracted from the `targetNamespace` attribute of the root element. If the root element does not have a `targetNamespace` attribute, return an empty string, "". Examples: <xs:schema targetNamespace="http://www.w3.org/XML/1998/namespace" xmlns:xs="http://www.w3.org/2001/XMLSchema"> -> http://www.w3.org/XML/1998/namespace """ ns_list = xml_tree.xpath("/*/@targetNamespace") if len(ns_list): return ns_list[0] return ""
f6bc1899f9e2590528bb0fc58c91b1938d4cb63d
478,074
def zone_bc_type_english(raw_table, base_index): """ Convert zone b/c type to English """ value = raw_table[base_index] if value == 0: return "NA" if value == 1: return "Direct" if value == 2: return "3WV" if value == 3: return "NA" if value == 4: return "swiming pool" return "Unknown"
d6fef02dd92ec1604b2bb892e6ad6dc00d5f889f
659,290
def edit_header(my_vcf): """ Add INFO for new fields to vcf """ header = my_vcf.header.copy() header.add_line(('##INFO=<ID=TruScore,Number=1,Type=Integer,' 'Description="Truvari score for similarity of match">')) header.add_line(('##INFO=<ID=PctSeqSimilarity,Number=1,Type=Float,' 'Description="Pct sequence similarity between this variant and its closest match">')) header.add_line(('##INFO=<ID=PctSizeSimilarity,Number=1,Type=Float,' 'Description="Pct size similarity between this variant and its closest match">')) header.add_line(('##INFO=<ID=PctRecOverlap,Number=1,Type=Float,' 'Description="Percent reciprocal overlap percent of the two calls\' coordinates">')) header.add_line(('##INFO=<ID=StartDistance,Number=1,Type=Integer,' 'Description="Distance of the base call\'s end from comparison call\'s start">')) header.add_line(('##INFO=<ID=EndDistance,Number=1,Type=Integer,' 'Description="Distance of the base call\'s end from comparison call\'s end">')) header.add_line(('##INFO=<ID=SizeDiff,Number=1,Type=Float,' 'Description="Difference in size of base and comp calls">')) header.add_line(('##INFO=<ID=GTMatch,Number=0,Type=Flag,' 'Description="Base/Comparison Genotypes match">')) header.add_line(('##INFO=<ID=MatchId,Number=1,Type=String,' 'Description="Id to help tie base/comp calls together {chunkid}.{baseid}.{compid}">')) header.add_line(('##INFO=<ID=Multi,Number=0,Type=Flag,' 'Description="Call is false due to non-multimatching">')) return header
bde0247125c2bc20f25ec21ae8117d5c4887c358
499,639
import re def make_role_node_dict(target_dict, nodes): """Given the target dict containing targets grouped by nodes and the list of nodes, this function returns a dictionary containing the list of nodes grouped by target and by role: { 'role1': { 'target1a': ['node1aa', 'node1ab'], 'target1b': ['node1ba'] }, 'role2': { 'target2a': ['node2aa'] } } """ result_dict = {} for role in target_dict.keys(): result_dict[role] = {} for target in target_dict[role]: result_dict[role][target] = [] if target[:2] == 'E@': # target is a regular expression target_re = re.compile(target[2:]) for node in nodes: if target_re.match(node): result_dict[role][target].append(node) else: # assume target is hostname result_dict[role][target].append(target) return result_dict
fb25b55192670391d3f1a120fe49b815e8cfbee6
172,947
def elementtree_to_dict(element): """Convert an xml ElementTree to a dictionary.""" d = {} if hasattr(element, "text") and element.text is not None: d["text"] = element.text d.update(list(element.items())) # element's attributes for c in list(element): # element's children if c.tag not in d: d[c.tag] = elementtree_to_dict(c) # an element with the same tag was already in the dict else: # if it's not a list already, convert it to a list and append if not isinstance(d[c.tag], list): d[c.tag] = [d[c.tag], elementtree_to_dict(c)] # append to the list else: d[c.tag].append(elementtree_to_dict(c)) return d
ba89b27ae5f3b86e21a33f33a4eb239f0b24ac57
527,117
def get_cycles(motif): """ Generates cyclical variations of a motif Parameters ---------- motif : str, nucleotide motif Returns ------- LIST, List of cyclical variations of the motif sorted in alphabetical order. """ cycles = set() for i in range(len(motif)): cycles.add(motif[i:] + motif[:i]) cycles = sorted(list(cycles)) return cycles
d34fcb1e9f2608fcf519755f2105bb5926393aeb
480,049
import requests def get_sha_url_and_ref_from_prid(repo, prid): """ given a GIT repo and a pull request ID, return the SHA, clone_url, and ref for that pull request """ response = requests.get( "https://api.github.com/repos/{}/pulls/{}".format(repo, prid) ) if response.status_code == 200: sha = response.json()["head"]["sha"] url = response.json()["head"]["repo"]["clone_url"] ref = response.json()["head"]["ref"] return (sha, url, ref) elif response.status_code == 405: raise Exception("ERROR : prid {} not found in repo {}".format(prid, repo)) else: raise Exception( "unexpected result looking for prid {} in repo {} status = {} response = {}".format( prid, repo, response.status_code, response.json() ) )
aba031aa86c1d8bbf1d75ba27813811dd4ac3cef
504,700
def query_transform(request, **kwargs): """Taken from http://stackoverflow.com/a/24658162/2844093 return a querystring with updated parameter. Useful, for example in pagination to change page number without replacing the whole query parameters. Usage: .. code-block:: html+django <a href="/path?{% query_transform request a=5 b=6 %}"> """ updated = request.GET.copy() for k, v in kwargs.items(): updated[k] = v return updated.urlencode()
9ec06a5c2414a26019d51e9b4229d9fddc1b6b5f
302,475
def get_csr_position(index, shape, crow_indices, col_indices): """Return the position of index in CSR indices representation. If index is not in indices, return None. """ # binary search row, col = index left = crow_indices[row] right = crow_indices[row+1] - 1 while left <= right: i = (left + right) // 2 d = col_indices[i] - col if d == 0: return i if d < 0: left = i + 1 elif d > 0: right = i - 1 # index is not in indices return
baf115707a23963a253470ebc7a63cd49cd87278
76,805
def get_lna_num(name): """Return the number of an LNA, in the range 0…5 Valid values for the parameter `name` can be: - The official name, e.g., HA1 - The UniMIB convention, e.g., H0 - The JPL convention, e.g., Q1 - An integer number, which will be returned identically """ if type(name) is int or name in ["4A", "5A"]: # Assume that the index refers to the proper firmware register return name elif (len(name) == 3) and (name[0:2] in ["HA", "HB"]): # Official names d = {"HA1": 0, "HA2": 1, "HA3": 2, "HB1": 5, "HB2": 4, "HB3": 3} return d[name] elif name[0] == "H": # UniMiB d = { "H0": 0, "H1": 1, "H2": 2, "H3": 3, "H4": 4, "H4A": "4A", "H5": 5, "H5A": "5A", } return d[name] elif (len(name) == 2) and (name[0] == "Q"): # JPL d = {"Q1": 0, "Q2": 1, "Q3": 2, "Q4": 3, "Q5": 4, "Q6": 5} return d[name] else: raise ValueError(f"Invalid amplifier name '{name}'")
ea5b29f25efbee2720d1ac62052e73f01924381d
383,456
def match_error_event(event, *_args): """ Matches error events. Returns True or False. """ return event['tag'] == 'error'
e3df2cbcbf3a8321a27fafad7a49881ec20502da
212,581
def _isoformat(date): """Format a date or return None if no date exists""" return date.isoformat() if date else None
566e26fed7818874322f820e684c68940c726376
63,693