content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
def get_month_as_str_col(df, date_col): """Generate a pandas series of the month as a string in YYYY-MM format from the date column. Parameters ---------- df : pandas df Pandas dataframe date_col : str Name of the column in the dataframe containing the timestamp Returns ---...
74b017ee3b5c56d8c2ae8be7d67c665603aabef1
669,330
def calc_IoU(bbox1, bbox2): """ Calculate intersection over union for two boxes. Args: bbox1 (array_like[int]): Endpoints of the first bounding box in the next format: [ymin, xmin, ymax, xmax]. bbox2 (array_like[int]): Endpoints of the second bounding box in the next...
96aaebde2b7572de5b58002a8694b8708598b989
669,331
def is_(self, state): """Check if machine is in given state.""" translator = self._meta['translator'] state = translator.translate(state) return self.actual_state == state
0a0ad30f4c09a4a1d7d0434220a0213b7fe4206d
669,332
def remove_quotation_marks(source_string): """ :param source_string: String from which quotation marks will be removed (but only the outermost). :return: String without the outermost quotation marks and the outermost white characters. """ first = source_string.find('"') second = source_string[fi...
13157e80cb701b915e0ccab1e38f9099de7f90bb
669,336
def write_file(filename="", text=""): """Write a string to a text file""" with open(filename, 'w') as f: c = f.write(text) return c
06dbe59c18a9c1750eb9cc0998b2fe7fbcbfc015
669,339
import re def pick_only_key_sentence(text, keyword): """ If we want to get all sentence with particular keyword. We can use below function. Parameters ---------- text: str Text selected to apply transformation. keyword: str Word to search within the phrase...
46a85d7edf3033e11ea0c4f11a656c7e48069cc3
669,340
def coverageTruncatedToString(coverage) : """Converts the coverage percentage to a formatted string. Returns: coveragePercentageAsString, coverageTruncatedToOneDecimalPlace Keyword arguments: coverage - The coverage percentage. """ # Truncate the 2nd decimal place, rather than rounding # to...
be9bbf940985d93d89d00e0c3f307c6d2b199321
669,345
def get_nodes(dag): """ Returns the names of all nodes found in dag """ nodes = dag.sig.names for node in dag.nodes: if node not in nodes and isinstance(node, str): nodes.append(node) return nodes
1f4bd8d7d007fed038c45cb162cf05a723ab6c52
669,346
def validate_transaction(spend_amounts, tokens_amounts): """ A transaction is considered valid here if the amounts of tokens in the source UTXOs are greater than or equal to the amounts to spend. :param spend_amounts: amounts to spend :param tokens_amounts: existing amounts to spend from :retur...
5a1de72aefe6d5d401864defc46c225afc218dba
669,347
def poly(X, Y, degree): """ Polynomial kernel implementation. X, Y: The matrices between which pairwise distances are computed. degree: The degree of the polynomial """ return (X @ Y.T + 1)**degree
5bc61c3c8b0d0f6aab6321dcb8e99db8fd8dade1
669,352
def k2f(k: float, r: int = 2) -> float: """Kelvin to Fahrenheit.""" return round(((k - 273.15) * (9 / 5)) + 32, r)
39de3421a9977f0ec0d66ca939efffb4b8809907
669,354
from pathlib import Path def resolve_doc_file_path(module_name: str, out_dir: Path, file_extension: str) -> Path: """Return the absolute path to a rendered doc file Args: module_name (str): the module name, i.e. "networkx.drawing.layout" out_dir (Path): the output directory, i.e. Path("/build...
703b6c91725380291fd53cae578ddd01c31eac3a
669,359
import six def to_text(s, encoding="utf-8"): """ Converts the bytes to a text type, if not already. :s: the bytes to convert to text :returns: `unicode` on Python2 and `str` on Python3. """ if isinstance(s, six.text_type): return s else: return six.binary_type(s).decode(en...
c06273f73a6b7dde03196e1d0355fa87528ad959
669,362
def find_between( s, first, last ): """Find a string between two characters.""" try: start = s.index(first) + len(first) end = s.index(last, start) return s[start:end] except ValueError: return ""
737941dd48a31c048ce3fe0583e13c893febb5ed
669,364
def get_name_value(line): """Get benchmark name and result from a text line""" name = line.split()[1] value = int(line.split()[4]) return name,value
7bc1a29a761c25963144fd1b94ca7e7b81f288b8
669,366
def is_sunday(date): """Is the specified date (a datetime.date object) a Sunday?""" return date.weekday() == 6
167ec36a372cf64646b4dabae46867515f71337d
669,369
def query_registry(model, registry): """Performs a lookup on a content type registry. Args: model: a Django model class registry: a python dictionary like ``` { "my_app_label": True, "my_other_model": { "my_model": True,...
7c410c5baa8d20792ee7f49423da000fee34d001
669,370
import hashlib def get_md5(payload): """ Generate md5 hash of a payload :param payload: The payload to be hashed. :returns: md5 hash :rtype: str """ return hashlib.md5(payload).hexdigest()
9ec3ba40f2046340391ba355d9d1cc6398002c4d
669,377
def scores(L): """Get the scores (position * alphabet score) for all words in list.""" scores = [] for key, val in enumerate(L): scores.append(val * (key + 1)) return scores
98327f6ff050b160deff683009750424bf60b35c
669,380
def ensure_each_wide_obs_chose_an_available_alternative(obs_id_col, choice_col, availability_vars, wide_data): """ Checks whether or not each ob...
9398d83e188c317d2289d074851a848488a15ea0
669,382
import re def parse_path_info(path_info): """ Parse path info formatted like a/c/f where c and f are optional and a leading / accepted. Return tuple (a, c, f). If invalid path_info a is set to None. If c or f are omitted they are set to None. """ mo = re.match(r'^/?(?P<a>\w+)(/(?P<c>\w+)(...
0cb000b1b57c3e0b100b2f1dbea60dab4d6f04ca
669,385
def do_check(func, files, status): """ Generic do_check helper method Args: func (function): Specific function to call files (list): list of files to run against status (list): list of pre-receive check failures to eventually print to the user Returns: ...
ec642743906a0523a5421237d62b83f0643201e2
669,387
def checkscheme(arglist, arg): """Returns index of arg in arglist or if not found returns -1. """ return arglist.index(arg) if arg in arglist else -1
1401edebaca7c764c992c6fdf5073795f9cff25d
669,389
def total_number_of_clusters(tree) -> int: """Get the number of leaves in the tree.""" if tree is None: return 1 return sum(total_number_of_clusters(subtree) for subtree in tree.subregions)
0ffffe5dd0a315f76778eed51ba44401994f28ad
669,391
import math def round_to_n(x: float, n_digits: int) -> float: """Round a floating point to n significant digits Args: x (float): Number to round n_digits (int): Number of digits to keep Returns: float: Rounded version of x with n_digits digits """ ...
e7eab22122f741ed6b583fb6e4ce3abb0fa91271
669,393
import time def log_tail(contents=''): """return a string, which can be write to the tail of a log files""" s = '================================================================\n' s += '[time] ' + time.asctime(time.localtime()) + '\n' s += '[program finish succeed!]\n' s += contents s += '=...
f03c68285ea8cf335a7eb8475085501eeb1c1eee
669,398
import socket def __try_op__(op_name, op, retries, *args): """ A helper function to retry an operation that timed out on a socket. After the retries are expired a socket.timeout is raised. Parameters ---------- op_name : str The operations name op : Callable The operation ...
3720f781106138f74a189f0bead4897148b307b5
669,400
import time def delay(ticks: int) -> int: """pause the program for an amount of time Will pause for a given number of nanoseconds. This function will use the processor (rather than sleeping) in order to make the delay more accurate than nygame.time.wait(). Parameters ---------- ticks ...
6b060f82e6fdaa9fd5e233b40b96ece2856ab851
669,404
def fib(n): """This function returns the nth Fibonacci number.""" i = 0 j = 1 n = n - 1 while n >= 0: i, j = j, i + j n = n - 1 return i
4985df3ec7c92081a416c0bedd6d65df482a4b9e
669,405
def name(data): """ Get the assigned name of the entry. """ return data["marker_name"]
55e5d2d4defebf1b391d1f27a03de3fa7d0de331
669,407
import json def dumps_json(value): """ dumps json value to indented string Args: value (dict): raw json data Returns: str: indented json dump string """ return json.dumps(value, indent=2, ensure_ascii=False)
b1c40c3fef82a7c3fde05aaa793c72012e04cd5a
669,408
def fn_example(values): """ function / method with built-in unit test example; this example computes the arithmetic mean of a list of numbers. Args: values: list of integers Returns: integer Examples: >>> print(fn_example([20, 30, 70])) 40.0 """ return sum(values) / len(values)
fc0356a975f25f690ada357f78e0a336b37859c0
669,409
from typing import Iterable from typing import Hashable from typing import List def _unique_order_preserving(iterable: Iterable[Hashable]) -> List[Hashable]: """Remove items from an iterable while preserving the order.""" seen = set() return [i for i in iterable if i not in seen and not seen.add(i)]
f5b3384e2c8812341b246fc05972bc9c1b13f255
669,416
def _tests_in_suite(suite_name, tests): """Check if the suite includes tests. :param suite_name: Name of the suite to be checked. :param tests: Set of tests :type suite_name: str :type tests: pandas.Series :returns: True if the suite includes tests. :rtype: bool """ for key in test...
53d3e1a1cc3e12d698f8a2a5eb4e246ce4e53ea9
669,417
import re def fixFlagsQuoting(text): """Replaces e.g. /DFOO with /D "FOO" and /DFOO=X with /D FOO=X.""" return re.sub(r'\/([DIid]) ([^ \"=]+)([ $])', r'/\1 "\2"\3', re.sub(r'\/([DIid]) ([^ \"=]+)=([^ \"]*)([ $])', r'/\1 \2=\3\4', text))
ab60d5cf539d7a3753e457838989ab3be520d6b3
669,422
from typing import Optional from typing import Dict def create_field_list_query(field_type: Optional[str] = None, field_documentation: bool = True) -> Dict: """Create a FieldListRequest dictionary request. Args: field_type: One of {'All', 'Static', 'RealTime'} field_documentation: Return fiel...
fc1ebcc4f7ba5af77e0dab0adf2719396b25fbac
669,423
def parse_videos(video): """ Parse data from the video JSON structure Parameters ---------- video : JSON object of strings The video search result requested from YouTube API v3 Returns ---------- video_dict : dictionary of strings The dictionary contianing video titl...
b9b2a243f7e1740bc449e7a37a6efa6fe76f7c02
669,424
def create_log_line(log_msg): """ Create a line for the log files from a LogMessage """ # determine log line contents tstamp = round(log_msg.tstamp.timestamp()) direction = "IN" sender = log_msg.sender if log_msg.own: direction = "OUT" sender = "you" msg = log_msg.ms...
3d88c147d14d3cc485cb19f54147c5fcf0df5c1f
669,428
def _filter(regex, expr): """ Build an `filter(<regex>, <expr>)` type query expression. `regex` is a regex matched on the rule names from `expr` `expr` is a query expression of any supported type. """ return "filter('{}', {})".format(regex, expr)
719d47de4670eb6ddc9b8238d5a903a7a89f5649
669,437
def getAuthorAndName(ctx): """ Takes the context variable from the calling function and returns the author object and the author display name, formatted. @param ctx the context passed to the calling function @return author the author object @return authorName the display name of the author "...
ba9c7674b21d42a95df0f01ab6ccbcaca276c777
669,438
def format_percentage(number): """ Formats a number into a percentage string :param number: a number assumed to be between 0 and 1 :return: str """ return '{}%'.format(round(number * 100))
5736b141b316d2de63804ddb248a45d9e4748ba4
669,440
def is_numeric(s): """ It's a useful function for checking if a data is a numeric. This function could identify any kinds of numeric: e.g. '0.1', '10', '-2.', 2.5, etc Parameters ---------- s : int, float or string. The input could be any kind of single value except the scalable ...
9b5bbc267dc5e4dad97df5446743d6c4c7e49a8c
669,442
def acs(concept, paragraph, model, min_length, stop_words=[]): """ :param concept: str, the concept word for the concept :param paragraph: list, a list of the tokens in the paragraph :param model: gensim.models.Word2Vec, model containing word vectors :return: float, the distance between the concept ...
4af462fb970fed1b7e8f42576e5cceac6b912ad6
669,444
import re def get_tab_info(root): """ Returns the prefix, separator, and max index for a set of jQueryUI tabs """ hrefs = [y.attrib['href'] for y in [x.find('a') for x in root.find('ul').findall('li')] ] splits = [r.groups() for r in [re.match('#(.*)([-_...
375f8cfc2b6f3467ae0d958c20daa8978a558fd0
669,445
import json def read_json_file(path): """ Reads and return the data from the json file at the given path. Parameters: path (str): Path to read Returns: dict,list: The read json as dict/list. """ with open(path, 'r', encoding='utf-8') as f: data = json.load(f) re...
e197c67811fe33c71ee92ce3e7d6a1dab0940f75
669,451
def split_with_square_brackets(input_str): """ Split a string using "," as delimiter while maintaining continuity within "[" and "]" Args: input_str: Input string Returns: substrings: List of substrings """ substrings = [] bracket_level = 0 current_substr = [] for ne...
0bdf0849019401f7bd0d702045ee4ad3fc5750c8
669,460
import string def splitNum(name, digits=string.digits): """ Split a string that ends with a number between the 'body' of the string and its numeric suffix. Both parts are returned as strings. :param name: The string to split. :keyword digits: The set of numeric characters. Default...
dd96edc9135623206735771e23c5afc80f4ceaea
669,461
from typing import Tuple def get_nb_tile_from_img(img_shape: Tuple[int, int], tile_size: int) -> int: """ return the number of tile inside an image currently the number of tile are computed without overlaping and by rounding so union of all tiles are smaller than image. Tile are square. Para...
363503a2285107d6f65c48acd26ff66c63af528f
669,462
def get_negation(token): """Get the negation of some token""" sign = True for child in token.children: if child.dep_ == "neg": sign = False break return sign
2f7bda6b753d4345319fd2739f7663c94928e609
669,467
def block_num_to_hex(block_num): """Converts a block number to a hex string. This is used for proper index ordering and lookup. Args: block_num: uint64 Returns: A hex-encoded str """ return "{0:#0{1}x}".format(block_num, 18)
88865256e07fdcebdff440aea964f26707931735
669,470
def forward_differences(f, h, x): """ Forward Finite Differences. Approximating the derivative using the Forward Finite Method. Parameters: f : function to be used h : Step size to be used x : Given point Returns: Approximation """ return (f(x + h) - f(x)) / h
4e94c8ac1f05c86ea78e971b60ed6da0b3e845d4
669,472
from typing import Tuple def bool_(buffer: bytes, offset: int = 0) -> Tuple[bool, int]: """ Unpack bool from Starbound save file. :param buffer: Starbound save file :param offset: position in Starbound save file :return: bool, new offset """ return bool(buffer[offset]), offset + 1
25643ed6a765f562302ca35bcabd0cd23c3d72ac
669,474
def get_job_main_info(job): """ Return a dictionary with the pieces of information that will be presented on the terminal. :param job: A Job object provided by ScrapingHub :return: A dictionary """ info = job.info main_info = { 'id': job.id, 'spider': info.get('spider'), ...
b23679cfe8e4996d120e958929f7663d5662d1cf
669,475
import json def user_io_loop(settings: dict): """ This function is run on the main process as it interacts with the user. It asks for some command and it executes the proper task if the input was recgonized. Parameters ---------- settings : proxy dict shared dictionary with inform...
6fa13628d654ad5493ad552db46323b40abac53a
669,476
def remove_action(actions, name): """ Find all the occurrences of actions with a given name and return them and remove them from the list :param actions: List of actions :param name: str name to find :returns: List of actions matching the given name """ matching = [action for action in ac...
3b8bc0d0081b1bf41c58c3504f2101b42ce1d70f
669,479
from typing import Optional def get_dag_id(this_dag_name: str, parent_dag_name: Optional[str] = None) -> str: """Generates the name for a DAG, accounting for whether it is a SubDAG. Args: this_dag_name: A name for this individual DAG. parent_dag_name: The name of the parent DAG of this DAG...
14ffbbec93e31eed431bcbb4c94c9a82beb3491e
669,481
def get_tagstring(refid, tags): """Creates a string from a reference ID and a sequence of tags, for use in report filenames.""" return "_".join([refid] + [t[0] + "." + (t[1] if t[1] else "None") for t in tags])
8ab5b461482194c2beabb861bd17c0fff91a15fa
669,482
import itertools def all_liouville_subspaces(hilbert_subspace): """ Given a Hilbert subspace, return a comma separated list with all included Liouville subspaces Example ------- >>> all_liouville_subspaces('ge') 'gg,ge,eg,ee' """ return ','.join(''.join(s) for s ...
c366dc36c182ea71bad527a7140eaeea54242071
669,489
def normalize_btwn_0_1(list_obj): """ Takes a list and normalizes the values from 0 (smallest) to 1(largest) """ return (list_obj-min(list_obj))/(max(list_obj)-min(list_obj))
b6b7bd4a7141c3254d46a8df1c92fe03432a63fb
669,492
def get_light_positions(rays_i, img_light_pos): """Extracts light positions given scene IDs. Args: rays_i: [R, 1] float tensor. Per-ray image IDs. img_light_pos: [N, 3] float tensor. Per-image light positions. Returns: rays_light_pos: [R, 3] float tensor. Per-ray light positions. ...
b96327e8104439ed466946a2e890e2e42d5337a0
669,493
def has_sublist(superlist, sublist): """ Does a list contain another list within it? Not very efficient. If 'eq' is given, this will be used to compare items. """ return any( superlist[i : i + len(sublist)] == sublist for i in range(len(superlist) - len(sublist) + 1) )
5af69cdc51fe141522c963b58e2006400bcf0f19
669,497
def MSEevaluation(y, predict): """ Evaluate predictions the mean sqaured error :param y: original values :param predict: predicted values :return: the mean squared error of the predicted values """ n = len(y) # number of...
d90666ef39d6b75895ee3b7757d4fd6fead3a434
669,499
def get_xml_node_value (root, name): """ return the value from an XML node, if it exists """ node = root.find(name) if node: return node.text else: return None
abf6de764889a3c847089372ad99803971b39e3a
669,503
def get_first_arg(args, kwargs, name): """Returns named argument assuming it is in first position. Returns None if not found. Args: args (tuple or list): args from function. kwargs (dict): kwargs from function. name (str): argument name """ try: return kwargs[name] ...
accd9389853ea7bc8821e3cbee093292174ede80
669,505
def simpleVoigt(vsh,vsv): """ seis_model.simpleVoigt(vsh,vsv) voigt average of horizontal and vertical shear wave velocities v = 0.5 * (vsh + vsv) Parameters ----------- vsh horizontal shear wave velocity, array or scalar vsv vertical shear wave velocity, array or scalar ...
0e25c0fc9873e5073687df2fbb87d2a7a9572645
669,506
import functools def noop_if_no_unpatch(f): """ A helper for PatchTestCase test methods that will no-op the test if the __unpatch_func__ attribute is None """ @functools.wraps(f) def wrapper(self, *args, **kwargs): if getattr(self, '__unpatch_func__') is None: return ...
b6e8829b9a04d9acdb53bfeb9b084652942eb870
669,510
def communicator(manager): """Get the ``Communicator`` instance of the currently loaded profile to communicate with RabbitMQ.""" return manager.get_communicator()
67cacd93330f6ce5f15a6f0f57aaeef10928f27f
669,511
from typing import List from typing import Optional from typing import Dict def package_item(errorHandlerTest: bool, failureHandlerTest: bool, data: str, aggregateList: List) -> Optional[Dict]: """Package item task definition. Args: errorHandlerTest (bool): One can set this flag (i.e. throught the AP...
d011300bee3511475a9914174ff00c897394d043
669,513
import re def get_table_dividers(table): """ Receives a results table Returns a list of divider rows (------) """ return [len(re.findall(r"^-{3,}$", line)) for line in table.split("\n")]
da3f971fd81207ab8d1a78605c31affb105ad968
669,514
from datetime import datetime def timestamp_to_weekday(timestamp): """ Weekday as a decimal number, where 0 is Sunday and 6 is Saturday. """ return int(datetime.fromtimestamp(timestamp / 1000.0).strftime("%w"))
fad8b84ee638adc80774993888ee4152ee76fc18
669,517
def get_hook_config(hook_api, module_name, key): """ Get user settings for hooks. Args: module_name: The module/package for which the key setting belong to. key: A key for the config. Returns: The value for the config. ``None`` if not set. The ``get_...
45cafd4586ed33c48386fa9a6d8e48251a154cc0
669,519
def get_turn_off_descriptions(get_turn_off, initial_state, current_state): """ Get all 'turn off' descriptions from the current state (if any). Parameters ---------- get_turn_off: function Function that gets the color of light which is off. initial_state: nd.array Initial state o...
ccf18779c38bc76da98425334db4c2b9ef159033
669,521
import torch def compute_Xty(X_t, y_t, cm_t, csd_t): """ cm: column means of X csd: column SDs of X """ ytX_t = torch.mm(y_t.T, X_t) # scale Xty scaled_Xty_t = ytX_t.T / csd_t.reshape(-1,1) # center Xty centered_scaled_Xty_t = scaled_Xty_t - cm_t.reshape(-1,1)/csd_t.reshape(-1,1) *...
3837a623aad24325924681c6d50984f40ae7949f
669,526
import logging def get_logger(name): """ Return a logger with the specified name, creating it if necessary. :param name: module name :return: logging.Logger """ logging.basicConfig(level=logging.INFO, format="%(asctime)s:%(levelname)s:%(name)s: %(message)s", ...
9630e884ff553fe8267c3683234de270878b5b29
669,527
def UseExistingBootDisk(disks): """Returns True if the user has specified an existing boot disk.""" return any(disk.get('boot') == 'yes' for disk in disks)
2e43eab6181b4a921f516b63289bf344de076e14
669,528
import configparser import re def _get_dict_cases(config_file, cases=('LAMMPS', 'GROMACS')): """ Function to return a dictionary with regex patterns for the given cases and a rating of those. Reads in the config_file. Parameters ---------- config_file : str or List[str] File path to t...
b3c1afd401bd748af2afbc7b28d9bcb822e24e0b
669,532
def smiley(message): """ IMPORTANT: You should NOT use loops or list comprehensions for this question. Instead, use lambda functions, any, map, and/or filter. Make a function that converts specific characters to smiley faces. >>> smiley("DSC20:(") 'DSC20:)(:' >>> smiley(":e)k3o(") ...
0e7e197c46a507bc064c79ad438ff31ad4a77aca
669,535
import calendar def get_last_friday_of_month(year, month): """Return the date of the last Friday in the month as an int.""" # calendar_for_month is a 2D list of days of the month, grouped by week. # For example, December 2018 looks like this: # [[ 0, 0, 0, 0, 0, 1, 2], # [ 3, 4, 5, 6, 7...
55778d3dc25cd11d2414ddfda79b106d7ee5424c
669,550
def _lerp(A, B, t): """Perform Linear interpolation in 1D""" return A * (1.0 - t) + B * t
6fb29bad0cec2590b4bc9ad944054a55eacb5ac4
669,551
def _interpolate(a, b, fraction): """Returns the point at the given fraction between a and b, where 'fraction' must be between 0 and 1. """ return a + (b - a) * fraction
47ae6935841a1cd3e941cde1df39a659303fe2ad
669,553
def identity(x): """Identity function: useful for avoiding special handling for None.""" return x
c40dbca9406d243351d7c734b935032b6eb27e67
669,557
def zenodo_get_children(data, resource_id, is_record): """ Get the children of the requested resource. Only going down one level. Parameters ---------- data : dict The project path data resource_id : str The resource id of the children is_record : bool Is this a Zen...
cca8f84539c58d9c5bf8b2cc11f82a4381cc339e
669,558
def triangle_geometry(triangle): """ Compute the area and circumradius of a triangle. Parameters ---------- triangle : (1x3) array-like The indices of the points which form the triangle. Returns ------- area : float The area of the triangle circum_r : float ...
9868cf6adeac1790034aa35b0ce7d8d7c7d38799
669,560
def find_col_index_with_name(name, trained_schema): """ finds the index of the column with name 'name' and returns the index :param name: name of the column to look for :type name: str :param trained_schema: :type trained_schema: List(dict) :return: index of the element in trained_schema tha...
66bc4c9d3f78ba6bf16a03854909787eaad21171
669,561
def anagram(word_1: str, word_2: str) -> bool: """Anagram check example :param word_1: {str} :param word_2: {str} :return: {bool} """ word_1 = word_1.lower() word_2 = word_2.lower() return sorted(word_1) == sorted(word_2)
6e99ebb0659fb4f81414f2dd552f854d52d61a0d
669,562
def get_month(date): """Extract month as form receiving string dd/mm/yyyy or mm/yyyy Args: date (string): Date formate dd/mm/yyyy Returns: mm: string with month. """ num_chars = len(date) if num_chars == 10: return date.split("/")[1] elif num_chars == 7: ret...
76731d27c0183e53ee4760305529de2800237c36
669,563
def get_index(l, key, value): """Find the index of an element by key value, for lists of dicts Return: index or -1 """ return next((index for index, d in enumerate(l) if d[key] == value), -1)
2fb4391093df6f3ec2de7247a430d40b8c58dffd
669,564
def midi_to_ansi_note(midi_note): """ returns the Ansi Note name for a midi number. ::Examples:: >>> midi_to_ansi_note(21) 'A0' >>> midi_to_ansi_note(102) 'F#7' >>> midi_to_ansi_note(108) 'C8' """ notes = ['A', 'A#', 'B', 'C', 'C#', 'D', 'D#', 'E', 'F', 'F#', 'G', 'G#'] num...
c6905c43a3aebd4d976e9fa8dbb37f2e6660cc8d
669,568
def intersect(index, keys): """ Utility method to compute the intersection of all the sets in index that correspond to the given keys keys. Args: index, hash for format {key -> set()} keys, list of strings Returns: set, the intersection of all the sets in index that correspond to...
3a885e7f3822a5f2c9bcc3e0558d060fc61bf17b
669,573
import base64 def b64_encode(byte_string: bytes) -> str: """Base 64 encode a byte string and return a unicode string.""" b64_bytes = base64.b64encode(byte_string) return b64_bytes.decode("utf-8")
d3c78f5914ec0feb826358bfc14b09b6efa657b5
669,576
def func_name(func): """Get a readable name.""" return '.'.join([func.__module__ or "", func.__name__])
e71a3d293a794bcb98d8a5496102067a5aa695db
669,578
def unique(sorted_list): """Return a new list containing all unique elements in their original order Keyword arguments: sorted_list -- a list of comparable elements in which all duplicates are next to one another """ res = [] last = None for element in sorted_list: ...
d36c4edf296c9d5f10ffbf2ec0e6b699041457f5
669,579
import math def compute_quaternion_w( x, y, z ): """Computes the Quaternion W component from the Quaternion X, Y and Z components. """ # extract our W quaternion component w = 1.0 - (x ** 2) - (y ** 2) - (z ** 2) if w < 0.0: w = 0.0 else: w = math.sqrt( w ) return w
ff90a0c2de59c89ecdaf2fc2250ad18611f9a59b
669,581
import re def clean_fn(filename): """ 移除文件名中的特殊字符 :param filename: 文件名 :return: 处理后的文件名 """ return re.sub(r'[\\/:*?"<>|]+', '', filename)
1b893718b15ae98ba0c13ce564d8339039565294
669,585
def is_in_any_txt(txt, within_txts_list, case_insensitive=False): """is "txt" in any of the texts list ?""" for within_txt in within_txts_list: if case_insensitive: # slower if txt.lower() in within_txt.lower(): return True else: if txt in within_...
5e5316fdbaf21617ee8ae3172a0efe4a3c17ae8c
669,588
from datetime import datetime async def do_request(client, url, headers, params=None): """Run request to `url` with the provided `params` and `headers`.""" def requester(url): if params: return client.post(url, headers=headers, json=params) else: return client.get(url,...
bfe6b849dc3642e089c380168d123339e075b5e5
669,591
def html_suffix(string): """Replace or add an html extension to a filename string.""" e = string.split('.') return '.'.join(e[:-1]) + '.html' if len(e) > 1 else e[0] + '.html'
0b246f39cac629ce1921f7e5e49a481509412493
669,592
from typing import Tuple from typing import Any def range(query: Tuple[int, int], field_name: str, object: Any) -> bool: """ Check if value of object is in range of query """ return query[0] < getattr(object, field_name) < query[1]
1a4c4422ffb0091c0c008331ae2ba1f0b266347a
669,593
import dataclasses def to_arg_format(cfg): """ Converts the values of a config in dictionary format to tuples (type, value). This is needed to separate dtype from default value for argument parsing. We treat `None` and `MISSING` as `str`, which is a useful default for parsing command line argumen...
c8d01d2b01e9cf4c946fb5dffa53d812dfccc483
669,594
def reshape_flattened_frames(array): """ Reshapes array shaped [frames, height*width] into array of shape [frames, height, width] Parameters ---------- array : np.array flattened array (frames, height*width) Returns ------- np.array reshaped array (frames, height, widt...
0dfdedb6c7c86116883efa312126af8372daa7b4
669,605