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(";",";\n ")
return text | 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: string
"""
if quotes:
lst_str = str(lst)
if not brackets:
lst_str = lst_str[1:-1]
else:
lst_str = ', '.join(lst)
if brackets:
lst_str = '[' + lst_str + ']'
lb = ',\n' + indent*' '
return lst_str.replace(', ', lb) | 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 of the class to be named
"""
typ = type(obj) if instance else obj
return "{}.{}".format(typ.__module__, typ.__name__) | 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]
elif v == max_value:
max_indices.append(i)
return max_indices | 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]
Returns
amplslen: the fractional amplitude of the self-lensing
"""
amplslen = 7.15e-5 * radistar**(-2.) * peri**(2. / 3.) * masscomp * (masscomp + massstar)**(1. / 3.) * 1e3 # [ppt]
return amplslen | 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_week = datetime.strptime(semester_first_week_date, '%Y-%m-%d %H:%M:%S').strftime('%W')
# 获取当前日期是一年中的第几周, 返回字符串
current_year_week = datetime.now().strftime('%W')
# 计算当前日期所属的教学周
# ( ) 中的减一表示第一周之前的周数
# 最后加一是因为计算周数是从索引00开始的,所以需要加1
current_teach_week = int(current_year_week) - (int(semester_first_week) - 1) + 1
return current_teach_week | 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 '{dataset_id}_{rule_name}'.format(dataset_id=dataset_id,
rule_name=re.sub(
r'\W', '_', rule_name)) | 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(dict1[key], dict) and isinstance(dict2[key], dict):
result[key] = recursive_dict_merge(dict1[key], dict2[key])
else:
result[key] = dict2[key]
return result | 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
"""
if sorted_citations_list and sorted_citations_list[0] >= n:
return the_H_function(sorted_citations_list[1:], n + 1)
else:
return n - 1 | 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, 180 or 270 degrees only") | 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_for_creating_event(row):
return {'id': row[id_field], 'event': name_of_event, 'timestamp': row[timestamp_field]} | 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.find('HEADER')
if element_header is None:
return False
element_format = element_header.find('FORMAT')
if element_format is None:
return False
try:
name = element_format.attrib['NAME']
except KeyError:
return False
if name != 'QEXML':
return False
return True | 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 - len(suffix)] + suffix | 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:
return "" | 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 : int
Quantile on which to perform turnover analysis.
period: int, optional
Number of days over which to calculate the turnover.
Returns
-------
quant_turnover : pd.Series
Period by period turnover for that quantile.
"""
quant_names = quantile_factor[quantile_factor == quantile]
quant_name_sets = quant_names.groupby(level=['date']).apply(
lambda x: set(x.index.get_level_values('asset')))
name_shifted = quant_name_sets.shift(period)
new_names = (quant_name_sets - name_shifted).dropna()
quant_turnover = new_names.apply(
lambda x: len(x)) / quant_name_sets.apply(lambda x: len(x))
quant_turnover.name = quantile
return quant_turnover | 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
"""
return dict(zip(my_keys, my_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 to roll to.
"""
# get resolution of data
res = lon.values[1] - lon.values[0]
# calculate how many degrees to move by to have lon[0] of rolled subset as lower bound of request
diff = lon.values[0] - first_element_value
# work out how many elements to roll by to roll data by 1 degree
index = 1 / res
# calculate the corresponding offset needed to change data by diff
offset = int(round(diff * index))
return offset | 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(hashlib.sha256(contents).digest()).decode('latin1').rstrip('=')
size = len(contents)
return hash, size | 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[:-len(".dylib")]
if path.endswith(".so"):
return path[:-len(".so")]
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 number
"""
def convert_color_to_letter(color):
if color.lower() not in ('red', 'white', 'blue', 'green', 'black', 'colorless', 'tap', 'energy'):
# some cards have weird split mana costs where you can pay N colorless
# or one of a specific color.
# Since we're ending up here, and what we're given isn't a color, lets assume its N
return color
else:
if color.lower() == 'blue': return 'U'
else: return color[0].upper()
try:
val = int(text, 10)
except Exception:
pass
else:
# This is just a number. Easy enough.
return f"{{{text}}}"
if ' or ' in text:
# this is a compound color, not as easy to deal with.
text = text.replace('or', '')
text = '/'.join([convert_color_to_letter(x) for x in text.split()])
else:
if 'Variable' in text:
text = 'X'
else:
# hopefully all that's left is just simple color symbols.
text = convert_color_to_letter(text)
# at this point we've hopefully
return f"{{{text}}}" | 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, the Tuple has length 13.
Returns:
--------
summed_layers: Tensor of shape (batch, seq_length, hidden_size)
"""
last_layers = sequence_outputs[-4:]
return torch.stack(last_layers, dim=0).sum(dim=0) | 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_str = '\n'.join(res_list)
return res_str | 3da11748d650e234c082255b8d7dff5e56e65732 | 709,997 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.