content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
import os
def load_sentiments(file_name="data"+os.sep+"data/sentiments.csv"):
"""Read the sentiment file and return a dictionary containing the sentiment
score of each word, a value from -1 to +1.
"""
sentiments = {}
for line in open(file_name, encoding='utf8'):
word, score = line.split(',... | 7713037d3c524d9a3c1a943840e96654f0552bbb | 696,189 |
import os
def readConfig():
"""
Read conf file and returns (editorName, pathToSave)
"""
confPath = os.path.expanduser("~")
confFile = os.path.join(confPath, ".forcecode")
if not os.path.isfile(confFile):
fileI = open(confFile, "w")
fileI.write("editor:gedit:")
fileI.wr... | d0d11749e6a17fa395fc925b55b8fdc32f834d14 | 696,192 |
def switch(*args):
""":yaql:switch
Returns the value of the first argument for which the key evaluates to
true, null if there is no such arg.
:signature: switch([args])
:arg [args]: mappings with keys to check for true and appropriate values
:argType [args]: chain of mapping
:returnType: a... | c0d152b4004866826c4892a1340865b79feefa2c | 696,194 |
import subprocess
def cmdline(command):
"""This loads the bestmatchfinder homepage."""
process = subprocess.Popen(
command,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
shell=True,
)
out, error = process.communicate()
# print("out", out)
# print("error", erro... | 929482b4ca2272ed41005fc54bdaebdffd4ede15 | 696,195 |
def extract_segment_types(urml_document_element, namespace):
"""Return a map from segment node IDs to their segment type
('nucleus', 'satellite' or 'isolated').
"""
segment_types = \
{namespace+':'+seg.attrib['id']: seg.tag
for seg in urml_document_element.iter('nucleus', 'satellite')}
... | 30d2050055a9c2e66da66e3663df27a9cc6852e1 | 696,196 |
def convert2voxels(x_um_rw, imExtends, voxelSize):
"""
Converting from real world um coordinates to 0 origin voxel.
:param x_um_rw: coordinates in real world frame, dimensions in um
:param imExtends (list of lists): the first list are the initial extends of the image, and the second list the
final... | 123414615e40bb41802b8f5f072bb994f859f3d7 | 696,197 |
import os
def get_blacklist(api):
"""Returns a function to filter unimportant files normally ignored."""
git_path = os.path.sep + '.git' + os.path.sep
svn_path = os.path.sep + '.svn' + os.path.sep
return lambda f: (
f.startswith(api.IGNORED) or
f.endswith('.pyc') or
git_path in f or
sv... | c33dce4f6e6035ad3ec4a6353f3b42f7b0848f1c | 696,198 |
def moeda(x=0.0, moeda='R$'):
"""
==> Formata valor de x para f'string de moeda local (BRL).
:param x: Valor que será formatado.
:param moeda: Cifrão da moeda local (BRL).
:return: retorna f'string formatada para moeda local (BRL).
"""
return f'{moeda}{x:.2f}'.replace('.', ',') | 7a9002ad9fbc476090d1a82a2fb18222567d1c71 | 696,199 |
def fill_big_gaps(array, gap_size):
"""
Insert values into the given sorted list if there is a gap of more than ``gap_size``.
All values in the given array are preserved, even if they are within the ``gap_size`` of one another.
>>> fill_big_gaps([1, 2, 4], gap_size=0.75)
[1, 1.75, 2, 2.75, 3.5, 4]
... | 11ecb164b9e54c75db249ca27cbbdd582ed47945 | 696,201 |
from pathlib import Path
def get_package_root() -> Path:
"""Returns package root folder."""
conf_folder = Path(__file__).parent.parent
dirs_in_scope = [x.name for x in conf_folder.iterdir() if x.is_dir()]
if "mapservices" not in dirs_in_scope:
msg = (
f"Not the right root director... | 7ff402b510528f7256ee6033ecbe6d5054bf487d | 696,202 |
def inversion(permList):
"""
Description - This function returns the number of inversions in a
permutation.
Preconditions - The parameter permList is a list of unique positve numbers.
Postconditions - The number of inversions in permList has been returned.
Input - permList : list... | 45868e69ceaed9f9a901da8f0157cc6fddace306 | 696,203 |
def match_rules(rules, app, action):
"""
This will match rules found in Group.
"""
for rule in rules.split(','):
rule_app, rule_action = rule.split(':')
if rule_app == '*' or rule_app == app:
if rule_action == '*' or rule_action == action or action == '%':
ret... | dd0f76819f2211111551a866c46496c36a1f385b | 696,204 |
def calc_acc(top_action, bot_aspect_action, bot_opinion_action, gold_labels, mode):
"""
Get accuracy.
Args:
top_action (list): List of predicted sentiments with their positions in a sequence.
bot_action (list): List of list(s) of sequence length, where each list of predicted entity correspo... | 2c247de46a132f708981c29a41cb2068b5efb91e | 696,206 |
def thrift_attrs(obj_or_cls):
"""Obtain Thrift data type attribute names for an instance or class."""
return [v[1] for v in obj_or_cls.thrift_spec.values()] | 7c4f75f0e00ca08ca8d889d537ceee355c4c6552 | 696,207 |
def s3so(worker_id):
"""
Returns s3 storage options to pass to fsspec
"""
endpoint_port = (
5000 if worker_id == "master" else 5550 + int(worker_id.lstrip("gw"))
)
endpoint_uri = f"http://127.0.0.1:{endpoint_port}/"
return {"client_kwargs": {"endpoint_url": endpoint_uri}} | bee24bca3dfefd1568c5376d2636c4354cda8633 | 696,208 |
def find_one_or_more(element, tag):
"""Return subelements with tag, checking that there is at least one."""
s = element.findall(tag)
assert len(s) >= 1, 'expected at least one <%s>, got %d' % (tag, len(s))
return s | 6faee2e8cad1a943da6499cb0ab987cafa79104a | 696,209 |
def find_max_simultaneous_events(events):
"""
Question 14.5: Given a list of intervals representing
start and end times of events, find the maximum number
of simultaneous events that we can schedule
"""
transitions = []
simultaneous = 0
max_simultaneous = 0
for event in events:
... | ffacabf17aa89dc61903a1aab44bace923f224a4 | 696,210 |
def G(x: int, y: int, z: int) -> int:
"""2ラウンド目に行う演算処理"""
return (x & z) | (y & ~z) | 802338277d7bba0f0e019fe886489beba37ecf18 | 696,211 |
def get_top(cards, colour):
"""
Get the top card played of the given colour string.
"""
iter = [card.rank
for card in cards
if card.colour.lower() == colour.lower()]
if not iter:
return 0
return max(iter) | 6c11a55c7214b18713462ffc0891a12a0460023f | 696,212 |
def transform_objects(objects):
"""Transform objects."""
obj_list = []
for i, obj in objects.items():
data = dict(obj, instance_id=i)
if data['destroyed'] is None:
data['destroyed_x'] = None
data['destroyed_y'] = None
obj_list.append(data)
return obj_list | e53f21ef107ba38a22b86d1747329aa9dfca2617 | 696,213 |
import math
def distance(x1, y1, x2, y2):
"""distance: euclidean distance between (x1,y1) and (x2,y2)"""
return math.sqrt((x2 - x1)**2 + (y2 - y1)**2) | b7b4662a88c9afd4b63d6ab04fc51749916749f1 | 696,214 |
def repeated_definitions_of_repo_in_config(config, repo):
"""Check if there are multiple definitions of the same repository in a
pre-commit configuration object.
Parameters
----------
config : dict
Pre-commit configuration dictionary.
repo : str
Repository to check for multiple de... | 10f44cd6d6d1ef2313a2b8b6ab20b81df8294565 | 696,217 |
def get_links_from_wiki(soup, n=5, prefix="https://en.wikipedia.org"):
"""
Extracts `n` first links from wikipedia articles and adds `prefix` to
internal links.
Parameters
----------
soup : BeautifulSoup
Wikipedia page
n : int
Number of links to return
prefix : str, defa... | 5d0b77bf82cc5e09cc3db3fe9e0bd0b58bc81f55 | 696,218 |
import bisect
def find_ge(array, x):
"""Find leftmost item greater than or equal to x.
Example::
>>> find_ge([0, 1, 2, 3], 1.0)
1
**中文文档**
寻找最小的大于等于x的数。
"""
i = bisect.bisect_left(array, x)
if i != len(array):
return array[i]
raise ValueError | 6f1aaa40da6d00acd15ee86d1db161f714c6d5d3 | 696,219 |
from typing import List
import subprocess
def _commit_files(files: List[str], message: str) -> bool:
"""
Stages the given files and creates a commit with the given message.
Returns True if a new commit was created, False if the files are unchanged.
"""
subprocess.check_call(["git", "add"] + files... | ce043cd3317c15c0cea1f4dca84dcdb0484a79eb | 696,220 |
def reverse_list (list):
"""
:param: list
:return: list
Return a list, whose elements are in reversed order
e.g. reverse_list([30,40,50]) returns [50,40,30]
"""
reversed=[]
#Copy the first element of the given list into empty reversed list: reversed list is now [30]
reversed.append(list[0])
#Insert second ele... | a3370aa505e19a4e4bca76d765c8f3859ac106d2 | 696,221 |
def inputInt(prompt, min=0, max=100):
"""
inputInt retourne un entier saisit par l'utilisteur. La saisit est
sécurisée: en de mauvaises entrés on redemande à l'utilisateur l'entier.
Si l'utilisateur quitte le proggrame avec Contrôle+C, le programme s'arrête.
"""
while True:
try:
i = int(input(prompt))
exce... | fa1a9ca1bcbdbf9dd46c37ecb242bb012c14d9e9 | 696,222 |
import torch
def max_log_loss(logits, targets=None, reduction='mean'):
"""
Loss.
:param logits: predicted classes
:type logits: torch.autograd.Variable
:param targets: target classes
:type targets: torch.autograd.Variable
:param reduction: reduction type
:type reduction: str
:retu... | d1478f73e3b18c1926f4c859125e120177799c06 | 696,224 |
import re
def clear_comments(data):
"""Return the bibtex content without comments"""
res = re.sub(r"(%.*\n)", '', data)
res = re.sub(r"(comment [^\n]*\n)", '', res)
return res | 16308058dd608a241109455a31405aa01fe46f2d | 696,225 |
async def list_top_communities(context, limit=25):
"""List top communities. Returns lite community list."""
assert limit < 100
#sql = """SELECT name, title FROM hive_communities
# WHERE rank > 0 ORDER BY rank LIMIT :limit"""
sql = """SELECT name, title FROM hive_communities
WH... | 64d73bbb857c2fd6ef3fb680d403869414eab268 | 696,226 |
def get_file_name(path):
"""
:param path:
:return:
"""
parts = path.split("/")
return parts[len(parts) - 1] | 6fb5ff0044931afd09a81df6be48da78b62e5902 | 696,227 |
def get_op_output_unit(unit_op, first_input_units, all_args=None, size=None):
"""Determine resulting unit from given operation.
Options for `unit_op`:
- "sum": `first_input_units`, unless non-multiplicative, which raises
OffsetUnitCalculusError
- "mul": product of all units in `all_args`
- "... | 0a873f698886b316c49ed24581bf5786f59be457 | 696,228 |
import getpass
def smtp_config_generator_password(results):
"""
Generate password config.
:param results: Values. Refer to `:func:smtp_config_writer`.
:type results: dict
"""
if results['password'] is None:
results['password'] = getpass.getpass(prompt="PASSWORD: ")
return results | b0ea947af703d7c90e124c1d0ecabbd1e6216e15 | 696,229 |
from pathlib import Path
def is_single_repository(repo_path: str) -> bool:
"""
This function returns True if repo_path points to a single repository (regular or bare) rather than a
folder containing multiple repositories.
"""
# For regular repositories
if Path("{}/.git".format(repo_path))... | c9b2c709984b79a36c36d898d0e337d7a9c3f725 | 696,230 |
def requires_to_requires_dist(requirement):
"""Compose the version predicates for requirement in PEP 345 fashion."""
requires_dist = []
for op, ver in requirement.specs:
requires_dist.append(op + ver)
if not requires_dist:
return ''
return " (%s)" % ','.join(sorted(requires_dist)) | 1a394de51d18b0a3cc4cb922364d352a29bccb09 | 696,231 |
def load_cows(filename):
"""
Read the contents of the given file. Assumes the file contents contain
data in the form of comma-separated cow name, weight pairs, and return a
dictionary containing cow names as keys and corresponding weights as values.
Parameters:
filename - the name of the data ... | 6245d9f20791316e5e7f370a8d53d8d590ff87c7 | 696,232 |
import math
def create_space(lat, lon, s=10):
"""Creates a s km x s km square centered on (lat, lon)"""
v = (180/math.pi)*(500/6378137)*s # roughly 0.045 for s=10
return lat - v, lon - v, lat + v, lon + v | 7f39942cdb65a274ebf77257941211fa59f7cf89 | 696,233 |
import numpy
def aperture(npix=256, cent_obs=0.0, spider=0):
"""
Compute the aperture image of a telescope
Args:
npix (int, optional): number of pixels of the aperture image
cent_obs (float, optional): central obscuration fraction
spider (int, optional): spider size in pixels
Returns:
... | 6ca52e89c50d8ca57416740378231c859e70d8de | 696,234 |
def compose_tweet(media_id=None, data={}):
""" writes tweet """
if data['status'] == 'tweeted':
status = '.@{} tweeted @ {} (#{})'.format(data['user'], data['timestamp'], data['tweet_id'])
elif data['status'] in ['retweeted', 'replied to']:
status = '.@{} {} @{} @ {} (#{})'.format(data['us... | 3da320190446637a84b15c5e5b9084c0d08d52b2 | 696,235 |
def s_interp(sAvg,xeAvg,deltaP):
"""
Searches for value to interpolate for s vs 1/H, relationships as described
by Ambwain and Fort Jr., 1979.
sAvg = float - average s value over two halves of droplet
xeAvg = float - average xe value over two halves of droplet
"""
if sAvg >= .9:
... | 4bc8424c026ab03d4e6ed046966c16275450743a | 696,236 |
import math
def count_taxes(common, precious, mineral, nether):
"""
Conta quanti IC devono essere pagati per quelle api
"""
total = 0
common_category = math.ceil(common/15)
precious_category = math.ceil(precious/15)
mineral_category = math.ceil(mineral/15)
nether_category = math.ceil(... | b310cee73ae978c2698335a59bd8548012ab0da3 | 696,237 |
import random
def uniqueof20(k, rep=10000):
"""Sample k times out of alphabet, how many different?"""
alphabet = 'ACDEFGHIKLMNPQRSTVWY'
reps = [len(set(random.choice(alphabet)
for i in range(k)))
for j in range(rep)]
return sum(reps) / len(reps) | 349f1bd964419585df46e13d3cde64d8f5a42c86 | 696,238 |
import itertools
import glob
import os
def find_strings_files():
"""Return the paths of the strings source files."""
return itertools.chain(
glob.iglob("strings*.json"), glob.iglob(f"*{os.sep}strings*.json")
) | 24324d092d773ceafc7b5f5c3e73edb114c00f58 | 696,239 |
def policy_name_as_regex(policy_name):
"""Get the correct policy name as a regex
(e.g. OOF_HAS_vCPE.cloudAttributePolicy ends up in policy as OOF_HAS_vCPE.Config_MS_cloudAttributePolicy.1.xml
So, for now, we query it as OOF_HAS_vCPE..*aicAttributePolicy.*)
:param policy_name: Example: OOF_HAS_vCPE.aicAt... | 5b60a6f35a30af5f3514a43c24c7bee25505adfb | 696,240 |
import struct
def int2hexstr(num, intsize=4):
"""
Convert a number to hexified string
"""
if intsize == 8:
if num < 0:
result = struct.pack("<q", num)
else:
result = struct.pack("<Q", num)
else:
if num < 0:
result = struct.pack("<l", num)... | bafdd3960a42a48b6b1ce689fb4b9455643388f9 | 696,241 |
def get_primary_key_params(obj):
"""
generate a dict from a mapped object suitable for formatting a primary key logline
"""
params = {}
for key in obj.__table__.primary_key.columns.keys():
params[key] = getattr(obj, key)
return params | aad247b31925389bca21ef35fc6416c286587eee | 696,243 |
def mean(numbers):
"""Return the arithmetic mean of a list of numbers"""
return float(sum(numbers)) / float(len(numbers)) | 26601c23b8b6af48895a43f6e596e25eb626e7d6 | 696,245 |
def PySelectCoins_MultiInput_SingleValue( \
unspentTxOutInfo, targetOutVal, minFee=0):
"""
This method should usually be called with a small number added to target val
so that a tx can be constructed that has room for user to add some extra fee
if necessary.
However, ... | c882a720b56c988ecd9d595b4778451cab8e298b | 696,246 |
def annual_Norm(dataframe):
"""This is a function that calculateing the annual production of the panel
Args:
dataframe(string):The name of the dataframe you want to adjust
Returns:
annual_values(list): the sum of the past 12 months energy production
mon... | 13c811f49f86c2514052defad39b96ad6689df47 | 696,247 |
def margined(arr, prop):
"""Returns (min(arr) - epsilon, max(arr) - epsilon), where
epsilon = (max(arr) - min(arr)) * prop. This gives the range of
values within arr along with some margin on the ends.
ARR: a NumPy array
PROP: a float"""
worst = arr.min()
best = arr.max()
margin ... | 65ea4e99453ae300b08094f1891a31cca3d302bd | 696,248 |
import requests
def framework_check(pypi_url: str) -> str:
"""
7. Are the tests running with the latest Integration version?
"""
response = requests.get(pypi_url).json()
classifiers = response.get("info").get("classifiers")
frameworks = [s.replace("Framework Django", "Framework").replace(" ::"... | dd268cf19eedd885c4723cb635d9a55540524e0b | 696,249 |
def faceAreaE3(face):
"""Computes the area of a triangular DCEL face with vertex coordinates given
as PointE3 objects.
Args:
face: A triangular face of a DCEL with vertex .data given by PointE3 objects.
Returns:
The area of the triangular face.
"""
p0, p1, p2... | 412031297213a702f0579f8c86c23c93baaff8c8 | 696,250 |
import asyncio
def get_active_loop() -> asyncio.AbstractEventLoop:
"""returns the current active asyncio loop or creates
a new one.
Returns:
asyncio.AbstractEventLoop
"""
loop = asyncio.events._get_running_loop()
loop = asyncio.new_event_loop() if loop is None else loop
return loo... | 42c15961326d2a5a372237a8455fbe4f292dff80 | 696,251 |
def gen_datavalue_list(soup):
"""Create a list of all the datavalues on the BLS EAG webpage."""
datavalue_list_soup = soup.findAll('span', 'datavalue')
datavalue_list = []
for datavalue in datavalue_list_soup:
datavalue_list.append(datavalue.text)
return datavalue_list | 8901511f0f65945c200b2ccc77d4cb011da41453 | 696,252 |
def bet_size_sigmoid(w_param, price_div):
"""
Part of SNIPPET 10.4
Calculates the bet size from the price divergence and a regulating coefficient.
Based on a sigmoid function for a bet size algorithm.
:param w_param: (float) Coefficient regulating the width of the bet size function.
:param pric... | cbc6c8d70f6f000e701f140ccbae34b55d7a46df | 696,253 |
import re
def slugify(text):
"""
Returns a slug of given text, normalizing unicode data for file-safe
strings. Used for deciding where to write images to disk.
Parameters
----------
text : string
The string to slugify
Returns
-------
slug : string
A normalized slu... | 8ac550ed32627a6c8a145b9442960e064ebd44e2 | 696,254 |
def flight_time_movies_1_brute_force(movie_lengths, flight_length):
"""
Solution: Brute force iterative solution compares each movie length with
all subsequent movie lengths.
Complexity:
Time: O(n^2)
Space: O(1)
"""
if len(movie_lengths) < 2:
raise ValueError('movie length list must be at least 2 items long... | 612825507cf1aea086bcfa37b702e6a778d85b7c | 696,256 |
from datetime import datetime
def datetime_type(string):
""" Validates UTC datetime. Examples of accepted forms:
2017-12-31T01:11:59Z,2017-12-31T01:11Z or 2017-12-31T01Z or 2017-12-31 """
accepted_date_formats = ['%Y-%m-%dT%H:%M:%SZ', '%Y-%m-%dT%H:%MZ', '%Y-%m-%dT%HZ', '%Y-%m-%d']
for form in accepted... | 36acb1d83b38310c463b2376fa2284fb6e9ad73e | 696,257 |
import re
def _remove_line_end_ellipsis_or_pass_keyword(line: str) -> str:
"""
Remove ellipsis or pass keyword from end of line
(e.g., `def sample_func(): ...` or `def sample_func(): pass`).
Parameters
----------
line : str
Target line string.
Returns
-------
result_line ... | 5ff12264670184737b2d9cc69f9fb2d8eca66cd9 | 696,258 |
import re
def parse_p0f_entry(entry) :
""" converts p0f log entry to dict object and returns """
# date data
r = re.compile(r'\[(\d{4}/\d{2}/\d{2} \d{2}:\d{2}:\d{2})\] (.+)')
match = r.match(entry)
# valid date format as extra validity check
if match is None :
return
datetime = match.... | 7f16d7bf7a42290ec76aa427fab678cdf02bd759 | 696,259 |
def check_dup(items_, items2_):
"""
check for duplicates in lists
"""
result = {}
for item in items_:
is_dup = False
for item2 in items2_:
if item.lower() == item2.lower():
is_dup = True
if not is_dup:
result[item] = item
return lis... | 34c8100a6e090404fee8615a9dd0e4c52f6c69a0 | 696,260 |
def get_count(input_str: str) -> int:
"""
Função responsável por fazer a contagem de vogais em uma palavra
"""
num_vowels = 0
lista = [i for i in input_str if i in 'aeiou']
num_vowels = len(lista)
return num_vowels | ae175e1dc24f655685d62d9ab955f8252427d14d | 696,261 |
def i_to_r(i, L, dx):
"""Return coordinates of lattice indices in continuous space.
Parameters
----------
i: integer array, shape (a1, a2, ..., d)
Integer indices, with last axis indexing the dimension.
It's assumed that all components of the vector
lie within plus or minus (L /... | 3c9f6ecc87a5220d487b434873f63c04f9933720 | 696,262 |
def _process_for_token(request):
"""
Checks for tokens in formdata without prior knowledge of request method
For now, returns whether the userid and token formdata variables exist, and
the formdata variables in a hash. Perhaps an object is warranted?
"""
# retrieve the formdata variables
if... | 14088de395c977ce6a59da3384fa8d49b213e791 | 696,263 |
def evaluate_score(rate, level):
"""
基金评分标准
基金和基准差值在[-1,1] 之间评分为 0,和基准表现相似,平庸
基金和基准差值在(1,5) 之间评分为 1,基本跑赢标准,及格
基金和基准差值在(5,10) 之间评分为 2,基本跑赢标准,优良
基金和基准差值在(10,20)之间评分为 3,基本跑赢标准,
基金和基准差值在(20 +) 评分为 4,基本跑赢标准,优秀
:param rate: 基金表现
:param level: 基准表现
:return: 返回评分
"""
diff = ra... | e3607f7a51f6fc4b68938257b6e793f281939b02 | 696,264 |
def make_response(error, message=None, image_base64=None):
"""
Generates the ObjectCut JSON response.
:param error: True if the response has to be flagged as error, False otherwise.
:param message: Message to return if it is a error response.
:param image_base64: Image result encoded in base64 if it... | 3be80141811fa493441a1ab964b4b6014a183dd1 | 696,265 |
def _cut(match):
"""
Cut matched characters from the searched string.
Join the remaining pieces with a space.
"""
string, start, end = match.string, match.start(), match.end()
if start == 0:
return string[end:]
if end == len(string):
return string[:start]
return ' '.join(... | 5a9b1ac7a4030b972d14b04c81acb343066b3f2b | 696,266 |
def parse_metadata_words(language='english', quality='low'):
"""
Identifies words corresponding to different metadata in the language
Parameters:
-----------------------------------
language : str
Name of the language whose testing data to fetch
quality : str
size of the dataset ... | 7b8430c3e9c553167e5d710ef5e1d0ddaaeded00 | 696,267 |
def make_set(labels):
"""
Create a new equivalence class and return its class label
"""
labels[0] += 1
labels[labels[0]] = labels[0]
return labels[0].astype(int) | 68ce42228c59259f341ce3b16fd1a9811a486c6b | 696,268 |
import torch
def bitmap_precision_recall(output, target, threshold=0.5):
""" Computes the precision recall over execution bitmap given a interpretation threshold """
with torch.no_grad():
target_one = (target == 1)
# target_one_total = torch.sum(target_one).item()
output_pred_binary ... | cee0d3381bcb45c450832923dba274f7cb39164d | 696,269 |
def device(request):
"""
This fixture will be called once to return the existing Device instance
that was setup in the session start hook function.
"""
return request.config._nrfu.device | 6b7da9f5d3b62e21eff3509e539ba60713dc629b | 696,270 |
from typing import List
def split_list(lst: List[str], wanted_parts: int = 1) -> List[List[str]]:
""" Splits a list into a list of lists of each of size 'wanted_parts'
Args:
lst: List to be split into smaller parts
wanted_parts: Desired size of each smaller list
Returns:
... | 204711aa6b8c14c54673182e6d89addd8ccdc857 | 696,271 |
def merge_new_data(data, key, value):
""" key: cpu.utilization
value: {'avg': 1.3}
"""
item = key.split('.')
key1 = item[0] # cpu
key2 = item[1] # utilization
data1 = data.get(key1, {})
data2 = data1.get(key2, {})
data2.update(value)
data1[key2] = data2
data[key1] = dat... | 83bf41250d486e7de99ce7d78ddabdf3857850cc | 696,272 |
import os
def get_markdown_file_list(directory: str) -> list:
"""Return the list of Markdown files from
directory. Scan subdirectories too.
"""
file_list = []
for root, dirs, files in os.walk(directory):
for name in files:
if os.path.splitext(name)[1] == '.md':
... | cbb247228286b73cc8dc9eb6dd0d374030a2f063 | 696,273 |
def gamma_to_tau_hard_threshold(gamma):
"""Converts gamma to tau for hard thresholding
"""
return 0.5 * gamma ** 2 | 4034918244477182cd3d7a14b97710c0731e03e3 | 696,274 |
def supervisor_client(client, supervisor):
"""A client with a supervisor logged in"""
client.force_login(supervisor)
return client | 2991812b91eb04e7ec58d3ecf0cb8f89bc5f41fe | 696,275 |
def build_sample_map(flowcell):
"""Build sample map ``dict`` for the given flowcell."""
result = {}
rows = [(lane, lib["name"]) for lib in flowcell["libraries"] for lane in lib["lanes"]]
i = 1
for _, name in sorted(set(rows)):
if name not in result:
result[name] = "S{}".format(i)... | faf43ca65146093462ae26a9c18ebb238e23a7ff | 696,276 |
def get_reshaped_data(dataloader):
"""Reshape data to fit into DeepHistone Model
:param dataloader: HistoneDataset
:type dataloader: HistoneDataset wraped by torch.utils.data.DataLoader
"""
(x, y, gene_name) = next(iter(dataloader)) # this step is slow since it actually loads all data
x_histon... | 750c302898e423cf62002a1050e05171eafda26c | 696,277 |
def get_scan_dir_and_rsfwd(voc, ascending, r_diff, ncompliance):
"""Determine the scan direction and forward bias series resistance of a sweep.
Scan direction is dermined based on the sweep direction and sign of Voc. This may
fail for truly dark I-V sweeps that don't have a Voc.
Parameters
-------... | 9310397abd12ee7f3a176e22faea1c1c8d097994 | 696,278 |
def 더하기(a,b):
"""Returns the sum of a and b
>>> 더하기(1,2)
3
"""
return 0 | d528db54471b81050ccefe303ef2847dbc449618 | 696,279 |
def indent(
text, # Text to indent
char=' ', # Character to use in indenting
indent=2 # Repeats of char
):
"""
Indent single- or multi-lined text.
"""
prefix = char * indent
return "\n".join([prefix + s for s in text.split("\n")]) | f170745f99a2bb151e79c2f468cf23880d60b3e5 | 696,281 |
def first_element_or_none(element_list):
"""
Return the first element or None from an lxml selector result.
:param element_list: lxml selector result
:return:
"""
if element_list:
return element_list[0]
return | df9c3437f38a50db96f0f4f946ede41916e5e2cf | 696,282 |
def is_public(data, action):
"""Check if the record is fully public.
In practice this means that the record doesn't have the ``access`` key or
the action is not inside access or is empty.
"""
return "_access" not in data or not data.get("_access", {}).get(action) | 2c5c80f8e16014f08df2cc34696cea8249e633b1 | 696,283 |
def __slice_scov__(cov, dep, given):
"""
Slices a covariance matrix keeping only the covariances between the variables
indicated by the array of indices of the independent variables.
:param cov: Covariance matrix.
:param dep: Index of dependent variable.
:param given: Array of indices of indepen... | a5742c8dc4db245521477b0bf8c6ad8f3b463a2b | 696,286 |
def forward_pass(output_node, sorted_nodes):
"""
Performs a forward pass through a list of sorted nodes
Arguments:
'output_node'
'sorted_nodes'
Returns the output node's value
"""
for n in sorted_nodes:
n.forward()
return output_node.value | 7783878c99db24165141c61106ec4435f02e87a9 | 696,287 |
def _val(var, is_percent=False):
"""
Tries to determine the appropriate value of a particular variable that is
passed in. If the value is supposed to be a percentage, a whole integer
will be sought after and then turned into a floating point number between
0 and 1. If the value is supposed to be a... | b1525cd11d1fd385720f223f34cc5b5580410247 | 696,288 |
import re
def check_project_name(name: str):
"""project name example: flask_demo
:param name:
:return:
"""
match = re.match('^[a-zA-z]\w+', name)
if not match:
return False
if name != match.group():
return False
return True | 43cc39d4338c55c45dff27f120535ba855c14785 | 696,289 |
def blend_html_colour_to_white(html_colour, alpha):
"""
:param html_colour: Colour string like FF552B or #334455
:param alpha: Alpha value
:return: Html colour alpha blended onto white
"""
html_colour = html_colour.upper()
has_hash = False
if html_colour[0] == '#':
has_hash = Tru... | a65efec4ca165614b93d1e0654907ad14d087211 | 696,290 |
import random
import string
def rnd_string(n=10):
"""Generate a random string."""
return ''.join(random.SystemRandom().choice(string.ascii_uppercase + string.digits) for _ in range(n)) | 1869afa5e950c24d75a446c54b9f53abd942c007 | 696,291 |
def generate_data_for_plot_distribution(x_data, y_data):
"""
输出每个类别对应的数据的列表的字典
:param x_data: 类别数据列表
:param y_data: 数值型数据列表
:return: {类别:[数据列表]}的字典
"""
digit_data_dict = {}
for key, value in zip(x_data, y_data):
if key in digit_data_dict:
digit_data_dict[key].append(v... | b9e6851be47378ddcc2f5009fe20274080ef18f1 | 696,292 |
import subprocess
import os
import random
import string
def make_in_filename(cesar_in):
"""Make filename for the CESAR input."""
if cesar_in: # is defined by user
# cesar in - file addr, False --> to mark it is not temp
return cesar_in, False
# is not defined --> create a folder in dev sh... | cbe138787fbfb9f488c96c19361c3bcec7231bf1 | 696,293 |
from dill import pickles, copy
import sys
import sys
def errors(obj, depth=0, exact=False, safe=False):
"""get errors for objects that fail to pickle"""
if not depth:
try:
pik = copy(obj)
if exact:
assert pik == obj, \
"Unpickling produces %s... | f57ced20947d9f9ed446e2a139a4d07fd2b54c1a | 696,294 |
def replace_digraphs(word_):
"""Return the given word processed for orthographic changes.
Parameters
----------
word_ : str
Returns
-------
str
"""
word_ = word_.lower()
word_ = word_.replace('ch', 'S')
word_ = word_.replace('lh', 'L')
word_ = word_.replace('nh', 'N')
... | 991278e31d9beecd8d249af7d12f4e01ec87911a | 696,295 |
import itertools
def chain_generators(*sprite_generators):
"""Chain generators by concatenating output sprite sequences.
Essentially an 'AND' operation over sprite generators. This is useful when
one wants to control the number of samples from the modes of a multimodal
sprite distribution.
Note ... | a6f57b44957807429a1cb8f28e62a571a2cdeb0d | 696,296 |
def checkSlashes(item='', sl_char='/'):
"""\
This function will make sure that a URI begins with a slash and does not end
with a slash.
item - the uri to be checked
sl_char - the character to be considered a 'slash' for the purposes of this
function
"""
if not item.start... | 1ebca2ea2e43d1b795350ee3df893e42218c475f | 696,297 |
from typing import Any
from typing import Iterable
from typing import Optional
def find_in_list(element: Any, container: Iterable[Any]) -> Optional[Any]:
"""
If the element is in the container, return it.
Otherwise, return None
:param element: to find
:param container: container with element
:... | 4fd775e93472f466b90eb0c2ee4fda6aa6ead69e | 696,298 |
import collections
def _get_tasks_by_domain(tasks):
"""Returns a dict mapping from task name to a tuple of domain names."""
result = collections.defaultdict(list)
for domain_name, task_name in tasks:
result[domain_name].append(task_name)
return {k: tuple(v) for k, v in result.items()} | 53483e8ddf28490b6c00a4d456b77b48de1aeb7d | 696,299 |
def splitFrom(df, attr, val):
"""
Split DataFrame in two subset based on year attribute
:param df: DataFrame to split
:param attr: attribute on which split data
:param val: value of attribute where do split
:return: two subset
"""
if attr not in df.columns:
raise ValueError("****... | e2c4f0c03d4b15ec2915e22bb905d4202cdf66cb | 696,300 |
import sys
def check_env(env):
"""
Ensures all key and values are strings on windows.
"""
if sys.platform == "win32":
win_env = {}
for key, value in env.items():
win_env[str(key)] = str(value)
env = win_env
return env | 37a311fad6f84a1fbb239911d10661794db00041 | 696,301 |
import sys
import os
def argparse(argv):
"""Parse commandline arguments.
Expects input file path
"""
try:
inputfile = str(argv[1])
except:
error = argv[0] + " <inputfile>"
print(error)
sys.exit(2)
if os.path.isfile(inputfile):
print('Input file is', inpu... | bb27082b32df1abcba938bc031a721a4f9a11916 | 696,302 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.