content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def sum_divisible_by_n(target, n):
"""
Note that for 5: 5+10+15+...+995 = 5*(1+2+....+199)
Also note: 1+2+3+...+p = ½*p*(p+1)
"""
p = target // n
return n * (p * (p + 1)) // 2 | 3dc42da324d19813242b27ff9794ce85163ab7f0 | 15,562 |
def invalid_ds_vsby(i, v):
"""Checks if visibility is inconsistent with DS or SS"""
if i == '+' and v >= 0.3:
return True
elif i == '' and not 0.3 < v < 0.6:
return True
return False | c4ee05f4ce8b19f76dfdc1847dc8f3eaf7e1b11b | 15,564 |
def get_valid_test_pipeline():
"""Return an arbitrary pipeline definition."""
return {
'sg1': [
'step1',
'step2',
{'name': 'step3key1',
'in':
{'in3k1_1': 'v3k1', 'in3k1_2': 'v3k2'}},
'step4'
],
'sg2': False,
... | 23611472d2cb0d513c59cec42d45893cb328303f | 15,565 |
import torch
def instance_propagate(annots_inst, masks_inst, is_sequence=True):
"""
propagate the last valid instance to the last position.
Args:
annots_inst: (inst, [seq,] ..., dim)
masks_inst: (inst, [seq,] ...)
Returns
new_annots, new_masks
Notes:
inst-first... | f8f231b1e2601df2c634458a8db34407f910cd51 | 15,566 |
def get_duration_in_time( duration ):
"""
Calculate the duration in hh::mm::ss and return it
@param duration: timestamp from the system
@return: formatted string with readable hours, minutes and seconds
"""
seconds = int( duration % 60 )
minutes = int( (duration / 60) ... | bcd6413b32183688c8b2aac428c5f9bfd5d34b8e | 15,570 |
def elimate_leading_whitespace(source, target=None):
""" return the count of whitespaces before the first target
if it is not the mode: <whitespace>*_target_, return 0
"""
if not source:
return 0
i, length = 0, len(source)
while i < length:
if source[i] not in ' \t':
... | 474bb0094bb8c7f39dd76aa85b72c26af321eb1a | 15,572 |
def set_(data_type):
""" Create an alias for a SetType that contains this data type """
return frozenset([data_type]) | 3ffbe4e111506c5897793cfe423cbbe55137de53 | 15,573 |
import subprocess
def get_tag():
"""
Get the git tag currently checked out.
"""
p=subprocess.Popen(["git","describe","--tags"],stdout=subprocess.PIPE)
tag = p.communicate()[0].decode("utf-8").strip()
return tag | b9acdc3fe2252c13d885d83ffa0d81ba7de3235c | 15,576 |
from bs4 import BeautifulSoup
def tag(tagname, attrs=None, text=None, dtrs=None):
"""Return a soup Tag element."""
attrs = {} if attrs is None else attrs
dtrs = [] if dtrs is None else dtrs
newtag = BeautifulSoup('', features='lxml').new_tag(tagname, attrs=attrs)
if text is not None:
newta... | 911ba6fe1d26b0acfd9ca0eec5f2bfb0369e6e2e | 15,577 |
import math
def marginal_parameter_likelihood(p: float, lambda_: float, x: int, tx: float, T: float) -> float:
"""Computes the marginal likelihood of the parameters lambda and p, given the transaction history.
See http://brucehardie.com/papers/018/fader_et_al_mksc_05.pdf equation (3).
Args:
p (fl... | a90140259da58247b13f4ce165f035076c9816be | 15,578 |
import os
def app_url(content):
"""
Generate APPLICATION_URL from ENV VAR.
"""
url = os.environ['APPLICATION_URL']
return content.replace('$APP_URL', url) | ae13ae104915f1038e66b05fd290984574bfb5f5 | 15,580 |
def task_id_ranges_format(value):
"""Space-separated number ranges in 'start-end' format."""
try:
start, end = [int(i) for i in value.split('-')]
except ValueError:
message = ("Incorrectly formatted task ID range. "
"Argument values should be numbers in the format 'start-e... | 9081765efc6b6240a243798b635573d6a44be470 | 15,581 |
import math
def __rotate(origin: tuple, point: tuple, angle: float):
"""
Rotates a point counterclockwise by a given angle around a given origin.
:param origin: Landmark in the (X, Y) format of the origin from which to count angle of rotation
:param point: Landmark in the (X, Y) format to be rotated
... | af8acd38d07042c1ab8d9ae3fe05afb7a1fea623 | 15,582 |
def precision_ranges(result2rank, total_terms):
"""Computes precision at standard cutoff ranks: [5, 10, 15, 20, 30, 100, 200, 500, 1000]
Args:
result2rank: A dict of source to ranks of good translation candidates.
total_terms: The expected term count.
Returns:
A dict containing a p... | 7e1c60030933530c1d1b1bd09387270174ae2aad | 15,583 |
def count_index(sequence):
"""
The index of `sequence` in a kMer profile.
"""
nucleotide_to_binary = {
'A': 0x00, 'a': 0x00,
'C': 0x01, 'c': 0x01,
'G': 0x02, 'g': 0x02,
'T': 0x03, 't': 0x03
}
binary = 0x00
for b in sequence:
binary = ((binary << 2) | n... | 30821109c85aa36cf2cc7a6e2fbfe2145ecfc58f | 15,584 |
def newends_OOM(adapters, ends):
"""Only works for small datasets like the examples"""
while not all((val == adapters[-1] for val in ends)):
result = []
for val in ends:
if val == adapters[-1]:
result.append(val)
else:
for n in range(1, 4):... | 410a35a5107ba375fec4c9e247aa02ef34c2013f | 15,586 |
import re
def extract_cursor(html) -> str:
"""
extract token for next page
:param html:
:return:
"""
cursor = re.findall('cursor=(\d+)', html)
if len(cursor) > 0:
return cursor[0]
else:
return "" | ec610ac123d0527c17eac56c83fa792d1f8bc1ff | 15,589 |
import socket
def get_local_network(private=False, subnet=100):
"""
Returns the IP address of the local network
Defaults to the local area network. If 'private", defaults to '100' for
the ROACH network.
"""
if private:
IP = socket.gethostbyname("192.168."+str(subnet)+".1")
else:
IP = socket.... | c007005bcf2e377b0c1789b5eeb43fd43c4e46e4 | 15,590 |
import random
def newid():
"""
Generate a new random object ID.
"""
return ''.join([random.choice("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_") for i in range(16)]) | 5d59b77e33712948ac30e2bbe5514dea992ab606 | 15,591 |
import os
import sys
def readScript(args):
"""
Either args.file should contains the provided file name
Or the script was passed through pipe
"""
script = None
# check input type (if piped or not)
# is_pipe will be True if the input is piped
is_pipe = not os.isatty(sys.stdin.fileno())
... | ff04538d900fc2170cb407ca9fdd4dc0b117f4d0 | 15,592 |
def make_text_objs(text, font, color):
"""
Function creates a text.
text -> string; content of text
font -> Font object; face of font
color -> tuple of color (red, green blue); colour of text
returns the surface object, rectangle object
"""
surf = font.render(text, True, color)
... | d5c0a41982f6d6979063dcb24aafc186ff132f1c | 15,594 |
def get_string(element):
"""Helper for safely pulling string from XML"""
return None if element == None else element.string | ff2dbec31f9c3c91c8cf6ca08a36313839265bbd | 15,595 |
def dt_to_us_from_epoch(dt):
"""Convert datetime.datetime object to microseconds since the epoch.
:param dt: datetime.datetime object.
:returns: microseconds since the epoch as a string.
"""
return '{:.0f}'.format(dt.timestamp() * 1e6) | 60d4befd19666ad4799bf45c00a083b3443e9c82 | 15,596 |
def form_errors(form):
""" Displays errors on a form using the form_errors template"""
return {"form":form} | 762f8bd40d689e9846f970c47ef2d154c6503ace | 15,600 |
def theoretical_yield(actual_yield, mole_ratio_top, mole_ratio_bottom):
"""Finds theoretical_yield\n
actual_yield:\n\tThe yield given in the equation if it is grams convert it to moles before using it \n
mole_ratio_top:\n\tFrom the balanced equation given, the number of moles of the wanted element\n
mol... | a601732b073ad9c7adff63fb52739b819425fe7e | 15,601 |
import unittest
def tests():
"""Used by test_suite below."""
return unittest.TestLoader().discover(
"vaeseq/", "*_test.py", top_level_dir=".") | fb3680800ade9e55f596426eca7455d62f8903d2 | 15,602 |
import pickle
def load(to_file=""):
"""function load
Args:
to_file:
Returns:
"""
dd = pickle.load(open(to_file, mode="rb"))
return dd | b4351183e94b2ce2f40510e1af768f6e0751a3c0 | 15,603 |
from bs4 import BeautifulSoup
def get_issue_metadata(issue_soup: BeautifulSoup, name: str) -> str:
"""
Return the value of the key
"""
if len(issue_soup.find_all("dd", id=name)) > 0:
if (name != "issue_indicia_publisher") & (name != "issue_brand"):
return issue_soup.find_all("dd", ... | 2643d36f9d79389048bc9ef6a3bd5de9c900d88f | 15,604 |
import uuid
def high_low_2_uuid(uuid_high, uuid_low):
"""Combine high and low bits of a split UUID.
:param uuid_high: The high 64 bits of the UUID.
:type uuid_high: int
:param uuid_low: The low 64 bits of the UUID.
:type uuid_low: int
:return: The UUID.
:rtype: :py:class:`uuid.UUID`
... | b0c7c53bc4b61085574bcda1d5a8c616f0db8c92 | 15,605 |
def _make_pr(source_repo, source_branch, base_ref, base_url=''):
"""Create a PR JSON object."""
return {
'head': {
'repo': {
'full_name': source_repo,
},
'ref': source_branch,
},
'base': {
'ref': base_ref,
'repo'... | d32e9748608bea7f491db39a750f64cea463b50b | 15,607 |
def _isFloat(argstr):
""" Returns True if and only if the given string represents a float. """
try:
float(argstr)
return True
except ValueError:
return False | 414e802de9557b531e881a5c8430a9a2cb295339 | 15,609 |
import struct
import re
import io
def get_size(data: bytes):
"""
Returns size of given image fragment, if possible.
Based on image_size script by Paulo Scardine: https://github.com/scardine/image_size
"""
size = len(data)
if size >= 10 and data[:6] in (b'GIF87a', b'GIF89a'):
# GIFs
... | 1b45563b0f59f5670638d554821406389b5333a6 | 15,612 |
def category_grouping(data):
"""
Each of the features "TrafficType", "OperatingSystems", and "Browser"
contain categorical values with less than 1% (123) overall datapoints.
Since these "categorical outliers" could potentially skew a clustering
algorithm, we will combine each value with ten or fewer... | 25a461688c13b8e583cc2748c252b4035c789f48 | 15,613 |
def srgb_to_linear(c):
"""Convert SRGB value of a color channel to linear value."""
assert 0 <= c <= 1
if c <= 0.03928:
return c /12.92
else:
return ((c + 0.055) / 1.055)**2.4 | 805960e67b40923608d51cab2a1915aae3d1e3ba | 15,614 |
def _df_to_html(df):
"""Converts DataFrame to HTML table with classes for formatting.
Parameters
---------------
df : pandas.DataFrame
Returns
---------------
str
HTML table for display.
"""
classes = ['table', 'table-hover']
html_raw = '<div id="config_table">{src}</di... | e1310947ff84178e0da32a8be4cda35d9ea16326 | 15,615 |
def choose_theory(proc_keyword_dct, spc_mod_dct_i):
""" choose between theories set in models.dat and in run.dat
"""
if proc_keyword_dct['geolvl']:
# thy_info = tinfo.from_dct(thy_dct.get(
# proc_keyword_dct['geolvl']))
spc_mod_dct_i = None
# else:
# thy_info = spc_mod_... | e548775d4376a6cd4d364c4820db4999dcc79062 | 15,618 |
from typing import Dict
import collections
import csv
def from_csv(path: str) -> Dict[str, str]:
"""Load a CSV into a dictionary."""
result = collections.OrderedDict({}) # type: Dict[str, str]
with open(path, "r") as csv_file:
reader = csv.reader(csv_file)
for row in reader:
a... | 270cd3b3afe9927fffc737b57b8f49a9e6e051e4 | 15,619 |
def get_NICMOS3_G141_WCS():
"""
Defines parameters for the NICMOS/G141 slitless mode
@return: slitless mode parameters
@rtype: dictionary
"""
wcs_keys = {}
# WCS from NICMOS G141 image n6le01upq
#/ World Coordinate System and Related Parameters
wcs_keys['grism'] = [
['WCSAX... | 6f342930d4daa4c76de5ce85cbc44a976d0e6bd0 | 15,620 |
def ask_for_matrix(initial_message, second_message):
"""Obtain an input in the way supported by the task"""
def take_input(message, type_of_value):
return (type_of_value(x) for x in input(message).split())
n, _ = take_input(initial_message, int)
values = [list(take_input(second_message if i ==... | 873a9b767f11eaaf59165fbc4d1a3dcb53adbd29 | 15,621 |
def ign2arr(ign_poses, robot_name):
"""Convert Ignition state poses into array"""
arr = []
prev_seconds = None
for timestamp, data in ign_poses:
if robot_name in data:
pos = data[robot_name]
if prev_seconds != timestamp.seconds:
# store only position every... | 591bcd0edf981b1ff36cb725317780b5cdbf8faa | 15,622 |
def separate_coords(df):
"""Separate the coordinates into a list of 'lats' and 'longs'."""
return df['coordinates'].apply(lambda x: x['latitude']), df['coordinates'].apply(lambda x: x['longitude']) | 5141431e5d1d9a2a60e31867c07b50a645d48165 | 15,623 |
import math
def calc_gps_distance(lat1, long1, lat2, long2):
"""
All calculations need to be done in radians, instead of degrees. Since most
GPS coordinates tend to use degrees, we convert to radians first, and then
use the Haversine formula. The Haversine formula gives the shortest
great-circl... | 4c38ad7a7d468b137834d87959d1c45bd00df9fb | 15,624 |
def get_frame_description(header, i):
"""
This function ...
:param header:
:param i:
:return:
"""
planeX = "PLANE" + str(i)
# Return the description
if planeX in header: return header[planeX]
else: return None | 33d4b57cd936e1d0eb4b3557b8b8496b5e67db08 | 15,625 |
def render_preamble():
"""Renders HTML preamble.
Include this in the HTML of each cell to make sure that #NOTEBOOK_FILES# in links is correctly substituted
"""
return ""
# return """<script>document.radiopadre.fixup_hrefs()</script>""" | 4aa366901a6ab67b30a29beb7a25844b7122a306 | 15,626 |
import sys
def get_contacts(filename):
"""
Retourne 2 listes: names, emails contenant les noms et adresses email
lu à partir de filename
"""
try:
names = []
emails = []
with open(filename, mode='r', encoding='utf-8') as contacts_file:
for a_contact in contacts_file:
names.append(a_contact.split()[0... | df04f03ed0fa79a5b593a187bb51b3ae77f2d0c6 | 15,627 |
def fibonacci(n):
"""returns a list of the first n fibonacci values"""
n0 = 0
n1 = 1
fib_list = []
if type(n) != type(0) or n<=0:
raise Exception("'%s' is not a positive int" % str(n))
for i in range(n):
fib_list.append(n1)
(n0, n1) = (n1, n0+n1)
return fib_list | eb680c89d9d66647b24b5d27dbb34e1a8bb4352c | 15,629 |
def sanitize_mobile_number(number):
"""Add country code and strip leading zeroes from the phone number."""
if str(number).startswith("0"):
return "+254" + str(number).lstrip("0")
elif str(number).startswith("254"):
return "+254" + str(number).lstrip("254")
else:
return number | 8f08563f015d77722f5dec0d07686956b4f46019 | 15,630 |
def total_seconds(timedelta):
""" Some versions of python don't have the timedelta.total_seconds() method. """
if timedelta is None:
return None
return (timedelta.days * 86400) + timedelta.seconds | 800c70a2855034563ab9baf1ca12032677889f5b | 15,631 |
import os
def make_dir(directory_path, new_folder_name):
"""Creates an expected directory if it does not exist"""
directory_path = os.path.join(directory_path, new_folder_name)
if not os.path.exists(directory_path):
os.makedirs(directory_path)
return directory_path | bae473087c00e44cbaa1b65362ef17efcece7973 | 15,632 |
def find_minimal_helices(nturn_starts):
"""
Find helices on the basis of the n-turn beginnings lists
Minimal helices are defined as consecutive n-turns
"""
min_helices = {
"3-min_helices": [],
"4-min_helices": [],
"5-min_helices": []
}
for n in [3, 4, 5]:
na... | 2ceaa35efdd09de8b943c96e1caa70d86fcc8832 | 15,636 |
def get_max_seq_len(indexed_pairs):
"""Return max sequence length computed from index pairs.
indexes already include SOS/EOS/SEP.
"""
max_seq_len = 0
# max_seq = ''
for indexed_pair in indexed_pairs:
max_seq_len = max(max_seq_len, len(indexed_pair[0]))
max_seq_len = max(max_seq_... | 1830334bdea69cad996caf78e9225f70eda48dd0 | 15,637 |
import inspect
def class_vars(obj):
"""Code from https://github.com/devsisters/DQN-tensorflow/blob/master/dqn/base.py"""
return {k:v for k, v in inspect.getmembers(obj) \
if not k.startswith('__') and not callable(k)} | 94112e3b5746e9c16294701a0446febb9a39da13 | 15,638 |
def get_authorization_key(request):
"""
Get the Authorization Key from the request
"""
auth = request.headers.get('Authorization')
if auth:
auth = auth.split()
if len(auth) == 2:
if auth[0].lower() == 'key':
return auth[1]
return None | 5cba14bdebb4b203c773c1e0832373114e554c78 | 15,639 |
def reactor_efficiency(voltage, current, theoretical_max_power):
"""Assess reactor efficiency zone.
:param voltage: voltage value (integer or float)
:param current: current value (integer or float)
:param theoretical_max_power: power that corresponds to a 100% efficiency (integer or float)
:return:... | b58fe806da2bcfdabc12bd3f5b36a0b296ce7142 | 15,640 |
def _bubbled_up_groups_from_units(group_access_from_units):
"""
Return {user_partition_id: [group_ids]} to bubble up from Units to Sequence.
This is to handle a special case: If *all* of the Units in a sequence have
the exact same group for a given user partition, bubble that value up to the
Sequen... | a4e3c5ee563d65bc3b8c787512efe356abfdfbd6 | 15,641 |
def is_list_with_max_len(value, length):
""" Is the list of given length or less?
:param value: The value being checked
:type value: Any
:param length: The length being checked
:type length: Nat
:return: True if the list is of the length or less, False otherwise
:rtype: bool
"""
retu... | fd5016617d264b79ee4e4a0dae7782776d997fc5 | 15,642 |
def exists_transcript_id(db, transcript_id):
"""
Search bar
MongoDB:
db.transcripts.find({'transcript_id': 'ENST00000450546'},
fields={'_id': False})
SciDB:
aggregate(
filter(transcript_index, transcript_id = 'ENST00000450546'),
count(*));
Sci... | 3a9588040e6e3fb7c2c0a78c0038aa873c1670b6 | 15,643 |
def split_data_to_chunks(data: list, max_chunk_size: int, overlapping_size: int):
"""
Because GP can take very long to finish, we split data into smaller chunks and train/predict these chunks separately
:param data:
:param max_chunk_size:
:param overlapping_size:
:return: list of split data
... | 370e9fe9a17c58d7dca202bb4c822f9b8b662fae | 15,644 |
def read_moves(file_name):
"""Read moves from file. Move features are pipe-separated.
Returns moves and keys as lists (every move is a dict at this point)."""
moves = []
with open(file_name, encoding='utf-8') as f:
first_line = f.readline()
first_line = first_line[1:] # remove '#' at th... | a87b73feaf7d49b3ece716fe5732f5647e5dcd25 | 15,645 |
def number_of_constituents(bc_class):
"""
Calculates the number of constituents
Args:
bc_class: The ADH simulation class that holds all simulation information
Returns:
The number of transport constituents
"""
num_trn = 0
cn = bc_class.constituent_properties
if cn.salin... | b290bc6ef6f4b02889dcc82d91120f44bff5f650 | 15,646 |
import os
def get_cols(datadir=".",infiles=None):
"""
Given a directory where simulation data are stored and the name of the input files,
return the name of each body's output columns
Parameters
----------
datadir : str
Name of directory where simulation results are kept
infiles :... | d79bd112a76e28adb7df994d4a4a0998bc9a41ce | 15,647 |
def is_hydrophilic(atom):
"""
Checks whether an atom belongs to hydrophilic residue
:param atom: atom
:return: True if the atom belongs to hydrophobic residue, otherwise false
"""
hydrophilic_atoms = ['H', 'N', 'S', 'O']
hydrophilic_residues = ['GLU', 'ASP', 'ASN', 'QLN', 'HIS', 'GLN', 'SER... | ac366f13934ce859eb9822855481fa7c2a49d21c | 15,648 |
def after_folder_option(location):
"""location: folder full path"""
return True | a2cdb5de2a6852964ecc7e71acbcd0ee2c6b92a8 | 15,649 |
def circle_distance_circle(circle, other):
"""
Give the distance between two circles.
The circles must have members 'center', 'r', where the latest is the radius.
"""
d = abs(circle.center - other.center) - circle.r - other.r
if d < 0.0:
d = 0.0
return d | c76146d1ec9003be5345b14b12563dfb8bac7798 | 15,650 |
def class_to_json(obj):
"""
eturns the dictionary description with simple data structure
(list, dictionary, string, integer and boolean)
for JSON serialization of an object
"""
return(obj.__dict__) | 8bac6f68d8fc18b1a80800943bede4106f618e6c | 15,651 |
def parse_txt(txtfile):
"""Text data format:
original tweet 1 ||| support ||| true
reply tweet 1 ||| deny
reply tweet 2 ||| query
<newline>
original tweet 2 ||| support ||| false
reply tweet 3 ||| deny
reply tweet 4 ||| comment
<newline>
...
"""
raw = open(txtfile, 'r').read()
def parse_ori... | b1c96a759fd8929e58a43c2c2c2c68df2632ee13 | 15,652 |
def get_product_by_id(product_id):
"""
Gets all products
:return:
"""
product = {"name": "test_product"}
return product | 471dafb41f4f77791f55b59c240c2ada4893fa03 | 15,653 |
import socket
import struct
import fcntl
def get_ip(iface=''):
"""
The get_ip function retrieves the IP for the network interface BSDPY
is running on.
"""
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sockfd = sock.fileno()
SIOCGIFADDR = 0x8915
ifreq = struct.pack('... | 0a7c30460ab860c1c2ccd3de9371985508456399 | 15,655 |
def normalize_row(row, max_cols):
"""
Padding to equalize cell string lengths
"""
r = ""
for i, max_col in enumerate(max_cols):
r += row[i] + (max_col - len(row[i]) + 1) * " "
return r + "\n" | c20dbdcf0b786bff13e04c5b1d04c5b0ba46162d | 15,657 |
def is_single(text):
"""Determine if there are many items in the text."""
indicators = [', ', ' y ', ' e ']
return not any(ind in text for ind in indicators) | edfa05e953d3c5816d4294d29d4b1725a1675a3b | 15,658 |
def safe_equals(left: object, right: object) -> bool:
"""Safely check whether two objects are equal."""
try:
return bool(left == right)
except Exception:
return False | 0ba9bb81e6b5ef8580b4677c74e82a40522d5aeb | 15,659 |
def get_minutes_remain(minutes: int) -> int:
"""
Returns minutes remaining after converting to hours
:param minutes: Total minutes before converting to hours
:return: minutes after converting to hours
"""
return minutes % 60 | abf025a83804a03d2c41b88eaac35606a5eddc4c | 15,660 |
def fmripop_save_imgdata(args, out_img, params_dict, output_tag=''):
"""
Saves the output 4D image
"""
# Output filename
output_filename, _ = args.niipath.split(".nii.gz")
# NOTE: this line is not general enough, but it'll do for now
output_tag = '_confounds-removed' + output_tag + '.nii.... | 2426c8a08740a0aa243091f5b62f60c1c0ab467e | 15,661 |
def rb_join_arg(li=[], identif="default", pos=0):
"""Construct url argument with identifier and li as list."""
if li == []:
return ""
if pos == 0:
letter = "?"
else:
letter = "&"
return "{letter}{ident}={arg}".format(letter=letter, ident=identif, arg=','.join(li)) | fefb80814ded2fd53ccf99c92a6ec9b538d85a28 | 15,663 |
def get_topics(bag):
"""
Get an alphabetical list of all the unique topics in the bag.
@return: sorted list of topics
@rtype: list of str
"""
return sorted(set([c.topic for c in bag._get_connections()])) | 863faf144cef064324bb0dff41a9ac70464837ee | 15,664 |
import requests
from bs4 import BeautifulSoup
def get_product_urls(page_lim=10):
""" Get urls of products from product listed web page """
urls = []
for i in range(page_lim):
url = 'http://www.cosme.net/item/item_id/1064/products/page/{0}'.format(i)
r = requests.get(url)
html = r.... | 2199c00a0e38280dd5bfdc84c583aaaf9897b316 | 15,666 |
from typing import Optional
def format_ipfs_cid(path: str) -> Optional[str]:
"""Format IPFS CID properly."""
if path.startswith('Qm'):
return path
elif path.startswith('ipfs://'):
return path.replace('ipfs://', '') | eca4a79bc2ba4151495831b51bbd50df68f73025 | 15,667 |
def openUnicode(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True,
opener=None):
"""
Unicode auto-detection by BOM.
:return: Returns open() with the correct encoding and with the missing first character, if it is BOM.
"""
detect = False
if "r" i... | c7af92a9acde80e5f1a14a304cb135b075b71d7b | 15,668 |
def insertion_sort(integers):
"""Iterate over the list of integers. With each iteration,
place the new element into its sorted position by shifting
over elements to the left of the pointer until the correct
location is found for the new element.
Sorts the list in place. O(n^2) running time, O(1) spa... | ee7aa8920406f7c74870e346e486f29486894df1 | 15,670 |
import curses
def init_screen(args):
""" Set ncurses screen and returns the screen object """
screen = curses.initscr()
curses.curs_set(0)
curses.start_color()
curses.init_pair(1, 1, args.background)
curses.init_pair(2, 2, args.background)
curses.init_pair(3, 3, args.background)
curs... | e46a5a3bee5f498219fbbf2b8b4df50abffa07fe | 15,671 |
def get_settings():
"""
Returns some nice default settings for matplotlib to be used with `matplotlib.pyplot.rc_context`.
"""
return {'axes.labelsize': 32,
'xtick.major.size': 10,
'xtick.major.width': 1.5,
'xtick.labelsize': 24,
'ytick.major.size': 10,
... | 7864c0bcb3b7ab427f6046b3358ee81f70646dd5 | 15,672 |
def patron_pid_minter(record_uuid, data):
"""Dummy patron minter."""
return None | c4ab8008467d54326911634bb51335f3b86cc96e | 15,673 |
import os
def get_output_number(dst):
"""Gives the last output folder number
Returns:
int: Last output folder number
"""
data = os.listdir(dst)
if not data == []:
last_record = sorted(data)[-1]
hiphen_index = last_record.rfind("-")
return int(last_record[hiphen_ind... | 292f42e0f73eb11b45d611eaa270282ba04de509 | 15,674 |
import sys
def start_logging(filename, params):
"""Logs the output of the execution in the specified file
:param filename: The name of the log file
:type filename: str
"""
f = open(f'{params["logs_path"]}/experiment-{filename}.txt' , 'w')
sys.stdout = f
return f | 5edb40d87fa1b1c121670abc5aaa5ebdca0a2f60 | 15,675 |
import os
def expand_path(path: str) -> str:
"""Expand variables and ~"""
return os.path.expanduser(os.path.expandvars(path)) | 88242835c8fa37c9bbb877ebc6d48f94b1f675d3 | 15,676 |
from typing import List
def primary() -> List[str]:
"""Primary color scheme."""
return ["#00A58D", "#008A8B", "#9FCD91", "#09505D", "#00587C"] | 8527c8a649e554e077a57172dfb0d529fff4036a | 15,677 |
import warnings
def pull_halo_output(h5file, clusterID, apertureID, dataset):
"""
Function to extract a dataset from a Bahamas snapshot output.
:param h5file: The h5py File object to extract the data from
:param clusterID: The number of cluster in the order imposed by FoF
:param apertureID: int(0-22) The index o... | d389af763c7dc7a3c6e54a1f61f4906c7fa4dc0e | 15,679 |
def rt_delta(maxdiff, precision=5):
# type: (float, int) -> float
"""Return the delta tolerance for the given retention time.
Keyword Arguments:
maxdiff -- maximum time difference between a feature edge and
an adjacent frame to be considered part of the same
... | ad04d4f0405544d1cf137b7b3c8aa25ac670365f | 15,680 |
def positive_negative_basic_reward_function(causal_prefetch_item):
"""
Consistent positive reward based on something being used within 128 steps (1, -1) rewards
"""
if causal_prefetch_item is None:
return -1
return 1 | beaefcaebe806329d17ec8fa584e2a0f102b978c | 15,681 |
def create_template_dict(dbs):
""" Generate a Template which will be returned by Executor Classes """
return {db: {'keys': [], 'tables_not_found': []} for db in dbs} | 01dbd3733ec77fef0323eea35bc67064b19093c9 | 15,682 |
def get_current_application(request):
"""Get current application."""
try:
app_name = request.resolver_match.namespace
if not app_name:
app_name = "home"
except Exception as e:
app_name = "home"
return app_name | 310004714da3129cafb2bc635837920a7457fbe7 | 15,683 |
import os
def check_block_directory():
"""
檢查日誌檔存放所需資料夾是否存在
Args:
None
Returns:
1:成功 | 0:失敗
"""
directory = str(os.getenv('DIRECTORY'))
if os.path.isdir(directory):
return True
else:
return False | 563c42679a12c259bbf90294c02150c8eb6cf353 | 15,685 |
def build_json(image_content):
"""Builds a json string containing response from vision api."""
json_data = {
'requests': [{
'image': {
'content': image_content
},
'features': [{
'type': 'FACE_DETECTION',
'maxResults': 1,
}]
... | bf6f45187d2e6b2c4a50ccf7ecfbeeb862f353ff | 15,686 |
def missing_summary(df):
"""
Takes in a dataframe and
returns a summary of all
missing values.
Parameters:
-----------
df : dataframe
Dataframe to calculate the
missing summary from.
Returns:
--------
df_miss : dataframe
Missing values s... | 4c6bb35e9d01827667d7b5ecbbc0b1ebcc8231bb | 15,687 |
import hashlib
def checksum(file, method='sha1', chunk_size=4096):
"""Calculate the checksum of a file.
Args:
file: str, path-like, or file-like bytes object
"""
try:
fh = open(file, 'rb')
except TypeError:
fh = file
try:
h = hashlib.new(method)
while ... | 9638985bec0c95d2c9cd30a93bf48f93381f99de | 15,689 |
import argparse
import os
import sys
def user_input():
"""
Handle PBclust command line arguments
"""
parser = argparse.ArgumentParser(
description="Cluster protein structures based on their PB sequences.")
# mandatory arguments
parser.add_argument("-f", action="append", required=True,... | bcae7a5e7e186fac62fc0bd401deb83d356a6cd6 | 15,692 |
def week(make_week):
"""Fixture creating a week."""
return make_week() | 52dda51ed415d75f966e302c930cc54119005307 | 15,693 |
def tf_score(word, sentence):
"""
Formula:
Number of times term w appears in a document) / (Total number of terms in the document).
"""
word_frequency_in_sentence = 0
len_sentence = len(sentence)
for word_in_sentence in sentence.split():
if word == word_in_sentence:
word_... | e93efbd52dfcdf05f771ab4d3f353e3f837dda96 | 15,694 |
def main():
"""Computational pathology toolbox by TIA Centre."""
return 0 | 7a0c5a83b018860f683407bd9517d4d28b1c2443 | 15,695 |
import sys
def compare_sequence_dicts(fasta_dict, bam_dict):
"""Compares a FASTA and BAM sequence dictionary, and prints any differences.
Returns true if all required sequences are found, false otherwise."""
if fasta_dict == bam_dict:
return True
sys.stderr.write("Sequence dictionaries in FASTA/BAM files... | 476dac9f4aa025f586f5fbe33d52062260920677 | 15,696 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.