content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
def counter_format(counter): """Pretty print a counter so that it appears as: "2:200,3:100,4:20" """ if not counter: return "na" return ",".join("{}:{}".format(*z) for z in sorted(counter.items()))
992993a590eabb2966eb9de26625077f2597718c
709,925
from pathlib import Path def all_files(dir, pattern): """Recursively finds every file in 'dir' whose name matches 'pattern'.""" return [f.as_posix() for f in [x for x in Path(dir).rglob(pattern)]]
45f12cda2e16cb745d99d2c8dfb454b32130e1c8
709,929
def matches(spc, shape_): """ Return True if the shape adheres to the spc (spc has optional color/shape restrictions) """ (c, s) = spc matches_color = c is None or (shape_.color == c) matches_shape = s is None or (shape_.name == s) return matches_color and matches_shape
fa9c90ea2be17b0cff7e4e76e63cf2c6a70cc1ec
709,930
def is_str(element): """True if string else False""" check = isinstance(element, str) return check
c46b80d109b382de761618c8c9a50d94600af876
709,932
def deal_text(text: str) -> str: """deal the text Args: text (str): text need to be deal Returns: str: dealed text """ text = " "+text text = text.replace("。","。\n ") text = text.replace("?","?\n ") text = text.replace("!","!\n ") text = text.replace(";"...
8f16e7cd2431dfc53503c877f9d4b5429f738323
709,933
def list2str(lst, indent=0, brackets=True, quotes=True): """ Generate a Python syntax list string with an indention :param lst: list :param indent: indention as integer :param brackets: surround the list expression by brackets as boolean :param quotes: surround each item with quotes :return...
ef441632bf59714d3d44ede5e78835625b41f047
709,935
def get_class_name(obj, instance=True): """ Given a class or instance of a class, returns a string representing the fully specified path of the class. Parameters ---------- obj : object An instance of any object instance: bool Indicates whether given object is an instance o...
3a7ebd1fb2682ec5dff6d42cd2cccf918d67f9a0
709,938
def maxindices(l): """ Get indices for all occurences of maximal element in list :param l: :return: """ max_indices = [] max_value = l[0] #Assume un-exhaustible iterator for i, v in enumerate(l): if v > max_value: max_value = v max_indices = [i] el...
b2f155fa97455c0327b2717591ebea2176773012
709,939
def retr_amplslen(peri, radistar, masscomp, massstar): """ Calculate the self-lensing amplitude. Arguments peri: orbital period [days] radistar: radius of the star [Solar radius] masscomp: mass of the companion [Solar mass] massstar: mass of the star [Solar mass] R...
32c0618f0e5965357fbcadd090443d0baf0e65bd
709,942
from datetime import datetime def calculate_current_teach_week(semester_first_week_date='2021-3-08 08:00:00'): """ 计算当前日期所属教学周,实现思路是:当前日期所属一年中的周 - 每学期的第一周 ---- param: semester_first_week_date: 学期第一周的日期,例如 '2021-3-08 08:00:00' return: 当前教学周 """ # 获取指定日期属于当年的第几周, 返回字符串 semester_first_we...
01a8df84b878e192dae1b1d0d38d78fb5c19f93e
709,943
import re def get_sandbox_table_name(dataset_id, rule_name): """ A helper function to create a table in the sandbox dataset :param dataset_id: the dataset_id to which the rule is applied :param rule_name: the name of the cleaning rule :return: the concatenated table name """ return '{data...
ee07d40f885cb9d6d0d34cc0215620a2572b6b5f
709,944
import copy def recursive_dict_merge(dict1, dict2): """ Merges dictionaries (of dictionaries). Preference is given to the second dict, i.e. if a key occurs in both dicts, the value from `dict2` is used. """ result = copy.deepcopy(dict1) for key in dict2: if key in dict1 and isinstance(...
fbcb51ad47de0dd4d1c95cd59873918187736b63
709,945
def the_H_function(sorted_citations_list, n=1): """from a list of integers [n1, n2 ..] representing publications citations, return the max list-position which is >= integer eg >>> the_H_function([10, 8, 5, 4, 3]) => 4 >>> the_H_function([25, 8, 5, 3, 3]) => 3 >>> the_H_function([1000, 20]) => 2...
24ad3d85963ef0a9d4531ba552371d7e829f1c2a
709,949
import random from bs4 import BeautifulSoup def get_random_quote(quotes_list): """Return a random quote to user.""" upper_limit = len(quotes_list)-1 select = random.randint(0, upper_limit) selected_quote = quotes_list[select] soup = BeautifulSoup(selected_quote, 'html.parser') return soup.text
c50f99640da88319c2b643b0fe1c386206c0c00b
709,950
def get_extension(fname): """ Get file extension. """ return '.' + fname.split(".")[-1]
9fa6f63d848aa7781b55e9cc384c9a8cb9665c69
709,951
def rotation(new_rotation=0): """Set the display rotation. :param new_rotation: Specify the rotation in degrees: 0, 90, 180 or 270 """ global _rotation if new_rotation in [0, 90, 180, 270]: _rotation = new_rotation return True else: raise ValueError("Rotation: 0, 90, 1...
4f12a90e104ef66e50520523d23b3fff421fa991
709,952
import re def clean_cmd(cmd): """Removes multiple spaces and whitespace at beginning or end of command. Args: cmd (str): A string containing the command to clean. Returns: A cleaned command string. """ return re.sub(r'\s{2, }', ' ', cmd).strip(' \t\n\r')
d98f4fea9791cbb5936b306ee74335efc6515902
709,956
import random def throw_dice(n): """Throw `n` dice, returns list of integers""" results = [] while n > 0: results += [random.randint(1,6)] n = n-1 return results
68c56b468ecd1eff59932099dd4620bae9581f45
709,964
def simple_dict_event_extractor(row, condition_for_creating_event, id_field, timestamp_field, name_of_event): """ Takes a row of the data df and returns an event record {id, event, timestamp} if the row satisfies the condition (i.e. condition_for_creating_event(row) returns True) """ if condition_fo...
2195acf5df6f465fdf3160df3abbac54e5ac0320
709,967
def __getStationName(name, id): """Construct a station name.""" name = name.replace("Meetstation", "") name = name.strip() name += " (%s)" % id return name
daab36ed8020536c8dd2c073c352634696a63f3e
709,971
def is_valid_pre_6_2_version(xml): """Returns whether the given XML object corresponds to an XML output file of Quantum ESPRESSO pw.x pre v6.2 :param xml: a parsed XML output file :return: boolean, True when the XML was produced by Quantum ESPRESSO with the old XML format """ element_header = xml.f...
80bda73addc68a88b2a1dc5828c0553cbaf7e6f2
709,974
def addMovieElement(findings, data): """ Helper Function which handles unavailable information for each movie""" if len(findings) != 0: data.append(findings[0]) else: data.append("") return data
af3c45c8b8d4c0cb7ba1cac4925d0f5998affe93
709,975
def get_trimmed_glyph_name(gname, num): """ Glyph names cannot have more than 31 characters. See https://docs.microsoft.com/en-us/typography/opentype/spec/... recom#39post39-table Trims an input string and appends a number to it. """ suffix = '_{}'.format(num) return gname[:31...
a5e90163d15bd4fc0b315414fffd2ac227768ab0
709,976
def get_proto_root(workspace_root): """Gets the root protobuf directory. Args: workspace_root: context.label.workspace_root Returns: The directory relative to which generated include paths should be. """ if workspace_root: return "/{}".format(workspace_root) else: r...
35cff0b28ee6c1893e5dba93593126c996ba72cc
709,978
def quantile_turnover(quantile_factor, quantile, period=1): """ Computes the proportion of names in a factor quantile that were not in that quantile in the previous period. Parameters ---------- quantile_factor : pd.Series DataFrame with date, asset and factor quantile. quantile : i...
6c7b2afdd4c4f0a2dbf38064d2d8664a25370ca2
709,979
def convert_to_dict(my_keys, my_values): """Merge a given list of keys and a list of values into a dictionary. Args: my_keys (list): A list of keys my_values (list): A list corresponding values Returns: Dict: Dictionary of the list of keys mapped to the list of values """ ...
e00690d27770539e6b9d2166835f6bd1b9c11c5a
709,981
def calculate_offset(lon, first_element_value): """ Calculate the number of elements to roll the dataset by in order to have longitude from within requested bounds. :param lon: longitude coordinate of xarray dataset. :param first_element_value: the value of the first element of the longitude array ...
a55eee1dd11b1b052d67ab1abadfc8087c1a2fe0
709,983
import base64 import hashlib def rehash(file_path): """Return (hash, size) for a file with path file_path. The hash and size are used by pip to verify the integrity of the contents of a wheel.""" with open(file_path, 'rb') as file: contents = file.read() hash = base64.urlsafe_b64encode(has...
167449640e8cbf17d36e7221df3490a12381dd8e
709,986
from typing import OrderedDict def sort_dict(value): """Sort a dictionary.""" return OrderedDict((key, value[key]) for key in sorted(value))
93e03b64d44ab79e8841ba3ee7a3546c1e38d6e4
709,988
from typing import Dict def dataset_is_open_data(dataset: Dict) -> bool: """Check if dataset is tagged as open data.""" is_open_data = dataset.get("isOpenData") if is_open_data: return is_open_data["value"] == "true" return False
fc1591d4a045ba904658bb93577a364145492465
709,993
def _remove_suffix_apple(path): """ Strip off .so or .dylib. >>> _remove_suffix_apple("libpython.so") 'libpython' >>> _remove_suffix_apple("libpython.dylib") 'libpython' >>> _remove_suffix_apple("libpython3.7") 'libpython3.7' """ if path.endswith(".dylib"): return path[:...
c5526b0f3420625c2efeba225187f72c7a51fb4b
709,994
def alt_text_to_curly_bracket(text): """ Converts the text that appears in the alt attribute of image tags from gatherer to a curly-bracket mana notation. ex: 'Green'->{G}, 'Blue or Red'->{U/R} 'Variable Colorless' -> {XC} 'Colorless' -> {C} 'N colorless' -> {N}, where N is some ...
c604b236a8d0baeff244e0e246176a406674c9e2
709,995
from typing import Tuple import torch def sum_last_4_layers(sequence_outputs: Tuple[torch.Tensor]) -> torch.Tensor: """Sums the last 4 hidden representations of a sequence output of BERT. Args: ----- sequence_output: Tuple of tensors of shape (batch, seq_length, hidden_size). For BERT base, th...
14bba441a116712d1431b1ee6dda33dc5ec4142c
709,996
def list2str(lst: list) -> str: """ 将 list 内的元素转化为字符串,使得打印时能够按行输出并在前面加上序号(从1开始) e.g. In: lst = [a,b,c] str = list2str(lst) print(str) Out: 1. a 2. b 3. c """ i = 1 res_list = [] for x in lst: res_list.append(str(i)+'. '+str(x)) i += 1 res...
3da11748d650e234c082255b8d7dff5e56e65732
709,997