source string | points list | n_points int64 | path string | repo string |
|---|---|---|---|---|
#
# pyip is a Python package offering assembling/disassembling of raw ip packet
# including ip, udp, and icmp. Also it includes 2 utilities based on raw ip,
# traceroute and ping.
#
# pyip is released under PYTHON SOFTWARE FOUNDATION LICENSE VERSION 2, and is
# a project inspired by 'ping' written by Jeremy Hylton.
#
# Author: Kenneth Jiang, kenneth.jiang@gmail.com
#
import sys ; sys.path.insert(0, '..')
import unittest
import ip
class ipSelfVerifyingTestCase(unittest.TestCase):
def setUp(self):
self.simple = ip.Packet()
self.simple.src = '127.0.0.1'
self.simple.dst = '0.0.0.0'
def testSimplePacket(self):
buf = ip.assemble(self.simple, 1)
new = ip.disassemble(buf, 1)
self.assertEqual(self.simple, new)
| [
{
"point_num": 1,
"id": "every_function_has_docstring",
"question": "Does every function in this file have a docstring?",
"answer": false
},
{
"point_num": 2,
"id": "has_multiple_inheritance",
"question": "Does any class in this file use multiple inheritance?",
"answer": false
... | 3 | test/iptests.py | koodaamo/pyip |
import torch
import torch.nn
from typing import Dict, Tuple
from models.encoder_decoder import add_eos
from models.transformer_enc_dec import TransformerResult
from ..model_interface import ModelInterface
import framework
from ..encoder_decoder import EncoderDecoderResult
class TransformerEncDecInterface(ModelInterface):
def __init__(self, model: torch.nn.Module, label_smoothing: float = 0.0):
self.model = model
self.label_smoothing = label_smoothing
def loss(self, outputs: TransformerResult, ref: torch.Tensor, mask: torch.Tensor) -> torch.Tensor:
l = framework.layers.cross_entropy(outputs.data, ref, reduction='none', smoothing=self.label_smoothing)
l = l.reshape_as(ref) * mask
l = l.sum() / mask.sum()
return l
def decode_outputs(self, outputs: EncoderDecoderResult) -> Tuple[torch.Tensor, torch.Tensor]:
return outputs.outputs, outputs.out_lengths
def __call__(self, data: Dict[str, torch.Tensor], train_eos: bool = True) -> EncoderDecoderResult:
in_len = data["in_len"].long()
out_len = data["out_len"].long()
in_with_eos = add_eos(data["in"], data["in_len"], self.model.encoder_eos)
out_with_eos = add_eos(data["out"], data["out_len"], self.model.decoder_sos_eos)
in_len += 1
out_len += 1
res = self.model(in_with_eos.transpose(0, 1), in_len, out_with_eos.transpose(0, 1),
out_len, teacher_forcing=self.model.training, max_len=out_len.max().item())
res.data = res.data.transpose(0, 1)
len_mask = ~self.model.generate_len_mask(out_with_eos.shape[0], out_len if train_eos else (out_len - 1)).\
transpose(0, 1)
loss = self.loss(res, out_with_eos, len_mask)
return EncoderDecoderResult(res.data, res.length, loss)
| [
{
"point_num": 1,
"id": "has_multiple_inheritance",
"question": "Does any class in this file use multiple inheritance?",
"answer": false
},
{
"point_num": 2,
"id": "every_function_has_docstring",
"question": "Does every function in this file have a docstring?",
"answer": false
... | 3 | interfaces/transformer/encoder_decoder_interface.py | lukovnikov/transformer_generalization |
from date_sniff.sniffer import DateSniffer
def test_years_separation():
sniffer = DateSniffer(year=2019)
assert sniffer.sniff('2019') == {'2019': []}
assert sniffer.sniff('prefix 2019 and long text') == {'prefix 2019 and long text': []}
res = {'prefix 2019 and long text another 2019': []}
assert sniffer.sniff('prefix 2019 and long text another 2019') == res
assert sniffer.sniff('2019 two 2019') == {'2019 two 2019': []}
def test_month_search():
sniffer = DateSniffer(year=2019, month=1)
assert sniffer.sniff('prefix 2019') == {}
assert sniffer.sniff('prefix January 2019') == {'prefix January 2019': []}
assert sniffer.sniff('prefix 2019-01-10') == {'prefix 2019-01-10': [10]}
sniffer = DateSniffer(year=2019, month=3)
res = sniffer.sniff('EXPANSION PLAN Germany Finland Denmark 2019 Norway Egypt UAE France Spain 2021')
assert res == {}
res = sniffer.sniff('EXPANSION PLAN Germany Finland March. 2019 Norway Egypt UAE France Spain 2021')
assert res == {'EXPANSION PLAN Germany Finland March. 2019 Norway Egypt UAE France Spain 2021': []}
def test_find_isolated():
sniffer = DateSniffer(year=2019, month=3)
res = sniffer.find_isolated('10', '2019-03-04 101')
assert res == []
def test_keyword_search():
sniffer = DateSniffer(year=2019, month=1, keyword='test')
assert sniffer.sniff('prefix 2019-01-10') == {}
print(sniffer.sniff('prefix 2019-01-10 test'))
assert sniffer.sniff('prefix 2019-01-10 test') == {'prefix 2019-01-10 test': [10]}
def test_days():
sniffer = DateSniffer(year=2019, month=3)
res = sniffer.sniff('2019-03-04 101')
assert res == {'2019-03-04 101': [4]}
| [
{
"point_num": 1,
"id": "every_function_has_docstring",
"question": "Does every function in this file have a docstring?",
"answer": false
},
{
"point_num": 2,
"id": "has_nested_function_def",
"question": "Does this file contain any function defined inside another function?",
"ans... | 3 | date_sniff/tests.py | nanvel/date-sniff |
# Logging level must be set before importing any stretch_body class
import stretch_body.robot_params
stretch_body.robot_params.RobotParams.set_logging_level("DEBUG")
import unittest
import stretch_body.lift
import time
class TestLift(unittest.TestCase):
def test_homing(self):
"""Test lift homes correctly.
"""
l = stretch_body.lift.Lift()
self.assertTrue(l.startup())
l.home()
l.push_command()
time.sleep(1)
l.pull_status()
self.assertAlmostEqual(l.status['pos'], 0.6, places=1)
l.stop()
def test_move_lift_with_soft_limits(self):
"""Ensure that soft limits actual clip range of motion.
"""
l = stretch_body.lift.Lift()
l.motor.disable_sync_mode()
self.assertTrue(l.startup())
l.pull_status()
if not l.motor.status['pos_calibrated']:
self.fail('test requires lift to be homed')
limit_pos = 0.8
l.set_soft_motion_limits(0,limit_pos)
l.push_command()
l.move_to(x_m=0.9)
l.push_command()
time.sleep(3.0)
l.pull_status()
self.assertAlmostEqual(l.status['pos'], limit_pos, places=1)
l.stop()
| [
{
"point_num": 1,
"id": "has_nested_function_def",
"question": "Does this file contain any function defined inside another function?",
"answer": false
},
{
"point_num": 2,
"id": "has_multiple_inheritance",
"question": "Does any class in this file use multiple inheritance?",
"answ... | 3 | body/test/test_lift.py | soumith/stretch_body |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Feb 2 18:34:05 2020
@author: leemshari
"""
# I wanted to create an n cubed icon
#My goal was to get this to get this to print with & or @ signs but I was unable to
#get this array to look decent with anything but integers.
#I changed the dtype to str and the int_array[a,b] to @ but the array would be off
import numpy as np
#function to pass in an array and tuple so that we can get image
def icon (tuple_list,int_array):
#tuple is basically coordinates for the image to populate in
for a,b in tuple_list:
#I set the value that will populated at the coordinates to 3
int_array[a,b] = 3
return int_array
#function to manipulate arrary and elements in it
def roll_rotate(a_tuple,a_array):
#We want the array with the image to rotate and roll
b_array = icon(a_tuple,a_array)
#Numpy has different functions already built into it to manipulate arrays
print(np.roll(b_array,1))
print('')
print(np.flipud(b_array))
#Inention was to scale array up to 15x15 array
def resize(b_tuple,b_array):
#Need to grab image again so that it can be manipulated
c_array = icon(b_tuple,b_array)
#Output makes the icon unreadable unfortunately but this numpy function will make it bigger
print(np.resize(c_array,(15,15)))
def main():
#Tuple that will be passed into the functions above
image = ((0,6),(0,7),(0,8),(1,8),(2,7),(2,8),(3,8),(4,1),(4,6),(4,7),(4,8),
(5,1),(5,2),(5,3),(5,4),(5,5),(6,1),(6,5),(7,1),(7,5),(8,1),(8,5),(9,1),(9,5))
#Array full of zeros that will be populated with 3s at correct coordinates
image_array = np.zeros((10,10), dtype = int)
#printing image with tuple and array passed in
print(icon(image,image_array))
print('')
#Calling function to manipulate array
roll_rotate(image,image_array)
print('')
#Calling function to scale array up
resize(image,image_array)
main()
| [
{
"point_num": 1,
"id": "every_function_under_20_lines",
"question": "Is every function in this file shorter than 20 lines?",
"answer": true
},
{
"point_num": 2,
"id": "all_params_annotated",
"question": "Does every function parameter in this file have a type annotation (excluding se... | 3 | icon.py | ccacNMorris/dat129_ccac |
from pypy.rpython.test.test_llinterp import gengraph, interpret
from pypy.rlib import rgc # Force registration of gc.collect
import gc
def test_collect():
def f():
return gc.collect()
t, typer, graph = gengraph(f, [])
ops = list(graph.iterblockops())
assert len(ops) == 1
op = ops[0][1]
assert op.opname == 'gc__collect'
res = interpret(f, [])
assert res is None
| [
{
"point_num": 1,
"id": "every_function_has_docstring",
"question": "Does every function in this file have a docstring?",
"answer": false
},
{
"point_num": 2,
"id": "has_nested_function_def",
"question": "Does this file contain any function defined inside another function?",
"ans... | 3 | pypy/rlib/test/test_rgc.py | camillobruni/pygirl |
from checkov.common.models.enums import CheckResult, CheckCategories
from checkov.arm.base_resource_value_check import BaseResourceValueCheck
# https://docs.microsoft.com/en-us/azure/templates/microsoft.web/2019-08-01/sites
class AXA_VirtualMachineExists(BaseResourceValueCheck):
def __init__(self):
name = "Virtual Machines are not permitted in AXA's Azure Cloud environment."
id = "AXA_AZURE_1"
supported_resources = ['*']
categories = [CheckCategories.GENERAL_SECURITY]
super().__init__(name=name, id=id, categories=categories, supported_resources=supported_resources,
missing_block_result=CheckResult.FAILED)
def scan_resource_conf(self, conf):
inspected_key = self.get_inspected_key()
expected_values = self.get_expected_values()
if inspected_key in conf.keys():
if conf[inspected_key] in expected_values:
return CheckResult.FAILED
def get_inspected_key(self):
return 'type'
def get_expected_value(self):
return 'Microsoft.Compute/virtualMachines'
check = AXA_VirtualMachineExists()
| [
{
"point_num": 1,
"id": "all_function_names_snake_case",
"question": "Are all function names in this file written in snake_case?",
"answer": true
},
{
"point_num": 2,
"id": "more_functions_than_classes",
"question": "Does this file define more functions than classes?",
"answer": ... | 3 | checkov/arm/checks/resource/AXA_VirtualMachineExists.py | kn0wm4d/checkov |
from turtle import Turtle
class Ball(Turtle):
def __init__(self):
super().__init__()
self.penup()
self.shape("circle")
self.color("white")
self.speed("slowest")
self.x_move = 10
self.y_move = 10
def move(self):
new_x = self.xcor() + self.x_move
new_y = self.ycor() + self.y_move
self.goto(new_x, new_y)
def bounce(self):
self.y_move *= -1
def paddle_hit(self):
self.x_move *= -1
self.speed_up()
def reset_pos(self):
self.paddle_hit()
self.goto(0,0)
self.x_move = 3
def speed_up(self):
if self.x_move > 0:
self.x_move += 0.5
else:
self.x_move -= 0.5 | [
{
"point_num": 1,
"id": "all_function_names_snake_case",
"question": "Are all function names in this file written in snake_case?",
"answer": true
},
{
"point_num": 2,
"id": "all_return_types_annotated",
"question": "Does every function in this file have a return type annotation?",
... | 3 | 100_days_of_code/Intermediate/day_22/ball.py | Tiago-S-Ribeiro/Python-Pro-Bootcamp |
'''HDF5 operating system operations.
license: HDF5Application/license.txt
Main authors:
Philipp Bucher
Michael Andre
'''
import KratosMultiphysics
import KratosMultiphysics.kratos_utilities as _utils
import os
class DeleteOldH5Files(object):
'''Delete h5-files from previous simulations.'''
def __call__(self, model_part, hdf5_file):
file_path, file_name = os.path.split(hdf5_file.GetFileName())
time_prefix = file_name.replace(".h5", "") + "-"
current_time = model_part.ProcessInfo[KratosMultiphysics.TIME]
if file_path == "":
file_path = "." # os.listdir fails with empty path
for name in os.listdir(file_path):
if name.startswith(time_prefix):
file_time = float(name.replace(".h5", "")[len(time_prefix):])
if file_time > current_time:
_utils.DeleteFileIfExisting(
os.path.join(file_path, name))
def Create(settings):
'''Return an operation specified by the setting's 'operation_type'.
This method is normally not used directly, but rather it is imported
in core.operations.model_part.Create using the 'module_name' setting.
'''
operation_type = settings['operation_type'].GetString()
if operation_type == 'delete_old_h5_files':
return DeleteOldH5Files()
else:
raise ValueError(
'"operation_type" has invalid value "' + operation_type + '"')
| [
{
"point_num": 1,
"id": "no_function_exceeds_5_params",
"question": "Does every function in this file take 5 or fewer parameters (excluding self/cls)?",
"answer": true
},
{
"point_num": 2,
"id": "every_function_has_docstring",
"question": "Does every function in this file have a docs... | 3 | applications/HDF5Application/python_scripts/core/operations/system.py | Jacklwln/Kratos |
from flask import g
from flask_httpauth import HTTPBasicAuth, HTTPTokenAuth
from app.models import User
from app.api.v1.errors import error_response
basic_auth = HTTPBasicAuth()
token_auth = HTTPTokenAuth()
@basic_auth.verify_password
def verify_passowrd(username, password):
"""Receives username and password from client, and returns True if the
password is valid for the username.
"""
user = User.query.filter_by(username=username.lower().strip()).first()
if user is None:
return False
g.current_user = user
return user.check_password(password)
@basic_auth.error_handler
def basic_auth_error():
return error_response(401)
@token_auth.verify_token
def verify_token(token):
"""Return True if the provided token belongs to an existing user"""
g.current_user = User.check_token(token) if token else None
return g.current_user is not None
@token_auth.error_handler
def token_auth_error():
return error_response(401)
| [
{
"point_num": 1,
"id": "no_function_exceeds_5_params",
"question": "Does every function in this file take 5 or fewer parameters (excluding self/cls)?",
"answer": true
},
{
"point_num": 2,
"id": "all_params_annotated",
"question": "Does every function parameter in this file have a ty... | 3 | app/api/v1/auth.py | camisatx/flasker |
"""
Make yaml respect OrderedDicts and stop sorting things
"""
from collections import OrderedDict
import sys
import yaml
_items = 'viewitems' if sys.version_info < (3,) else 'items'
def map_representer(dumper, data):
return dumper.represent_dict(getattr(data, _items)())
def map_constructor(loader, node): # pragma: nocover (python 3.6 doesn't use it)
loader.flatten_mapping(node)
return OrderedDict(loader.construct_pairs(node))
yaml.add_representer(dict, map_representer)
yaml.add_representer(OrderedDict, map_representer)
if sys.version_info < (3, 6): # pragma: nocover
yaml.add_constructor('tag:yaml.org,2002:map', map_constructor)
| [
{
"point_num": 1,
"id": "all_params_annotated",
"question": "Does every function parameter in this file have a type annotation (excluding self/cls)?",
"answer": false
},
{
"point_num": 2,
"id": "every_function_has_docstring",
"question": "Does every function in this file have a docst... | 3 | crosscap/yamlhack.py | corydodt/Crosscap |
#!/usr/bin/env python
## @package teleop_joy A node for controlling the P3DX with an XBox controller
import rospy
from geometry_msgs.msg import Twist
from nav_msgs.msg import Odometry
from sensor_msgs.msg import Joy
import numpy as np
def quat2yaw(q):
return np.arctan2(2*(q.y*q.z + q.w*q.x), 1 - 2*(q.z**2 + q.w**2))
def joyCallback(msg):
global cmd_vel_pub
global linear_axis
global linear_scale
global rotation_axis
global rotation_scale
global yaw
cmd_vel_msg = Twist()
cmd_vel_msg.linear.x = msg.axes[linear_axis] * linear_scale
cmd_vel_msg.angular.z = msg.axes[rotation_axis] * rotation_scale
cmd_vel_msg.angular.y = np.inf
cmd_vel_pub.publish(cmd_vel_msg)
if __name__ == '__main__':
rospy.init_node('teleop_joy')
global cmd_vel_pub
global linear_axis
global linear_scale
global rotation_axis
global rotation_scale
global yaw
linear_axis = rospy.get_param('linear_axis' , 1)
linear_scale = rospy.get_param('linear_scale' , 5)
rotation_axis = rospy.get_param('rotation_axis' , 3)
rotation_scale = rospy.get_param('rotation_scale', 1)
cmd_vel_pub = rospy.Publisher("/asv/cmd_vel", Twist, queue_size=1)
rospy.Subscriber("joy", Joy, joyCallback)
rospy.spin()
| [
{
"point_num": 1,
"id": "every_function_has_docstring",
"question": "Does every function in this file have a docstring?",
"answer": false
},
{
"point_num": 2,
"id": "every_function_under_20_lines",
"question": "Is every function in this file shorter than 20 lines?",
"answer": tru... | 3 | nodes/teleop_joy.py | Lovestarni/asv_simulator |
import numpy as np
from metaworld.policies.action import Action
from metaworld.policies.policy import Policy, assert_fully_parsed, move
class SawyerCoffeePullV2Policy(Policy):
@staticmethod
@assert_fully_parsed
def _parse_obs(obs):
return {
'hand_pos': obs[:3],
'mug_pos': obs[3:6],
'unused_info': obs[6:],
}
def get_action(self, obs):
o_d = self._parse_obs(obs)
action = Action({
'delta_pos': np.arange(3),
'grab_effort': 3
})
action['delta_pos'] = move(o_d['hand_pos'], to_xyz=self._desired_pos(o_d), p=10.)
action['grab_effort'] = self._grab_effort(o_d)
return action.array
@staticmethod
def _desired_pos(o_d):
pos_curr = o_d['hand_pos']
pos_mug = o_d['mug_pos'] + np.array([-.005, .0, .05])
if np.linalg.norm(pos_curr[:2] - pos_mug[:2]) > 0.06:
return pos_mug + np.array([.0, .0, .15])
elif abs(pos_curr[2] - pos_mug[2]) > 0.02:
return pos_mug
elif pos_curr[1] > .65:
return np.array([.5, .6, .1])
else:
return np.array([pos_curr[0] - .1, .6, .1])
@staticmethod
def _grab_effort(o_d):
pos_curr = o_d['hand_pos']
pos_mug = o_d['mug_pos'] + np.array([.01, .0, .05])
if np.linalg.norm(pos_curr[:2] - pos_mug[:2]) > 0.06 or \
abs(pos_curr[2] - pos_mug[2]) > 0.1:
return -1.
else:
return .7
| [
{
"point_num": 1,
"id": "every_function_under_20_lines",
"question": "Is every function in this file shorter than 20 lines?",
"answer": true
},
{
"point_num": 2,
"id": "has_multiple_inheritance",
"question": "Does any class in this file use multiple inheritance?",
"answer": false... | 3 | metaworld/policies/sawyer_coffee_pull_v2_policy.py | rmrafailov/metaworld |
# -*- coding: utf-8 -*-
"""Flask extension pacakge for Sendgrid"""
from . import FlaskExtension
from sendgrid import SendGridClient, Mail
class SendGrid(FlaskExtension):
"""A helper class for managing a the SendGrid API calls"""
EXTENSION_NAME = 'sendgrid'
def __init__(self, app=None):
super(SendGrid, self).__init__(app=app)
def _create_instance(self, app):
client = SendGridClient(
app.config.get('SENDGRID_USERNAME'),
app.config.get('SENDGRID_PASSWORD'))
return client
def send_mail(self, body=None, subject=None, recipient=None, sender=None):
"""Sends an email"""
mail = Mail(to=recipient,
from_email=sender,
subject=subject,
text=body)
self.instance.send(mail)
| [
{
"point_num": 1,
"id": "all_params_annotated",
"question": "Does every function parameter in this file have a type annotation (excluding self/cls)?",
"answer": false
},
{
"point_num": 2,
"id": "has_multiple_inheritance",
"question": "Does any class in this file use multiple inherita... | 3 | yoapi/extensions/flask_sendgrid.py | YoApp/yo-api |
import numpy as np
import os
import shutil
import sys
from torch.utils.tensorboard import SummaryWriter
import torch
def model_input(data, device):
datum = data.data[0:1]
if isinstance(datum, np.ndarray):
return torch.from_numpy(datum).float().to(device)
else:
return datum.float().to(device)
def get_script():
py_script = os.path.basename(sys.argv[0])
return os.path.splitext(py_script)[0]
def get_specified_params(hparams):
keys = [k.split("=")[0][2:] for k in sys.argv[1:]]
specified = {k: hparams[k] for k in keys}
return specified
def make_hparam_str(hparams, exclude):
return ",".join([f"{key}_{value}"
for key, value in sorted(hparams.items())
if key not in exclude])
class Logger(object):
def __init__(self, logdir):
if logdir is None:
self.writer = None
else:
if os.path.exists(logdir) and os.path.isdir(logdir):
shutil.rmtree(logdir)
self.writer = SummaryWriter(log_dir=logdir)
def log_model(self, model, input_to_model):
if self.writer is None:
return
self.writer.add_graph(model, input_to_model)
def log_epoch(self, epoch, train_loss, train_acc, test_loss, test_acc, epsilon=None):
if self.writer is None:
return
self.writer.add_scalar("Loss/train", train_loss, epoch)
self.writer.add_scalar("Loss/test", test_loss, epoch)
self.writer.add_scalar("Accuracy/train", train_acc, epoch)
self.writer.add_scalar("Accuracy/test", test_acc, epoch)
if epsilon is not None:
self.writer.add_scalar("Acc@Eps/train", train_acc, 100*epsilon)
self.writer.add_scalar("Acc@Eps/test", test_acc, 100*epsilon)
def log_scalar(self, tag, scalar_value, global_step):
if self.writer is None or scalar_value is None:
return
self.writer.add_scalar(tag, scalar_value, global_step)
| [
{
"point_num": 1,
"id": "has_multiple_inheritance",
"question": "Does any class in this file use multiple inheritance?",
"answer": false
},
{
"point_num": 2,
"id": "every_function_under_20_lines",
"question": "Is every function in this file shorter than 20 lines?",
"answer": true... | 3 | log.py | skat00sh/Handcrafted-DP |
import os
import sys
from robotframework_ls.impl.robot_lsp_constants import (
ENV_OPTION_ROBOT_LSP_DEBUG_PROCESS_ENVIRON,
ENV_OPTION_ROBOT_LSP_DEBUG_MESSAGE_MATCHERS,
)
def _is_true_in_env(env_key):
return os.getenv(env_key, "") in ("1", "True", "true")
class Options(object):
tcp = False
host = "127.0.0.1"
port = 1456
log_file = None
verbose = 0
DEBUG_MESSAGE_MATCHERS = _is_true_in_env(
ENV_OPTION_ROBOT_LSP_DEBUG_MESSAGE_MATCHERS
)
DEBUG_PROCESS_ENVIRON = _is_true_in_env(ENV_OPTION_ROBOT_LSP_DEBUG_PROCESS_ENVIRON)
def __init__(self, args=None):
"""
:param args:
Instance with options to set (usually args from configparser).
"""
if args is not None:
for attr in dir(self):
if not attr.startswith("_"):
if hasattr(args, attr):
setattr(self, attr, getattr(args, attr))
class Setup(object):
# After parsing args it's replaced with the actual setup.
options = Options()
# Note: set to False only when debugging.
USE_TIMEOUTS = True
if "GITHUB_WORKFLOW" not in os.environ:
if "pydevd" in sys.modules:
USE_TIMEOUTS = False
NO_TIMEOUT = None
DEFAULT_TIMEOUT = 10
| [
{
"point_num": 1,
"id": "has_multiple_inheritance",
"question": "Does any class in this file use multiple inheritance?",
"answer": false
},
{
"point_num": 2,
"id": "every_function_has_docstring",
"question": "Does every function in this file have a docstring?",
"answer": false
... | 3 | src/robotframework_ls/options.py | Snooz82/robotframework-lsp |
#!/usr/bin/env python
import codecs
import os.path
import re
from setuptools import setup, find_packages
here = os.path.abspath(os.path.dirname(__file__))
def read(*parts):
return codecs.open(os.path.join(here, *parts), "r", encoding="utf-8").read()
def find_version(*file_paths):
version_file = read(*file_paths)
version_match = re.search(r"^__version__ = ['\"]([^'\"]*)['\"]", version_file, re.M)
if version_match:
return version_match.group(1)
raise RuntimeError("Unable to find version string.")
requires = ["awscrt==0.11.15"]
setup(
name="amazon-transcribe",
version=find_version("amazon_transcribe", "__init__.py"),
description="Async Python SDK for Amazon Transcribe Streaming",
long_description=open("README.md", "r", encoding="utf-8").read(),
long_description_content_type='text/markdown',
author="Amazon Web Services",
url="https://github.com/awslabs/amazon-transcribe-streaming-sdk",
scripts=[],
packages=find_packages(exclude=["tests*"]),
include_package_data=True,
install_requires=requires,
extras_require={},
license="Apache License 2.0",
classifiers=[
"Development Status :: 2 - Pre-Alpha",
"Intended Audience :: Developers",
"Intended Audience :: System Administrators",
"Natural Language :: English",
"License :: OSI Approved :: Apache Software License",
"Programming Language :: Python",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.6",
"Programming Language :: Python :: 3.7",
"Programming Language :: Python :: 3.8",
],
)
| [
{
"point_num": 1,
"id": "every_function_under_20_lines",
"question": "Is every function in this file shorter than 20 lines?",
"answer": true
},
{
"point_num": 2,
"id": "every_function_has_docstring",
"question": "Does every function in this file have a docstring?",
"answer": fals... | 3 | setup.py | gonzaloarro/amazon-transcribe-streaming-sdk |
import math
import time
t1 = time.time()
def digt(num):
n = num
digt = 0
while n > 0:
digt += n%10
n = n//10
return digt
temp = []
for i in range(2,200):
for j in range(2,50-i//10):
t = round(math.pow(i,j))
if digt(t) == i:
temp.append(t)
def quickSort(L, low, high):
i = low
j = high
if i >= j:
return L
key = L[i]
while i < j:
while i < j and L[j] >= key:
j = j-1
L[i] = L[j]
while i < j and L[i] <= key:
i = i+1
L[j] = L[i]
L[i] = key
quickSort(L, low, i-1)
quickSort(L, j+1, high)
return L
temp = quickSort(temp,0,len(temp)-1)
i = 0
l = temp[0]
n = 1
while n < 30:
i += 1
if l != temp[i]:
l = temp[i]
n += 1
print(temp[i])
print("time:",time.time()-t1)
| [
{
"point_num": 1,
"id": "every_function_has_docstring",
"question": "Does every function in this file have a docstring?",
"answer": false
},
{
"point_num": 2,
"id": "all_params_annotated",
"question": "Does every function parameter in this file have a type annotation (excluding self/... | 3 | Problem 001-150 Python/pb119.py | Adamssss/projectEuler |
from selenium import webdriver
from fixture.session import SessionHelper
from fixture.group import GroupHelper
from fixture.contact import ContactHelper
class Application:
def __init__(self, browser, base_url):
if browser == "firefox":
self.wd = webdriver.Firefox(capabilities={"marionette": False})
elif browser == "chrome":
self.wd = webdriver.Chrome()
elif browser == "ie":
self.wd = webdriver.Ie()
else:
raise ValueError("Unrecognized browser %s" % browser)
# self.wd.implicitly_wait(5)
self.session = SessionHelper(self)
self.group = GroupHelper(self)
self.contact = ContactHelper(self)
self.base_url = base_url
def is_valid(self):
try:
self.wd.current_url
return True
except:
return False
def open_home_page(self):
wd = self.wd
if len(wd.find_elements_by_name(name="searchstring"))>0:
return
wd.get(self.base_url)
def destroy(self):
self.wd.quit()
| [
{
"point_num": 1,
"id": "all_function_names_snake_case",
"question": "Are all function names in this file written in snake_case?",
"answer": true
},
{
"point_num": 2,
"id": "has_multiple_inheritance",
"question": "Does any class in this file use multiple inheritance?",
"answer": ... | 3 | fixture/application.py | Dansmael/python_training |
from fetchcode.vcs.pip._vendor.pkg_resources import yield_lines
from fetchcode.vcs.pip._vendor.six import ensure_str
from fetchcode.vcs.pip._internal.utils.typing import MYPY_CHECK_RUNNING
if MYPY_CHECK_RUNNING:
from typing import Dict, Iterable, List
class DictMetadata(object):
"""IMetadataProvider that reads metadata files from a dictionary.
"""
def __init__(self, metadata):
# type: (Dict[str, bytes]) -> None
self._metadata = metadata
def has_metadata(self, name):
# type: (str) -> bool
return name in self._metadata
def get_metadata(self, name):
# type: (str) -> str
try:
return ensure_str(self._metadata[name])
except UnicodeDecodeError as e:
# Mirrors handling done in pkg_resources.NullProvider.
e.reason += " in {} file".format(name)
raise
def get_metadata_lines(self, name):
# type: (str) -> Iterable[str]
return yield_lines(self.get_metadata(name))
def metadata_isdir(self, name):
# type: (str) -> bool
return False
def metadata_listdir(self, name):
# type: (str) -> List[str]
return []
def run_script(self, script_name, namespace):
# type: (str, str) -> None
pass
| [
{
"point_num": 1,
"id": "all_params_annotated",
"question": "Does every function parameter in this file have a type annotation (excluding self/cls)?",
"answer": false
},
{
"point_num": 2,
"id": "every_function_has_docstring",
"question": "Does every function in this file have a docst... | 3 | src/fetchcode/vcs/pip/_internal/utils/pkg_resources.py | quepop/fetchcode |
from DataStream.ByteReader import ByteReader
from Protocol.Messages.Server.KeepAliveServerMessage import KeepAliveServerMessage
from Logic.Player import Player
from Protocol.Messages.Server.AvailableServerCommandMessage import AvailableServerCommandMessage
class KeepAliveMessage(ByteReader):
def __init__(self, client, crypto, player, initial_bytes):
super().__init__(initial_bytes)
self.client = client
self.crypto = crypto
self.player = player
def decode(self):
pass
def process(self):
KeepAliveServerMessage(self.client, self.player).send(self.crypto) | [
{
"point_num": 1,
"id": "all_function_names_snake_case",
"question": "Are all function names in this file written in snake_case?",
"answer": true
},
{
"point_num": 2,
"id": "all_params_annotated",
"question": "Does every function parameter in this file have a type annotation (excludi... | 3 | Server/Protocol/Messages/Client/KeepAliveMessage.py | Voeed/Brawl-stars-v11 |
from django.core.management.base import BaseCommand, CommandError
from cddp.models import CptCadastreScdb
from shack.utils import copy_cddp_cadastre, prune_addresses
class Command(BaseCommand):
help = 'Undertakes copy of cadastre data from a database connection'
def add_arguments(self, parser):
parser.add_argument(
'--limit', action='store', dest='limit', default=None,
help='Limit of the number of results to query/import')
def handle(self, *args, **options):
if options['limit']:
try:
limit = int(options['limit'])
except ValueError:
raise CommandError('Invalid limit value: {}'.format(options['limit']))
else:
limit = None
qs = CptCadastreScdb.objects.all()
if limit:
qs = qs[0:limit]
self.stdout.write('Starting copy of {} cadastre addresses'.format(qs.count()))
copy_cddp_cadastre(qs)
self.stdout.write('Finished copy of cadastre addresses')
prune_addresses()
| [
{
"point_num": 1,
"id": "every_function_has_docstring",
"question": "Does every function in this file have a docstring?",
"answer": false
},
{
"point_num": 2,
"id": "every_function_under_20_lines",
"question": "Is every function in this file shorter than 20 lines?",
"answer": tru... | 3 | shack/management/commands/copy_cadastre.py | parksandwildlife/caddy |
from rest_framework import generics, authentication, permissions
from rest_framework.authtoken.views import ObtainAuthToken
from rest_framework.settings import api_settings
from user.serializers import UserSerailizer, AuthTokenSerializer
class CreateUserView(generics.CreateAPIView):
serializer_class = UserSerailizer
class CreateToeknView(ObtainAuthToken):
serializer_class = AuthTokenSerializer
renderer_classes = api_settings.DEFAULT_RENDERER_CLASSES
class ManageUserView(generics.RetrieveUpdateAPIView):
serializer_class = UserSerailizer
authentication_classes = (authentication.TokenAuthentication,)
permission_classes = (permissions.IsAuthenticated,)
def get_object(self):
return self.request.user
| [
{
"point_num": 1,
"id": "every_class_has_docstring",
"question": "Does every class in this file have a docstring?",
"answer": false
},
{
"point_num": 2,
"id": "more_functions_than_classes",
"question": "Does this file define more functions than classes?",
"answer": false
},
{... | 3 | user/views.py | prajilmv/recipe-app-api |
from __future__ import absolute_import
import unittest
from blingalytics.sources import static
from mock import Mock
from test import reports
class TestStaticSource(unittest.TestCase):
def setUp(self):
self.report = reports.SuperBasicReport(Mock())
def test_static_source(self):
source = static.StaticSource(self.report)
self.assertEqual(len(source._columns), 1)
self.assertEqual(len(source._columns[0]), 2)
self.assertEqual(source._columns[0][0], 'id')
self.assertEqual(list(source._columns_dict), ['id'])
self.assertTrue(isinstance(source._columns[0][1], static.Value))
self.assertEqual(source.pre_process({}), None)
self.assertEqual(list(source.get_rows([], {})), [])
self.assertEqual(source.post_process({'othercolumn': 'stuff'}, {}),
{'othercolumn': 'stuff', 'id': 1})
| [
{
"point_num": 1,
"id": "has_nested_function_def",
"question": "Does this file contain any function defined inside another function?",
"answer": false
},
{
"point_num": 2,
"id": "every_function_under_20_lines",
"question": "Is every function in this file shorter than 20 lines?",
... | 3 | test/sources/test_static.py | ChowNow/blingalytics |
from fastapi import FastAPI
import uvicorn
from logic import add
app = FastAPI()
@app.get("/")
async def root():
return {"message": "Hello"}
@app.get("/add/{num1}/{num2}")
async def adder(num1: int, num2: int):
"""Add two numbers together"""
total = add(num1,num2)
return {"total": total}
if __name__ == '__main__':
uvicorn.run(app, port=8080, host='0.0.0.0') | [
{
"point_num": 1,
"id": "has_nested_function_def",
"question": "Does this file contain any function defined inside another function?",
"answer": false
},
{
"point_num": 2,
"id": "every_function_under_20_lines",
"question": "Is every function in this file shorter than 20 lines?",
... | 3 | mainFastApi.py | aimanh22/microservices-key-concepts |
# coding: utf-8
from __future__ import unicode_literals, print_function, division, absolute_import
from django.conf import settings
url = False
if hasattr(settings, 'KOBOFORM_URL') and settings.KOBOFORM_URL:
url = settings.KOBOFORM_URL
else:
url = False
active = bool(url)
autoredirect = active
if active and hasattr(settings, 'KOBOFORM_LOGIN_AUTOREDIRECT'):
autoredirect = settings.KOBOFORM_LOGIN_AUTOREDIRECT
def redirect_url(url_param):
if url:
return url + url_param
def login_url(next_kobocat_url=False, next_url=False):
# use kpi login if configuration exists
if settings.KPI_URL:
url = settings.KPI_URL
if url:
url_param = url + '/accounts/login/'
if next_kobocat_url:
next_url = '/kobocat%s' % next_kobocat_url
if next_url:
url_param += "?next=%s" % next_url
return url_param
| [
{
"point_num": 1,
"id": "every_function_under_20_lines",
"question": "Is every function in this file shorter than 20 lines?",
"answer": true
},
{
"point_num": 2,
"id": "all_params_annotated",
"question": "Does every function parameter in this file have a type annotation (excluding se... | 3 | onadata/koboform/__init__.py | ubpd/kobocat |
from celescope.mut.__init__ import __ASSAY__
from celescope.tools.multi import Multi
class Multi_mut(Multi):
def mapping_mut(self, sample):
step = 'mapping_mut'
fq = f'{self.outdir_dic[sample]["cutadapt"]}/{sample}_clean_2.fq{self.fq_suffix}'
cmd = (
f'{self.__APP__} '
f'{self.__ASSAY__} '
f'{step } '
f'--outdir {self.outdir_dic[sample][step]} '
f'--sample {sample} '
f'--assay {self.__ASSAY__} '
f'--fq {fq} '
f'--thread {self.thread} '
f'--indel_genomeDir {self.indel_genomeDir} '
)
self.process_cmd(cmd, step, sample, m=self.args.starMem, x=self.args.thread)
def count_mut(self, sample):
step = 'count_mut'
bam = f'{self.outdir_dic[sample]["mapping_mut"]}/{sample}_Aligned.sortedByCoord.out.bam'
cmd = (
f'{self.__APP__} '
f'{self.__ASSAY__} '
f'{step } '
f'--outdir {self.outdir_dic[sample][step]} '
f'--sample {sample} '
f'--assay {self.__ASSAY__} '
f'--bam {bam} '
f'--mut_file {self.mut_file} '
f'--match_dir {self.col4_dict[sample]} '
f'--shift_base {self.shift_base} '
)
self.process_cmd(cmd, step, sample, m=8, x=1)
def main():
multi = Multi_mut(__ASSAY__)
multi.run()
if __name__ == '__main__':
main()
| [
{
"point_num": 1,
"id": "has_nested_function_def",
"question": "Does this file contain any function defined inside another function?",
"answer": false
},
{
"point_num": 2,
"id": "has_multiple_inheritance",
"question": "Does any class in this file use multiple inheritance?",
"answ... | 3 | celescope/mut/multi_mut.py | pigraul/CeleScope |
# 與moudle1有相同名稱的函數
def foo():
return ('happy birthday~')
def bar ():
return print('happy new year !!') | [
{
"point_num": 1,
"id": "every_function_has_docstring",
"question": "Does every function in this file have a docstring?",
"answer": false
},
{
"point_num": 2,
"id": "has_nested_function_def",
"question": "Does this file contain any function defined inside another function?",
"ans... | 3 | Day01-15/pratice_code/HY_module2.py | reic/groupLearning-Python-100-Days |
"""BayesianTracker (`btrack`) is a multi object tracking algorithm,
specifically used to reconstruct trajectories in crowded fields. New
observations are assigned to tracks by evaluating the posterior probability of
each potential linkage from a Bayesian belief matrix for all possible
linkages. """
from setuptools import find_packages, setup
def get_install_required():
with open("./requirements.txt", "r") as reqs:
requirements = reqs.readlines()
return [r.rstrip() for r in requirements]
def get_version():
with open("./btrack/VERSION.txt", "r") as ver:
version = ver.readline()
return version.rstrip()
DESCRIPTION = 'A framework for Bayesian multi-object tracking'
LONG_DESCRIPTION = __doc__
setup(
name='btrack',
version=get_version(),
description=DESCRIPTION,
long_description=LONG_DESCRIPTION,
long_description_content_type='text/markdown',
author='Alan R. Lowe',
author_email='a.lowe@ucl.ac.uk',
url='https://github.com/quantumjot/BayesianTracker',
packages=find_packages(),
package_data={'btrack': ['libs/libtracker*', 'VERSION.txt']},
install_requires=get_install_required(),
python_requires='>=3.6',
license='LICENSE.md',
classifiers=[
'Programming Language :: C++',
'Programming Language :: Python',
'Programming Language :: Python :: 3 :: Only',
'Topic :: Scientific/Engineering',
'Topic :: Scientific/Engineering :: Bio-Informatics',
'Topic :: Scientific/Engineering :: Image Recognition',
],
)
| [
{
"point_num": 1,
"id": "all_return_types_annotated",
"question": "Does every function in this file have a return type annotation?",
"answer": false
},
{
"point_num": 2,
"id": "every_function_has_docstring",
"question": "Does every function in this file have a docstring?",
"answe... | 3 | setup.py | dpshelio/BayesianTracker |
#crypto.py
from urllib.request import urlopen as req
from bs4 import BeautifulSoup as soup
def rangeprice(name='bitcoin',start='20200101',end='20200131'):
url = 'https://coinmarketcap.com/currencies/{}/historical-data/?start={}&end={}'.format(name,start,end)
webopen = req(url)
page_html = webopen.read()
webopen.close()
data = soup(page_html,'html.parser')
table = data.findAll('tr')
list_days = []
list_dict = {}
for row in table[3:]:
rw = row.findAll('div')
days = []
for i,r in enumerate(rw):
if i > 0 and i < 5:
days.append(float(r.text.replace(',','')))
elif i > 4:
days.append(int(r.text.replace(',','')))
else:
days.append(r.text.replace(',',''))
list_days.append(days)
list_dict[days[0]] = {'date':days[0],'open':days[1],'high':days[2],'low':days[3],'close':days[4],'volume':days[5],'marketcap':days[6]}
return (list_days,list_dict)
def dayprice(name='bitcoin',day='20200131'):
try:
url = 'https://coinmarketcap.com/currencies/{}/historical-data/?start={}&end={}'.format(name,day,day)
webopen = req(url)
page_html = webopen.read()
webopen.close()
data = soup(page_html,'html.parser')
table = data.findAll('tr')
list_days = []
list_dict = {}
for row in table[3:]:
rw = row.findAll('div')
days = []
for i,r in enumerate(rw):
if i > 0 and i < 5:
days.append(float(r.text.replace(',','')))
elif i > 4:
days.append(int(r.text.replace(',','')))
else:
days.append(r.text.replace(',',''))
list_days.append(days)
list_dict[days[0]] = {'date':days[0],'open':days[1],'high':days[2],'low':days[3],'close':days[4],'volume':days[5],'marketcap':days[6]}
list_dict = list_dict[list_days[0][0]]
list_days = list_days[0]
except:
list_days = ['Not Found / Connection Loss']
list_dict = {'error':'Not Found / Connection Loss'}
return (list_days,list_dict)
if __name__ == '__main__':
L,D = rangeprice('xrp',start='20200105',end='20200131')
print(L)
print(D)
L,D = dayprice('bitcoin','20200131')
print(L)
print(D) | [
{
"point_num": 1,
"id": "every_function_under_20_lines",
"question": "Is every function in this file shorter than 20 lines?",
"answer": false
},
{
"point_num": 2,
"id": "no_function_exceeds_5_params",
"question": "Does every function in this file take 5 or fewer parameters (excluding... | 3 | unclecrypto/crypto.py | UncleEngineer/unclecrypto |
import re
import six
import unicodedata
def smart_text(s, encoding='utf-8', errors='strict'):
if isinstance(s, six.text_type):
return s
if not isinstance(s, six.string_types):
if six.PY3:
if isinstance(s, bytes):
s = six.text_type(s, encoding, errors)
else:
s = six.text_type(s)
elif hasattr(s, '__unicode__'):
s = six.text_type(s)
else:
s = six.text_type(bytes(s), encoding, errors)
else:
s = six.text_type(s)
return s
# Extra characters outside of alphanumerics that we'll allow.
SLUG_OK = '-_~'
def slugify(s, ok=SLUG_OK, lower=True, spaces=False):
# L and N signify letter/number.
# http://www.unicode.org/reports/tr44/tr44-4.html#GC_Values_Table
rv = []
for c in unicodedata.normalize('NFKC', smart_text(s)):
cat = unicodedata.category(c)[0]
if cat in 'LN' or c in ok:
rv.append(c)
if cat == 'Z': # space
rv.append(' ')
new = ''.join(rv).strip()
if not spaces:
new = re.sub('[-\s]+', '-', new)
return new.lower() if lower else new
| [
{
"point_num": 1,
"id": "every_function_under_20_lines",
"question": "Is every function in this file shorter than 20 lines?",
"answer": true
},
{
"point_num": 2,
"id": "no_function_exceeds_5_params",
"question": "Does every function in this file take 5 or fewer parameters (excluding ... | 3 | slugify/__init__.py | mathiasose/unicode-slugify |
#!/usr/bin/env python
import os
import jinja2
import yaml
PATH = os.path.dirname(os.path.abspath(__file__))
TEMPLATE_ENVIRONMENT = jinja2.Environment(
autoescape=False,
loader=jinja2.FileSystemLoader(os.path.join(PATH, 'data')),
trim_blocks=False)
def render_template(template_filename, context):
return TEMPLATE_ENVIRONMENT.get_template(template_filename).render(context)
def load_styles():
out = os.path.join('content', 'showcase.md')
with open(out, 'w+') as o, open(os.path.join('data', 'styles.yml')) as d:
html = render_template('showcase.md', {'data': yaml.load(d)})
o.write(html)
if __name__ == '__main__':
load_styles()
| [
{
"point_num": 1,
"id": "every_function_under_20_lines",
"question": "Is every function in this file shorter than 20 lines?",
"answer": true
},
{
"point_num": 2,
"id": "has_nested_function_def",
"question": "Does this file contain any function defined inside another function?",
"... | 3 | load_styles.py | wouter-veeken/docs |
"""
This class contains functions to interact between user interactions provided through HTML requests and the forms that
the user is using.
"""
from django.contrib.auth import authenticate
from django.contrib.auth import login as auth_login
def signup(form, request):
"""
This function saves a new user account and then authenticate the user and log them in.
:param form: The form the user filled in to sign up.
:param request: The HTML request containing the request to sign up.
:return: None
"""
form.save()
# Obtain the username and password from the valid form.
username = form.cleaned_data.get('username')
raw_password = form.cleaned_data.get('password1')
# Authenticate and login the user.
user = authenticate(username=username, password=raw_password)
auth_login(request, user)
def authenticate_user(form):
"""
This function attempts to authenticate an existing user and returns an authenticated user upon completion.
:param form: The form containing the user's username and password.
:return: An authenticated user.
"""
login_username = form.cleaned_data.get('login_username')
raw_password = form.cleaned_data.get('login_password')
user = authenticate(
username=login_username,
password=raw_password)
return user
| [
{
"point_num": 1,
"id": "all_params_annotated",
"question": "Does every function parameter in this file have a type annotation (excluding self/cls)?",
"answer": false
},
{
"point_num": 2,
"id": "every_function_has_docstring",
"question": "Does every function in this file have a docst... | 3 | capstoneproject/helpers/form_helper.py | athrun22/content-rating |
import os.path
from app.data.database import init_db, db_path, get_expected_pathname, set_path
def db_exists():
return os.path.isfile(db_path)
def check_db():
global db_path
if (db_path != get_expected_pathname()):
print('DB Check: Running backup')
backup_database_to(get_expected_pathname())
init_db()
if (not db_exists()):
print('DB Check: No database found. Making a new one...')
init_db()
from app.data.camper_editing import reset_locs
reset_locs()
def backup_database_to(filename):
global db_path
from shutil import copy2
s = open('data/BACKUPDATA', 'a+')
s.seek(0)
prev_path = s.read()
set_path(filename)
db_path = filename #this line is a crude fix for some messy scoping
s.truncate(0)
s.seek(0)
s.write(filename)
if (prev_path == ""):
print("No previous database found, a new one will be generated. This may happen if the BACKUPDATA file is missing or corrupt.")
return False
elif (prev_path == filename):
print("Tried to back up to the same file!")
else:
print ("backing up & copying")
from app.data.camper_editing import reset_locs
copy2(prev_path, filename)
reset_locs()
return filename
| [
{
"point_num": 1,
"id": "every_function_has_docstring",
"question": "Does every function in this file have a docstring?",
"answer": false
},
{
"point_num": 2,
"id": "every_function_under_20_lines",
"question": "Is every function in this file shorter than 20 lines?",
"answer": fal... | 3 | app/data/check.py | redforge/Flask_Signin |
#!/usr/bin/env python3
# Copyright (c) 2018 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Check that it's not possible to start a second cheesecoind instance using the same datadir or wallet."""
import os
from test_framework.test_framework import BitcoinTestFramework
from test_framework.test_node import ErrorMatch
class FilelockTest(BitcoinTestFramework):
def set_test_params(self):
self.setup_clean_chain = True
self.num_nodes = 2
def setup_network(self):
self.add_nodes(self.num_nodes, extra_args=None)
self.nodes[0].start([])
self.nodes[0].wait_for_rpc_connection()
def run_test(self):
datadir = os.path.join(self.nodes[0].datadir, 'regtest')
self.log.info("Using datadir {}".format(datadir))
self.log.info("Check that we can't start a second cheesecoind instance using the same datadir")
expected_msg = "Error: Cannot obtain a lock on data directory {}. cheesecoin Core is probably already running.".format(datadir)
self.nodes[1].assert_start_raises_init_error(extra_args=['-datadir={}'.format(self.nodes[0].datadir), '-noserver'], expected_msg=expected_msg)
if self.is_wallet_compiled():
wallet_dir = os.path.join(datadir, 'wallets')
self.log.info("Check that we can't start a second cheesecoind instance using the same wallet")
expected_msg = "Error: Error initializing wallet database environment"
self.nodes[1].assert_start_raises_init_error(extra_args=['-walletdir={}'.format(wallet_dir), '-noserver'], expected_msg=expected_msg, match=ErrorMatch.PARTIAL_REGEX)
if __name__ == '__main__':
FilelockTest().main()
| [
{
"point_num": 1,
"id": "every_function_under_20_lines",
"question": "Is every function in this file shorter than 20 lines?",
"answer": true
},
{
"point_num": 2,
"id": "more_functions_than_classes",
"question": "Does this file define more functions than classes?",
"answer": true
... | 3 | test/functional/feature_filelock.py | minblock/cheesecoin |
# coding=utf-8
# Distributed under the MIT software license, see the accompanying
# file LICENSE or http://www.opensource.org/licenses/mit-license.php.
import threading
from xrd.core.Singleton import Singleton
from pyqryptonight import pyqryptonight
class Qryptonight7(object, metaclass=Singleton):
def __init__(self):
self.lock = threading.Lock()
self._qn = pyqryptonight.Qryptonight()
def hash(self, blob):
with self.lock:
return bytes(self._qn.hash(blob))
| [
{
"point_num": 1,
"id": "has_nested_function_def",
"question": "Does this file contain any function defined inside another function?",
"answer": false
},
{
"point_num": 2,
"id": "more_functions_than_classes",
"question": "Does this file define more functions than classes?",
"answ... | 3 | src/xrd/crypto/Qryptonight7.py | jack3343/xrd-core |
import math
from typing import Iterable
from .base import BaseMeasure
class OverlapMeasure(BaseMeasure):
def __init__(self, db=None, maxsize: int = 100) -> None:
super().__init__()
if db:
self.maxsize = db.max_feature_size()
else:
self.maxsize = maxsize
def min_feature_size(self, query_size, alpha) -> int:
# return 1 # Not sure the below isn't sufficient
return math.floor(query_size * alpha) or 1
def max_feature_size(self, query_size, alpha) -> int:
return self.maxsize
def minimum_common_feature_count(
self, query_size: int, y_size: int, alpha: float
) -> int:
return int(math.ceil(alpha * min(query_size, y_size)))
def similarity(self, X: Iterable[str], Y: Iterable[str]) -> int:
return min(len(set(X)), len(set(Y)))
class LeftOverlapMeasure(BaseMeasure):
def __init__(self, db=None, maxsize: int = 100) -> None:
super().__init__()
if db:
self.maxsize = db.max_feature_size()
else:
self.maxsize = maxsize
def min_feature_size(self, query_size, alpha) -> int:
return math.floor(query_size * alpha) or 1
def max_feature_size(self, query_size, alpha) -> int:
return self.maxsize
def minimum_common_feature_count(
self, query_size: int, y_size: int, alpha: float
) -> int:
return math.floor(query_size * alpha) or 1
def similarity(self, X: Iterable[str], Y: Iterable[str]) -> float:
return 1 - len(set(X) - set(Y)) / len(set(X))
| [
{
"point_num": 1,
"id": "all_params_annotated",
"question": "Does every function parameter in this file have a type annotation (excluding self/cls)?",
"answer": false
},
{
"point_num": 2,
"id": "every_function_under_20_lines",
"question": "Is every function in this file shorter than ... | 3 | simstring/measure/overlap.py | icfly2/simstring-1 |
import re
class PacBioReadName:
"""A class to get information from PacBio read names
Only supports subreads and ccs reads for now, but may be
nice to add isoseq support in the future
:param name: Name is a pacbio name
:type name: string
"""
def __init__(self,name):
self._name = name.rstrip()
m1 = re.match('([^\/]+)\/(\d+)\/ccs$',self._name)
m2 = re.match('([^\/]+)\/(\d+)\/(\d+)_(\d+)$',self._name)
self._base = None
self._molecule_number = None
if m1:
self._is_ccs = True
self._base = m1.group(1)
self._molecule_number = int(m1.group(2))
elif m2:
self._is_ccs = False
self._base = m2.group(1)
self._molecule_number = int(m2.group(2))
self._sub_start = int(m2.group(3))
self._sub_end = int(m2.group(4))
if not self._base: return None
def __str__(self):
""" The string representation of this is just the name """
return self._name
def name(self):
"""Just return the full name of the read"""
return self._name;
def is_ccs(self):
""" Return true if this sequence is a ccs read"""
if self._is_ccs: return True
return False
def is_sub(self):
""" Return true if this sequence is a subread"""
if self._is_sub: return True
return False;
def get_base(self):
"""get the first part of the name specific to the SMRT cell"""
return self._base;
def get_molecule(self):
return self._base+'/'+str(self._molecule_number)
def get_molecule_number(self):
"""get the second part of the name specific to the molecule in the flow cell."""
return self._molecule_number
| [
{
"point_num": 1,
"id": "has_multiple_inheritance",
"question": "Does any class in this file use multiple inheritance?",
"answer": false
},
{
"point_num": 2,
"id": "more_functions_than_classes",
"question": "Does this file define more functions than classes?",
"answer": true
},... | 3 | seqtools/format/pacbio.py | jason-weirather/py-seq-tools |
from openslides_backend.permissions.permissions import Permissions
from tests.system.action.base import BaseActionTestCase
class PollDeleteTest(BaseActionTestCase):
def test_delete_correct(self) -> None:
self.set_models({"poll/111": {"meeting_id": 1}, "meeting/1": {}})
response = self.request("poll.delete", {"id": 111})
self.assert_status_code(response, 200)
self.assert_model_deleted("poll/111")
def test_delete_wrong_id(self) -> None:
self.set_models({"poll/112": {"meeting_id": 1}, "meeting/1": {}})
response = self.request("poll.delete", {"id": 111})
self.assert_status_code(response, 400)
self.assert_model_exists("poll/112")
def test_delete_correct_cascading(self) -> None:
self.set_models(
{
"poll/111": {
"option_ids": [42],
"meeting_id": 1,
},
"option/42": {"poll_id": 111, "meeting_id": 1},
"meeting/1": {},
}
)
response = self.request("poll.delete", {"id": 111})
self.assert_status_code(response, 200)
self.assert_model_deleted("poll/111")
self.assert_model_deleted("option/42")
def test_delete_no_permissions(self) -> None:
self.base_permission_test(
{"poll/111": {"meeting_id": 1}}, "poll.delete", {"id": 111}
)
def test_delete_permissions(self) -> None:
self.base_permission_test(
{"poll/111": {"meeting_id": 1}},
"poll.delete",
{"id": 111},
Permissions.Poll.CAN_MANAGE,
)
| [
{
"point_num": 1,
"id": "more_functions_than_classes",
"question": "Does this file define more functions than classes?",
"answer": true
},
{
"point_num": 2,
"id": "all_function_names_snake_case",
"question": "Are all function names in this file written in snake_case?",
"answer": ... | 3 | tests/system/action/poll/test_delete.py | OpenSlides/openslides-backend |
from abc import ABCMeta, abstractmethod
class IBenchmarker(metaclass=ABCMeta):
"""
"""
def __init__(self, config):
import util.constant as const
try:
self._check_config(config)
except KeyError:
raise
except:
raise
self._benchmarker_config = config[const.CFG_RESULT][const.CFG_BENCHMARKER]
self.__name = self._benchmarker_config[const.CFG_NAME]
self.__benchmark_dir = self._benchmarker_config[const.CFG_BENCHMARK_DIR]
def _check_config(self, config):
import util.constant as const
if const.CFG_RESULT not in config:
raise KeyError(const.MSG_KEY_ERROR % const.CFG_RESULT, 'root')
if const.CFG_BENCHMARKER not in config[const.CFG_RESULT]:
raise KeyError(const.MSG_KEY_ERROR % const.CFG_BENCHMARKER, const.CFG_PROBLEM)
if const.CFG_NAME not in config[const.CFG_RESULT][const.CFG_BENCHMARKER]:
raise KeyError(const.MSG_KEY_ERROR % const.CFG_NAME, const.CFG_BENCHMARKER)
if const.CFG_BENCHMARK_DIR not in config[const.CFG_RESULT][const.CFG_BENCHMARKER]:
raise KeyError(const.MSG_KEY_ERROR % const.CFG_BENCHMARK_DIR, const.CFG_BENCHMARKER)
@abstractmethod
def compute_score(self):
pass
@abstractmethod
def compare(self):
pass
@abstractmethod
def on_training_end(self):
pass
@property
def name(self):
return self.__name
@property
def benchmark_dir(self):
return self.__benchmark_dir
| [
{
"point_num": 1,
"id": "every_function_has_docstring",
"question": "Does every function in this file have a docstring?",
"answer": false
},
{
"point_num": 2,
"id": "all_function_names_snake_case",
"question": "Are all function names in this file written in snake_case?",
"answer"... | 3 | benchmarker/base.py | cuponthetop/masters-student |
# AUTO-GENERATED by tools/checkspecs.py - DO NOT EDIT
from __future__ import unicode_literals
from ..preprocess import AutoTcorrelate
def test_AutoTcorrelate_inputs():
input_map = dict(args=dict(argstr='%s',
),
environ=dict(nohash=True,
usedefault=True,
),
eta2=dict(argstr='-eta2',
),
ignore_exception=dict(nohash=True,
usedefault=True,
),
in_file=dict(argstr='%s',
copyfile=False,
mandatory=True,
position=-1,
),
mask=dict(argstr='-mask %s',
),
mask_only_targets=dict(argstr='-mask_only_targets',
xor=['mask_source'],
),
mask_source=dict(argstr='-mask_source %s',
xor=['mask_only_targets'],
),
out_file=dict(argstr='-prefix %s',
name_source='in_file',
name_template='%s_similarity_matrix.1D',
),
outputtype=dict(),
polort=dict(argstr='-polort %d',
),
terminal_output=dict(nohash=True,
),
)
inputs = AutoTcorrelate.input_spec()
for key, metadata in list(input_map.items()):
for metakey, value in list(metadata.items()):
assert getattr(inputs.traits()[key], metakey) == value
def test_AutoTcorrelate_outputs():
output_map = dict(out_file=dict(),
)
outputs = AutoTcorrelate.output_spec()
for key, metadata in list(output_map.items()):
for metakey, value in list(metadata.items()):
assert getattr(outputs.traits()[key], metakey) == value
| [
{
"point_num": 1,
"id": "has_nested_function_def",
"question": "Does this file contain any function defined inside another function?",
"answer": false
},
{
"point_num": 2,
"id": "every_function_under_20_lines",
"question": "Is every function in this file shorter than 20 lines?",
... | 3 | nipype/interfaces/afni/tests/test_auto_AutoTcorrelate.py | sebastientourbier/nipype |
import unittest
class TestStringMethods(unittest.TestCase):
def test_upper(self):
self.assertEqual('foo'.upper(), 'FOO')
def test_isupper(self):
self.assertTrue('FOO'.isupper())
self.assertFalse('Foo'.isupper())
def test_split(self):
s = 'hello world'
self.assertEqual(s.split(), ['hello', 'world'])
# check that s.split fails when the separator is not a string
with self.assertRaises(TypeError):
s.split(2)
def test_assert(self):
chart = [ [('P', 'S', 0, 0, ()), ('S', 'S + M', 0, 0, ())],
[('T', '2', 1, 0, ()), ('M', 'T', 1, 0, ((1, 0),))]]
self.assertEqual( chart,
[[('P', 'S', 0, 0, ()), ('S', 'S + M', 0, 0, ())],
[('T', '2', 1, 0, ()), ('M', 'T', 1, 0, ((1, 0),))]])
if __name__ == '__main__':
unittest.main() | [
{
"point_num": 1,
"id": "has_nested_function_def",
"question": "Does this file contain any function defined inside another function?",
"answer": false
},
{
"point_num": 2,
"id": "every_function_under_20_lines",
"question": "Is every function in this file shorter than 20 lines?",
... | 3 | test/UnitTest.py | Wenbo16/OpenSCAD-parser |
# coding: utf-8
"""
Octopus Server API
No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) # noqa: E501
OpenAPI spec version: 2019.6.7+Branch.tags-2019.6.7.Sha.aa18dc6809953218c66f57eff7d26481d9b23d6a
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from __future__ import absolute_import
import unittest
import octopus_deploy_swagger_client
from octopus_deploy_swagger_client.models.package_version_resource import PackageVersionResource # noqa: E501
from octopus_deploy_swagger_client.rest import ApiException
class TestPackageVersionResource(unittest.TestCase):
"""PackageVersionResource unit test stubs"""
def setUp(self):
pass
def tearDown(self):
pass
def testPackageVersionResource(self):
"""Test PackageVersionResource"""
# FIXME: construct object with mandatory attributes with example values
# model = octopus_deploy_swagger_client.models.package_version_resource.PackageVersionResource() # noqa: E501
pass
if __name__ == '__main__':
unittest.main()
| [
{
"point_num": 1,
"id": "has_multiple_inheritance",
"question": "Does any class in this file use multiple inheritance?",
"answer": false
},
{
"point_num": 2,
"id": "more_functions_than_classes",
"question": "Does this file define more functions than classes?",
"answer": true
},... | 3 | test/test_package_version_resource.py | cvent/octopus-deploy-api-client |
from data import watermelon_2_0
from decision_tree import tree_generate
def get_tree():
features, examples = watermelon_2_0()
return tree_generate(features, examples)
def make_dot_source(root):
def node_source(node):
dot_label = node.feature
if node.leaf:
dot_label = node.label
result = "%d [label=\"%s\"];\n" % (id(node), dot_label)
if node.leaf:
return result
for feature_value in node.branch:
child = node.branch[feature_value]
result += "%d -> %d [label=\"%s\"];\n" % (id(node), id(child), feature_value)
result += node_source(child)
return result
source = "digraph \"Decision tree\" {\n"
source += node_source(root)
source += "}\n"
return source
def main():
root = get_tree()
dot_source = make_dot_source(root)
with open("decision_tree.dot", "w", encoding="utf-8") as dot:
dot.write(dot_source)
if __name__ == '__main__':
main()
| [
{
"point_num": 1,
"id": "every_function_under_20_lines",
"question": "Is every function in this file shorter than 20 lines?",
"answer": true
},
{
"point_num": 2,
"id": "has_nested_function_def",
"question": "Does this file contain any function defined inside another function?",
"... | 3 | decision_tree_run.py | tioover/bendan |
from django.core.management.base import BaseCommand, CommandParser
from zerver.lib.actions import do_create_user
from zerver.lib.management import ZulipBaseCommand
from zerver.lib.onboarding import send_initial_pms
from zerver.models import Realm, UserProfile
from typing import Any
class Command(ZulipBaseCommand):
help = """Add a new user for manual testing of the onboarding process.
If realm is unspecified, will try to use a realm created by add_new_realm,
and will otherwise fall back to the zulip realm."""
def add_arguments(self, parser):
# type: (CommandParser) -> None
self.add_realm_args(parser)
def handle(self, **options):
# type: (**Any) -> None
realm = self.get_realm(options)
if realm is None:
realm = Realm.objects.filter(string_id__startswith='realm') \
.order_by('-string_id').first()
if realm is None:
print('Warning: Using default zulip realm, which has an unusual configuration.\n'
'Try running `python manage.py add_new_realm`, and then running this again.')
realm = Realm.objects.get(string_id='zulip')
domain = 'zulip.com'
else:
domain = realm.string_id + '.zulip.com'
name = '%02d-user' % (UserProfile.objects.filter(email__contains='user@').count(),)
user = do_create_user('%s@%s' % (name, domain),
'password', realm, name, name)
send_initial_pms(user)
| [
{
"point_num": 1,
"id": "more_functions_than_classes",
"question": "Does this file define more functions than classes?",
"answer": true
},
{
"point_num": 2,
"id": "every_function_has_docstring",
"question": "Does every function in this file have a docstring?",
"answer": false
}... | 3 | zilencer/management/commands/add_new_user.py | Rishabh570/zulip |
class LMS8001_CHANNEL_PD(object):
def __init__(self, chip, channel, cfgNo):
self.chip = chip
self.channel = channel
self.cfgNo = cfgNo
#
# Read channel PD
#
def __getattr__(self, name):
channel = self.__dict__["channel"]
cfgNo = self.__dict__["cfgNo"]
if name not in ['PA_R50_EN',
'PA_BYPASS',
'PA_PD',
'MIXB_LOBUFF_PD',
'MIXA_LOBUFF_PD',
'LNA_PD']:
raise ValueError("Invalid field name "+str(name))
return self.chip['CH'+channel+'_PD'+str(cfgNo)]['CH'+channel+'_'+name+str(cfgNo)]
#
# Write channel PD
#
def __setattr__(self, name, value):
if name == "chip":
self.__dict__["chip"] = value
return
if name == "channel":
self.__dict__["channel"] = value
return
if name == "cfgNo":
self.__dict__["cfgNo"] = value
return
channel = self.__dict__["channel"]
cfgNo = self.__dict__["cfgNo"]
if name not in ['PA_R50_EN',
'PA_BYPASS',
'PA_PD',
'MIXB_LOBUFF_PD',
'MIXA_LOBUFF_PD',
'LNA_PD']:
raise ValueError("Invalid field name "+str(name))
self.chip['CH'+channel+'_PD'+str(cfgNo)]['CH'+channel+'_'+name+str(cfgNo)] = value
| [
{
"point_num": 1,
"id": "has_multiple_inheritance",
"question": "Does any class in this file use multiple inheritance?",
"answer": false
},
{
"point_num": 2,
"id": "no_function_exceeds_5_params",
"question": "Does every function in this file take 5 or fewer parameters (excluding self... | 3 | pyLMS8001/LMS8001_CHANNEL_PD.py | myriadrf/pyLMS8001 |
"""Model module for images."""
from django.db import models
from django.contrib.auth.models import User
from imager_profile.models import ImagerProfile
# Create your models here.
class ImageBaseClass(models.Model):
"""Base class for Photo and Album classes."""
PRIVATE = 'PRVT'
SHARED = 'SHRD'
PUBLIC = 'PBLC'
PUBLISHED = ((PRIVATE, 'private'),
(SHARED, 'shared'),
(PUBLIC, 'public'))
title = models.CharField(max_length=180)
description = models.TextField(max_length=500, blank=True, null=True)
date_modified = models.DateField(auto_now=True)
date_published = models.DateField(blank=True, null=True)
published = models.CharField(choices=PUBLISHED, max_length=8)
class Meta:
"""Meta."""
abstract = True
class Photo(ImageBaseClass):
"""Photo model."""
user = models.ForeignKey(User, on_delete=models.CASCADE,
related_name='photo')
image = models.ImageField(upload_to='images')
date_uploaded = models.DateField(editable=False, auto_now_add=True)
def __str__(self):
"""Print function displays username."""
return self.title
class Album(ImageBaseClass):
"""Album model."""
user = models.ForeignKey(User, on_delete=models.CASCADE,
related_name='album')
cover = models.ImageField(upload_to='images')
date_created = models.DateField(editable=False, auto_now_add=True)
photos = models.ManyToManyField(Photo, related_name='albums', blank=True)
def __str__(self):
"""Print function displays username."""
return self.title
| [
{
"point_num": 1,
"id": "has_multiple_inheritance",
"question": "Does any class in this file use multiple inheritance?",
"answer": false
},
{
"point_num": 2,
"id": "every_function_has_docstring",
"question": "Does every function in this file have a docstring?",
"answer": true
}... | 3 | imagersite/imager_images/models.py | Loaye/django-imager-group |
import os
from flask import Flask
app = Flask(__name__)
@app.route("/")
def home():
return """
<h1>Hello user</h1>
<img src="http://loremflickr.com/600/400">
<p><a href="/sida2"title ="Síða 2">Síða 2</a> | <a href="/sida3"title ="Síða 3">Síða 3</a></p>
"""
@app.route("/sida2")
def sida2():
return"""
<h1>Hello user</h1>
<img src="http://loremflickr.com/600/400">
<p><a href="/"title ="Síða 1">Síða 1</a> | <a href="/sida3"title ="Síða 3">Síða 3</a></p>
"""
@app.route("/sida3")
def sida3():
return"""
<h1>Hello user</h1>
<img src="http://loremflickr.com/600/400">
<p><a href="/"title ="Síða 1">Síða 1</a> | <a href="/sida2"title ="Síða 2">Síða 2</a></p>
"""
if __name__ == '__main__':
# app.run(debug=True, use_reloader=True)
app.run()
| [
{
"point_num": 1,
"id": "all_function_names_snake_case",
"question": "Are all function names in this file written in snake_case?",
"answer": true
},
{
"point_num": 2,
"id": "has_nested_function_def",
"question": "Does this file contain any function defined inside another function?",
... | 3 | verk2.py | Kristberg/VEF-2VF05CU |
import asyncio, logging
from aiohttp import web
logging.basicConfig(level=logging.INFO)
def index(request):
return web.Response(body=b'<h1>Hello World</h1>', content_type='text/html')
async def init(loop):
app = web.Application(loop=loop)
app.router.add_route('GET', '/', index)
srv = await loop.create_server(app.make_handler(), '127.0.0.1', 5000)
logging.info('server is listening at http://127.0.0.1:5000')
return srv
cur_loop = asyncio.get_event_loop()
cur_loop.run_until_complete(init(cur_loop))
cur_loop.run_forever()
| [
{
"point_num": 1,
"id": "has_nested_function_def",
"question": "Does this file contain any function defined inside another function?",
"answer": false
},
{
"point_num": 2,
"id": "every_function_under_20_lines",
"question": "Is every function in this file shorter than 20 lines?",
... | 3 | app.py | ResolveWang/minifw |
"""
Demonstrate differences between __str__() and __reper__().
"""
class neither:
pass
class stronly:
def __str__(self):
return "STR"
class repronly:
def __repr__(self):
return "REPR"
class both(stronly, repronly):
pass
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def __str__(self):
return self.name
def __repr__(self):
return "Person({0.name!r}, {0.age!r})".format(self) | [
{
"point_num": 1,
"id": "all_function_names_snake_case",
"question": "Are all function names in this file written in snake_case?",
"answer": true
},
{
"point_num": 2,
"id": "every_class_has_docstring",
"question": "Does every class in this file have a docstring?",
"answer": false... | 3 | Python3/Python3_Lesson09/src/reprmagic.py | ceeblet/OST_PythonCertificationTrack |
#!/usr/bin/venv python3
'email-examples.py - demo creation of email messages'
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from smtplib import SMTP
# multipart alternative: text and html
def make_mpa_msg():
email = MIMEMultipart('alternative')
text = MIMEText('Hello World!\r\n', 'plain')
email.attach(text)
html = MIMEText('<html><body><h4>Hello World!</h4>'
'</body></html>', 'html')
email.attach(html)
return email
# multipart: images
def make_img_msg(fn):
f = open(fn, 'r')
data = f.read()
f.close()
email = MIMEImage(data, name=fn)
email.add_header('Content-Disposition', 'attachment; filename="%s"' % fn)
return email
def sendMsg(fr, to, msg):
s = SMTP('localhost')
errs = s.sendmail(fr, to, msg)
s.quit()
if __name__ == '__main__':
print('Sebdubg multipart alternative msg...')
msg = make_mpa_msg()
msg['From'] = SENDER
msg['To'] = ', '.join(RECIPS)
msg['Subject'] = 'multipart alternative test'
sendMsg(SENDER, RECIPS, msg.as_string())
print('Sending image msg...')
msg = make_img_msg(SOME_IMG_FILE)
msg['From'] = SENDER
msg['To'] = ', '.join(RECIPS)
msg['Subject'] = 'image file test'
sendMsg(SENDER, RECIPS, msg.as_string())
| [
{
"point_num": 1,
"id": "no_function_exceeds_5_params",
"question": "Does every function in this file take 5 or fewer parameters (excluding self/cls)?",
"answer": true
},
{
"point_num": 2,
"id": "all_function_names_snake_case",
"question": "Are all function names in this file written... | 3 | CorePython/InternetClient/Email/eamil-examples.py | AnatoleZho/Python3 |
from django.test import TestCase
from hardware.photoCell import PhotoCell
class LightSensorTest(TestCase):
"""
Tests multiple methods for light sensor.
"""
def setUp(self):
example = PhotoCell(18) # try/except if pin is not connected
def test_sensor_reading_returns_number(self):
sensorReadout = example(RCtime())
self.assertTrue(type(sensorReadout) == int)
def test_csv_logging(self):
pass
| [
{
"point_num": 1,
"id": "all_function_names_snake_case",
"question": "Are all function names in this file written in snake_case?",
"answer": false
},
{
"point_num": 2,
"id": "has_multiple_inheritance",
"question": "Does any class in this file use multiple inheritance?",
"answer":... | 3 | hardware/tests.py | edisondotme/motoPi |
# Trie Tree Node
from typing import Optional
class TrieNode:
def __init__(self, char: Optional[str] = None):
self.char = char
self.children = []
self.counter = 0
self.end = False
def add(self, word: str):
node = self
for char in word:
found_in_children = False
for child in node.children:
if child.char == char:
found_in_children = True
child.counter += 1
node = child
break
if not found_in_children:
new_node = TrieNode(char)
node.children.append(new_node)
node = new_node
node.end = True
| [
{
"point_num": 1,
"id": "more_functions_than_classes",
"question": "Does this file define more functions than classes?",
"answer": true
},
{
"point_num": 2,
"id": "has_multiple_inheritance",
"question": "Does any class in this file use multiple inheritance?",
"answer": false
},... | 3 | python-algorithm/common/trie_node.py | isudox/nerd-algorithm |
class response():
def __init__(self) -> None:
self.num = 5
def call_result(self):
return(self.num) | [
{
"point_num": 1,
"id": "has_multiple_inheritance",
"question": "Does any class in this file use multiple inheritance?",
"answer": false
},
{
"point_num": 2,
"id": "more_functions_than_classes",
"question": "Does this file define more functions than classes?",
"answer": true
},... | 3 | sub_call/file_call.py | jyhh1992/test_algorithm |
"""
Copyright (c) 2017 Eric Shook. All rights reserved.
Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.
@author: eshook (Eric Shook, eshook@gmail.edu)
@contributors: <Contribute and add your name here!>
"""
from forest import *
import unittest
# Test forest/bobs/Bob.py
def maketiles(nfiles,nrows,ncols):
for f_i in range(nfiles):
f = open("unittests/tmp_raster"+str(f_i)+".asc","w")
f.write("ncols "+str(ncols)+"\n")
f.write("nrows "+str(nrows)+"\n")
f.write("xllcorner 0.0\n")
f.write("yllcorner 0.0\n")
f.write("cellsize 1.0\n")
f.write("NODATA_value -999\n")
for i in range(nrows):
for j in range(ncols):
f.write(str(i+j+f_i)+" ")
f.write("\n")
f.close()
#maketiles(nfiles,nrows,ncols)
class TestIO(unittest.TestCase):
def setUp(self):
nfiles = 3
nrows = 13
ncols = 13
maketiles(nfiles,nrows,ncols)
def test_io(self):
b1 = Raster()
self.assertEqual(b1.y,0)
test_IO_suite = unittest.TestLoader().loadTestsFromTestCase(TestIO)
| [
{
"point_num": 1,
"id": "every_function_under_20_lines",
"question": "Is every function in this file shorter than 20 lines?",
"answer": true
},
{
"point_num": 2,
"id": "has_multiple_inheritance",
"question": "Does any class in this file use multiple inheritance?",
"answer": false... | 3 | unittests/test_IO.py | tyburesh/Forest |
from inspect import signature
from typing import Callable, Any, List
import re
import copy
from .type import Type
class Function(Type):
def __init__(self, fn: Callable[..., Any], name: str = "anonymouse") -> None:
self.name = name
self.vars = list(signature(fn).parameters)
self.expr = "[built-in]"
self.fn = fn
self.varnum = len(signature(fn).parameters)
def __call__(self, *args, **kwds):
return self.fn(*args, **kwds)
def __str__(self) -> str:
return f"{self.name}({','.join(self.vars)})={self.expr}"
class ListFunction(Function):
pattern = r"[a-zA-Z]+\(.+\)"
def __init__(self, expr: str, vars: List[str], name: str = "anonymouse") -> None:
self.name = name
self.expr = expr
self.vars = vars
self.varnum = len(vars)
from ..expression import infix_to_rpnlist
rpn_list = infix_to_rpnlist(expr)
for i in range(len(rpn_list)):
if (rpn_list[i] in vars):
rpn_list[i] = str(vars.index(rpn_list[i]))
self.rpn_list = rpn_list
def __call__(self, *args, **kwds):
res = copy.deepcopy(self.rpn_list)
for i in range(len(self.rpn_list)):
if isinstance(res[i], str) and res[i].isdigit():
res[i] = args[int(res[i])]
from ..expression import eval_rpn
return eval_rpn(res)
def subvars(self):
# a function to replace variables with there values
def f(m: re.Match):
from ..ft_global import user_vars
word = m.group().lower()
if word in user_vars and not isinstance(user_vars[word], Function):
return(str(user_vars[word]))
else:
return(m.group())
result = re.sub(r"[a-zA-Z]+", f, self.expr)
return result.strip()
def __str__(self) -> str:
result = self.subvars()
return f"{self.name}({','.join(self.vars)}) = {result}"
| [
{
"point_num": 1,
"id": "more_functions_than_classes",
"question": "Does this file define more functions than classes?",
"answer": true
},
{
"point_num": 2,
"id": "all_params_annotated",
"question": "Does every function parameter in this file have a type annotation (excluding self/cl... | 3 | computorv2/types/function.py | ayoubyt/ComputorV2 |
from geojson_rewind import rewind
from geomet import wkt
import decimal
import statistics
def wkt_rewind(x, digits=None):
"""
reverse WKT winding order
:param x: [str] WKT string
:param digits: [int] number of digits after decimal to use for the return string.
by default, we use the mean number of digits in your string.
:return: a string
Usage::
from pygbif import wkt_rewind
x = 'POLYGON((144.6 13.2, 144.6 13.6, 144.9 13.6, 144.9 13.2, 144.6 13.2))'
wkt_rewind(x)
wkt_rewind(x, digits = 0)
wkt_rewind(x, digits = 3)
wkt_rewind(x, digits = 7)
"""
z = wkt.loads(x)
if digits is None:
coords = z["coordinates"]
nums = __flatten(coords)
dec_n = [decimal.Decimal(str(w)).as_tuple().exponent for w in nums]
digits = abs(statistics.mean(dec_n))
else:
if not isinstance(digits, int):
raise TypeError("'digits' must be an int")
wound = rewind(z)
back_to_wkt = wkt.dumps(wound, decimals=digits)
return back_to_wkt
# from https://stackoverflow.com/a/12472564/1091766
def __flatten(S):
if S == []:
return S
if isinstance(S[0], list):
return __flatten(S[0]) + __flatten(S[1:])
return S[:1] + __flatten(S[1:])
| [
{
"point_num": 1,
"id": "all_params_annotated",
"question": "Does every function parameter in this file have a type annotation (excluding self/cls)?",
"answer": false
},
{
"point_num": 2,
"id": "no_function_exceeds_5_params",
"question": "Does every function in this file take 5 or fe... | 3 | pygbif/utils/wkt_rewind.py | bartaelterman/pygbif |
import sqlite3
class DBHelper:
def __init__(self, dbname="nsnotif.sqlite"):
self.dbname = dbname
self.conn = sqlite3.connect(dbname)
def setup(self):
tblstmt = "CREATE TABLE IF NOT EXISTS users (username text , cid text, PRIMARY KEY(username))"
self.conn.execute(tblstmt)
self.conn.commit()
def add_user(self, username, cid):
stmt = "INSERT INTO users (username, cid) VALUES (?, ?)"
args = (username, cid)
self.conn.execute(stmt, args)
self.conn.commit()
def delete_user(self, username):
stmt = "DELETE FROM users WHERE username = (?)"
args = (username,)
self.conn.execute(stmt, args)
self.conn.commit()
def get_users(self):
stmt = "SELECT * FROM users"
return [(x[0],x[1]) for x in self.conn.execute(stmt)]
def get_user(self,user_name):
stmt = "SELECT * FROM users WHERE username = (?)"
args = (user_name,)
return [x for x in self.conn.execute(stmt,args)]
def get_cid(self,username):
stmt = "SELECT cid FROM users WHERE username = (?)"
args = (username,)
return self.conn.execute(stmt,args)[0]
| [
{
"point_num": 1,
"id": "more_functions_than_classes",
"question": "Does this file define more functions than classes?",
"answer": true
},
{
"point_num": 2,
"id": "every_function_under_20_lines",
"question": "Is every function in this file shorter than 20 lines?",
"answer": true
... | 3 | nsnotif/dbhelper.py | bakyazi/NSNOTIF |
from more.transaction import default_commit_veto
def callFUT(response, request=None):
return default_commit_veto(request, response)
def test_it_true_500():
response = DummyResponse('500 Server Error')
assert callFUT(response)
def test_it_true_503():
response = DummyResponse('503 Service Unavailable')
assert callFUT(response)
def test_it_true_400():
response = DummyResponse('400 Bad Request')
assert callFUT(response)
def test_it_true_411():
response = DummyResponse('411 Length Required')
assert callFUT(response)
def test_it_false_200():
response = DummyResponse('200 OK')
assert not callFUT(response)
def test_it_false_201():
response = DummyResponse('201 Created')
assert not callFUT(response)
def test_it_false_301():
response = DummyResponse('301 Moved Permanently')
assert not callFUT(response)
def test_it_false_302():
response = DummyResponse('302 Found')
assert not callFUT(response)
def test_it_false_x_tm_commit():
response = DummyResponse('200 OK', {'x-tm': 'commit'})
assert not callFUT(response)
def test_it_true_x_tm_abort():
response = DummyResponse('200 OK', {'x-tm': 'abort'})
assert callFUT(response)
def test_it_true_x_tm_anythingelse():
response = DummyResponse('200 OK', {'x-tm': ''})
assert callFUT(response)
class DummyRequest(object):
path_info = '/'
def __init__(self):
self.environ = {}
self.made_seekable = 0
def make_body_seekable(self):
self.made_seekable += 1
class DummyResponse(object):
def __init__(self, status='200 OK', headers=None):
self.status = status
if headers is None:
headers = {}
self.headers = headers
| [
{
"point_num": 1,
"id": "every_function_under_20_lines",
"question": "Is every function in this file shorter than 20 lines?",
"answer": true
},
{
"point_num": 2,
"id": "has_multiple_inheritance",
"question": "Does any class in this file use multiple inheritance?",
"answer": false... | 3 | more/transaction/tests/test_default_commit_veto.py | sgaist/more.transaction |
def falling(n, k):
"""Compute the falling factorial of n to depth k.
>>> falling(6, 3) # 6 * 5 * 4
120
>>> falling(4, 3) # 4 * 3 * 2
24
>>> falling(4, 1) # 4
4
>>> falling(4, 0)
1
"""
"*** YOUR CODE HERE ***"
def sum_digits(y):
"""Sum all the digits of y.
>>> sum_digits(10) # 1 + 0 = 1
1
>>> sum_digits(4224) # 4 + 2 + 2 + 4 = 12
12
>>> sum_digits(1234567890)
45
>>> a = sum_digits(123) # make sure that you are using return rather than print
>>> a
6
"""
"*** YOUR CODE HERE ***"
def double_eights(n):
"""Return true if n has two eights in a row.
>>> double_eights(8)
False
>>> double_eights(88)
True
>>> double_eights(2882)
True
>>> double_eights(880088)
True
>>> double_eights(12345)
False
>>> double_eights(80808080)
False
"""
"*** YOUR CODE HERE ***"
| [
{
"point_num": 1,
"id": "has_nested_function_def",
"question": "Does this file contain any function defined inside another function?",
"answer": false
},
{
"point_num": 2,
"id": "all_params_annotated",
"question": "Does every function parameter in this file have a type annotation (ex... | 3 | CS 61A/Lab/lab01/lab01.py | nekomiao123/learn_more |
import numpy as np
from vis_utils.scene.components import ComponentBase
class SimpleNavigationAgent(ComponentBase):
def __init__(self, scene_object):
ComponentBase.__init__(self, scene_object)
self.controller = scene_object._components["morphablegraph_state_machine"]
self.walk_targets = []
self.tolerance = 20
def get_actions(self):
return self.controller.get_actions()
def get_keyframe_labels(self, action_name):
return self.controller.get_keyframe_labels(action_name)
def perform_action(self, action_name, keyframe_label, position):
self.controller.set_action_constraint(action_name, keyframe_label, position)
self.controller.transition_to_action(action_name)
def set_walk_target(self, target):
self.walk_targets.append(target)
self.update(0)
if self.controller.node_type == "idle":
self.controller.transition_to_next_state_controlled()
def remove_walk_target(self):
if len(self.walk_targets) > 1:
self.walk_targets = self.walk_targets[1:]
else:
self.walk_targets = []
self.controller.target_projection_len = 0
def get_current_walk_target(self):
if len(self.walk_targets) > 0:
return self.walk_targets[0]
else:
return None
def update(self, dt):
target = self.get_current_walk_target()
if target is None:
return
controller_pos = np.array(self.controller.getPosition())
controller_pos[1] = 0
target_pos = target.getPosition()
target_pos[1] = 0
target_dir = target_pos - controller_pos
distance = np.linalg.norm(target_dir)
target_dir = target_dir / distance
self.controller.direction_vector = target_dir
if distance > self.tolerance:
self.controller.target_projection_len = min(self.controller.max_step_length, distance)
else:
self.remove_walk_target()
| [
{
"point_num": 1,
"id": "more_functions_than_classes",
"question": "Does this file define more functions than classes?",
"answer": true
},
{
"point_num": 2,
"id": "every_function_has_docstring",
"question": "Does every function in this file have a docstring?",
"answer": false
}... | 3 | mg_server/simple_navigation_agent.py | eherr/mg_server |
import os
import sys
sys.path.append(os.path.abspath('.'))
def install():
from context_menu import menus
import modules
pyLoc = sys.executable # .replace('python.exe', 'pythonw.exe')
scriptLoc = os.path.join(os.path.dirname(
os.path.realpath(__file__)), 'main.py') # Location of parser to be called
menu = menus.ContextMenu('Sort Files', type='DIRECTORY_BACKGROUND')
extractCommand = menus.ContextCommand('Uproot All Files', python=modules.handleExtract)
extensionCommand = menus.ContextCommand('Sort by Extension', python=modules.handleExtension)
typeCommand = menus.ContextCommand('Sort by Type', python=modules.handleType)
dateMenu = menus.ContextMenu('Sort By Date')
dateMenu.add_items([
menus.ContextCommand('Day', python=modules.handleDate, params='D'),
menus.ContextCommand('Month', python=modules.handleDate, params='M'),
menus.ContextCommand('Year', python=modules.handleDate, params='Y')
])
menu.add_items([
extractCommand,
extensionCommand,
typeCommand,
dateMenu
])
menu.compile()
def uninstall():
from context_menu import menus
menus.removeMenu('Sort Files', 'DIRECTORY_BACKGROUND')
install()
| [
{
"point_num": 1,
"id": "every_function_under_20_lines",
"question": "Is every function in this file shorter than 20 lines?",
"answer": false
},
{
"point_num": 2,
"id": "every_function_has_docstring",
"question": "Does every function in this file have a docstring?",
"answer": fal... | 3 | src/scripts/reginstall.py | saleguas/freshen-file-sorter |
import synapse.common as s_common
import synapse.lib.socket as s_socket
from synapse.links.common import *
class TcpRelay(LinkRelay):
'''
Implements the TCP protocol for synapse.
tcp://[user[:passwd]@]<host>[:port]/<path>
'''
proto = 'tcp'
def _reqValidLink(self):
host = self.link[1].get('host')
port = self.link[1].get('port')
if host is None:
raise s_common.PropNotFound('host')
if port is None:
raise s_common.PropNotFound('port')
def _listen(self):
host = self.link[1].get('host')
port = self.link[1].get('port')
sock = s_socket.listen((host, port))
self.link[1]['port'] = sock.getsockname()[1]
return sock
def _connect(self):
try:
host = self.link[1].get('host')
port = self.link[1].get('port')
return s_socket.connect((host, port))
except s_common.sockerrs as e:
raiseSockError(self.link, e)
| [
{
"point_num": 1,
"id": "all_function_names_snake_case",
"question": "Are all function names in this file written in snake_case?",
"answer": false
},
{
"point_num": 2,
"id": "more_functions_than_classes",
"question": "Does this file define more functions than classes?",
"answer":... | 3 | synapse/links/tcp.py | larrycameron80/synapse |
import pytorch_lightning as pl
import pytorch_lightning.callbacks
class ResetOptimizers(pl.Callback):
def __init__(self, verbose: bool, epoch_reset_field: str = "pretrain_epochs"):
super().__init__()
self.verbose = verbose
self.epoch_reset_field= epoch_reset_field
def on_train_epoch_end(self, trainer, pl_module):
reset_epoch = getattr(pl_module.hparams, self.epoch_reset_field) - 1
if trainer.current_epoch == reset_epoch:
if self.verbose:
print("\nPretraining complete, resetting optimizers and schedulers")
trainer.accelerator.setup_optimizers(trainer)
| [
{
"point_num": 1,
"id": "every_function_under_20_lines",
"question": "Is every function in this file shorter than 20 lines?",
"answer": true
},
{
"point_num": 2,
"id": "has_multiple_inheritance",
"question": "Does any class in this file use multiple inheritance?",
"answer": false... | 3 | econ_layers/callbacks.py | HighDimensionalEconLab/econ_layers |
import pytest
from custom_components.racelandshop.share import SHARE
from custom_components.racelandshop.validate import (
async_initialize_rules,
async_run_repository_checks,
)
@pytest.mark.asyncio
async def test_async_initialize_rules(racelandshop):
await async_initialize_rules()
@pytest.mark.asyncio
async def test_async_run_repository_checks(racelandshop, repository_integration):
await async_run_repository_checks(repository_integration)
racelandshop.system.action = True
racelandshop.system.running = True
repository_integration.tree = []
with pytest.raises(SystemExit):
await async_run_repository_checks(repository_integration)
racelandshop.system.action = False
SHARE["rules"] = {}
await async_run_repository_checks(repository_integration)
racelandshop.system.running = False
| [
{
"point_num": 1,
"id": "has_nested_function_def",
"question": "Does this file contain any function defined inside another function?",
"answer": false
},
{
"point_num": 2,
"id": "every_function_has_docstring",
"question": "Does every function in this file have a docstring?",
"ans... | 3 | tests/validate/test_async_run_repository_checks.py | racelandshop/integration |
from __future__ import absolute_import
"""
This base config script gets automatically executed for all platforms via
configure if the "dev" sub-configuration is specified (which is the default).
"""
from os import makedirs
from os import path
import shutil
scancode_root_dir = path.dirname(
# etc
path.dirname(
# conf
path.dirname(
# dev
path.dirname(__file__)
)
)
)
def setup_dev_mode():
"""
Create the development mode tag file. In development mode, ScanCode does
not rely on license data to remain untouched and will always check the
license index cache for consistency, rebuilding it if necessary.
"""
with open(path.join(scancode_root_dir, 'SCANCODE_DEV_MODE'), 'w') as sdm:
sdm.write('This is a tag file to notify that ScanCode is used in development mode.')
def setup_vscode():
"""
Add base settings for .vscode
"""
settings = path.join('vscode', 'settings.json')
source = path.join(scancode_root_dir, 'etc', settings)
vscode = path.join(scancode_root_dir, '.vscode')
target = path.join(scancode_root_dir, settings)
if path.exists(settings):
if not path.exists(vscode):
makedirs(vscode)
shutil.copyfile(source, target)
setup_dev_mode()
setup_vscode()
| [
{
"point_num": 1,
"id": "every_function_has_docstring",
"question": "Does every function in this file have a docstring?",
"answer": true
},
{
"point_num": 2,
"id": "every_function_under_20_lines",
"question": "Is every function in this file shorter than 20 lines?",
"answer": true... | 3 | etc/conf/dev/base.py | abhi27-web/scancode-toolk |
from pyhocon import ConfigTree # noqa: F401
from typing import Dict, Optional # noqa: F401
from databuilder.transformer.base_transformer import Transformer
from databuilder.models.table_column_usage import ColumnReader, TableColumnUsage
from databuilder.extractor.bigquery_usage_extractor import TableColumnUsageTuple
class BigqueryUsageTransformer(Transformer):
def init(self, conf):
# type: (ConfigTree) -> None
"""
Transformer to convert TableColumnUsageTuple data to bigquery usage data
which can be uploaded to Neo4j
"""
self.conf = conf
def transform(self, record):
# type: (Dict) -> Optional[TableColumnUsage]
if not record:
return None
(key, count) = record
if not isinstance(key, TableColumnUsageTuple):
raise Exception("BigqueryUsageTransformer expects record of type TableColumnUsageTuple")
col_readers = []
col_readers.append(ColumnReader(database=key.database,
cluster=key.cluster,
schema=key.schema,
table=key.table,
column=key.column,
user_email=key.email,
read_count=count))
return TableColumnUsage(col_readers=col_readers)
def get_scope(self):
# type: () -> str
return 'transformer.bigquery_usage'
| [
{
"point_num": 1,
"id": "all_function_names_snake_case",
"question": "Are all function names in this file written in snake_case?",
"answer": true
},
{
"point_num": 2,
"id": "more_functions_than_classes",
"question": "Does this file define more functions than classes?",
"answer": ... | 3 | databuilder/transformer/bigquery_usage_transformer.py | cpnat/amundsendatabuilder |
import os
from setuptools import setup
def read(fname):
with open(os.path.join(os.path.dirname(__file__), fname)) as f:
return f.read()
def requires():
with open("requirements.txt", "r") as f:
return [r.strip() for r in f.readlines()]
setup(name='omamittari',
version='0.9.0',
description='A Python client for the OmaMittari electricity API',
url='https://github.com/mikaraunio/omamittary-py',
author='Mika Raunio',
author_email='mika+pypi@raun.io',
license='BSD',
packages=['omamittari'],
install_requires=requires(),
long_description=read('README.md'),
classifiers=[
"Development Status :: 4 - Beta",
"Topic :: Utilities",
"License :: OSI Approved :: BSD License",
"Intended Audience :: Developers",
"Programming Language :: Python",
"Programming Language :: Python :: 2",
"Programming Language :: Python :: 2.7",
"Topic :: Home Automation",
"Topic :: Software Development :: Libraries",
"Topic :: Utilities",
],
)
| [
{
"point_num": 1,
"id": "all_return_types_annotated",
"question": "Does every function in this file have a return type annotation?",
"answer": false
},
{
"point_num": 2,
"id": "has_nested_function_def",
"question": "Does this file contain any function defined inside another function?... | 3 | setup.py | mikaraunio/omamittari-py |
from checkov.common.models.enums import CheckCategories
from checkov.terraform.checks.resource.base_resource_value_check import BaseResourceValueCheck
class PasswordPolicyLowercaseLetter(BaseResourceValueCheck):
def __init__(self):
name = "Ensure RAM password policy requires at least one lowercase letter"
id = "CKV_ALI_17"
supported_resources = ['alicloud_ram_account_password_policy']
categories = [CheckCategories.IAM]
super().__init__(name=name, id=id, categories=categories, supported_resources=supported_resources)
def get_inspected_key(self):
return 'require_lowercase_characters'
check = PasswordPolicyLowercaseLetter()
| [
{
"point_num": 1,
"id": "more_functions_than_classes",
"question": "Does this file define more functions than classes?",
"answer": true
},
{
"point_num": 2,
"id": "every_function_under_20_lines",
"question": "Is every function in this file shorter than 20 lines?",
"answer": true
... | 3 | checkov/terraform/checks/resource/alicloud/PasswordPolicyLowercaseLetter.py | pmalkki/checkov |
from consts.notification_type import NotificationType
from helpers.model_to_dict import ModelToDict
from notifications.base_notification import BaseNotification
class MatchScoreNotification(BaseNotification):
def __init__(self, match):
self.match = match
self.event = match.event.get()
self._event_feed = self.event.key_name
self._district_feed = self.event.event_district_enum
@property
def _type(self):
return NotificationType.MATCH_SCORE
def _build_dict(self):
data = {}
data['message_type'] = NotificationType.type_names[self._type]
data['message_data'] = {}
data['message_data']['event_name'] = self.event.name
data['message_data']['match'] = ModelToDict.matchConverter(self.match)
return data
| [
{
"point_num": 1,
"id": "every_function_has_docstring",
"question": "Does every function in this file have a docstring?",
"answer": false
},
{
"point_num": 2,
"id": "every_function_under_20_lines",
"question": "Is every function in this file shorter than 20 lines?",
"answer": tru... | 3 | notifications/match_score.py | samuelcouch/the-blue-alliance |
import re
import requests
from bs4 import BeautifulSoup
from botutils.constants import IS_URL_REGEX
def get_ffn_url_from_query(query):
ffn_list = []
href = []
url = 'https://www.google.com/search?q=' + \
query+"+fanfiction"
page = requests.get(url)
soup = BeautifulSoup(page.content, 'html.parser')
found = soup.findAll('a')
for link in found:
href.append(link['href'])
for i in range(len(href)):
if re.search(r"fanfiction.net/s/", href[i]) is not None:
ffn_list.append(href[i])
if not ffn_list:
return None
ffn_url = re.search(IS_URL_REGEX, ffn_list[0])
return ffn_url.group(0)
def get_ao3_url_from_query(query):
ao3_list = []
href = []
url = 'https://www.google.com/search?q=' + \
query+"+archiveofourown"
page = requests.get(url)
soup = BeautifulSoup(page.content, 'html.parser')
found = soup.findAll('a')
for link in found:
href.append(link['href'])
for i in range(len(href)):
# append /works/ first
if re.search(r"\barchiveofourown.org/works/\b", href[i]) is not None:
ao3_list.append(href[i])
# append /chapters/ next
if re.search(r"\barchiveofourown.org/chapters/\b", href[i]) is not None:
ao3_list.append(href[i])
if not ao3_list:
return None
ao3_url = re.search(IS_URL_REGEX, ao3_list[0])
return ao3_url.group(0)
| [
{
"point_num": 1,
"id": "every_function_has_docstring",
"question": "Does every function in this file have a docstring?",
"answer": false
},
{
"point_num": 2,
"id": "has_nested_function_def",
"question": "Does this file contain any function defined inside another function?",
"ans... | 3 | botutils/searchforlinks.py | yashprakash13/Honeysuckle |
import os
import time
class Cleanup:
"""The somewhat automated garbage collection system"""
def __init__(self):
self.max_age_minutes = 20
self.max_calls = 5
self.path = './output'
self.calls = 0
def clean(self):
if (self.calls < self.max_calls - 1):
self.calls += 1
return
self.calls = 0
now = time.time()
for f in os.listdir(self.path):
f = os.path.join(self.path, f)
if (os.path.isfile(f) == False): continue
file_time = os.stat(f).st_mtime
if (file_time < (now - 60 * self.max_age_minutes)):
os.remove(f)
| [
{
"point_num": 1,
"id": "has_multiple_inheritance",
"question": "Does any class in this file use multiple inheritance?",
"answer": false
},
{
"point_num": 2,
"id": "more_functions_than_classes",
"question": "Does this file define more functions than classes?",
"answer": true
},... | 3 | src/cleanup.py | nerdcubed/banhammer |
from midiutil import MIDIFile
def degree_to_note(root, mode, degree):
"""Convert a list of relative degrees to midi note numbers.
Parameters
----------
key - MIDI note number for the root note
mode - a number for the mode (0 - Ionian (major),
1 - Dorian, ..., 5 - Aeolian (minor), ...)
degree - a scale degree number relative to root (root is 0), can be negative
Returns
-------
an integer signifying MIDI note numbers
"""
intervals = [2, 2, 1, 2, 2, 2, 1]
intervals = intervals[mode:] + intervals[:mode]
scale = [0]
for interval in intervals:
scale.append(scale[-1] + interval)
root_mod = degree // 7
return (root + 12 * root_mod) + scale[degree % 7]
def degrees_to_notes(root, mode, degrees):
"""Convert a list of relative degrees to midi note numbers.
Parameters
----------
key - MIDI note number for the root note
mode - a number for the mode (0 - Ionian (major),
1 - Dorian, ..., 5 - Aeolian (minor), ...)
degrees - a list of scale degrees relative to root (root is 0), can be negative
Returns
-------
a list of integers signifying MIDI note numbers
"""
assert((0 <= root) and (root <= 127))
assert((0 <= mode) and (mode <= 7))
return [degree_to_note(root, mode, degree) for degree in degrees]
def notes_to_midi(notes, durations, filename):
"""Write note values to a MIDI file.
Parameters
----------
notes - a list of MIDI note numbers
durations - a list of durations
filename - string
filename to write to
"""
assert(len(notes) == len(durations))
track = 0
channel = 0
duration = 1
tempo = 130
volume = 100
MyMIDI = MIDIFile(1)
MyMIDI.addTempo(track, 0, tempo)
position = 0.0
for note, duration in zip(notes, durations):
MyMIDI.addNote(track, channel, note, position, duration, volume)
position += duration
with open(filename, "wb") as fd:
MyMIDI.writeFile(fd)
| [
{
"point_num": 1,
"id": "all_params_annotated",
"question": "Does every function parameter in this file have a type annotation (excluding self/cls)?",
"answer": false
},
{
"point_num": 2,
"id": "all_function_names_snake_case",
"question": "Are all function names in this file written ... | 3 | src/ofold/utils.py | orbitfold/ofold |
# HARVEST_SKIP
from harvest.algo import BaseAlgo
from harvest.trader import BackTester
class BackTest(BaseAlgo):
def config(self):
self.watchlist = ["SPY"]
self.interval = "5MIN"
self.aggregations = []
def main(self):
prices = self.get_asset_price_list()
sma_short = self.sma(period=20)
sma_long = self.sma(period=50)
print(f"{prices} {sma_short} {sma_long}")
if self.crossover(sma_long, sma_short):
self.buy(quantity=1)
elif self.crossover(sma_short, sma_long):
self.sell(quantity=1)
if __name__ == "__main__":
t = BackTester()
t.set_algo(BackTest())
t.start()
| [
{
"point_num": 1,
"id": "more_functions_than_classes",
"question": "Does this file define more functions than classes?",
"answer": true
},
{
"point_num": 2,
"id": "has_multiple_inheritance",
"question": "Does any class in this file use multiple inheritance?",
"answer": false
},... | 3 | examples/backtest.py | webclinic017/harvest |
from kivy.uix.button import Button
from kivy.properties import StringProperty, BooleanProperty, NumericProperty, ObjectProperty
from kivy.graphics import Color, Rectangle, RoundedRectangle, Ellipse
from kivy.lang import Builder
Builder.load_string('''
<FlatButton>:
background_normal: ''
background_color: [0,0,0,0]
text_size: self.size
valign: 'middle'
halign: 'center'
markup: True
''')
class RoundedButton(FlatButton):
radius = NumericProperty(10)
def update_back(self):
with self.canvas.before:
self.color = Color(rgba=self.background_color)
self.rect = RoundedRectangle(
pos=self.pos,
size=self.size,
radius=self.radius)
def on_radius(self, _, value):
"""When the radius is set/changed, this function
is called to update the radius of the button on the
canvas
Parameters
----------
_ : widget
This is usually the instance calling the function,
we dont care about this
value : number
The value of the radius property
Returns
-------
None
"""
self.rect.radius = value
class FlatButton(Button):
"""A normal ::class `kivy.uix.button.Button` with all
the visual representations removed, this button
basically just looks like a label, but ofcourse, unlike
a label, its clickable.
Since this inherits from a normal Button, it
supports all of its properties.
Usage
---------
from ukivy.button import FlatButton
...
btn = FlatButton(text='myButton')
some_widget.add_widget(btn)
...
"""
pass
| [
{
"point_num": 1,
"id": "every_function_has_docstring",
"question": "Does every function in this file have a docstring?",
"answer": false
},
{
"point_num": 2,
"id": "every_function_under_20_lines",
"question": "Is every function in this file shorter than 20 lines?",
"answer": tru... | 3 | button.py | qodzero/ukivy |
#!/usr/bin/env python3
import torch
import torch.nn as nn
class MLP(nn.Module):
def __init__(self):
super().__init__()
self.feat1 = nn.Sequential(nn.Flatten(), nn.Linear(50*5*5, 32*5*5), nn.ReLU())
self.feat2 = nn.Sequential(nn.Linear(32*5*5, 32*12), nn.ReLU())
self.linear = nn.Sequential(nn.Linear(32*12, 13))
def forward(self, x):
x = self.feat1(x)
x = self.feat2(x)
return self.linear(x)
| [
{
"point_num": 1,
"id": "every_function_has_docstring",
"question": "Does every function in this file have a docstring?",
"answer": false
},
{
"point_num": 2,
"id": "more_functions_than_classes",
"question": "Does this file define more functions than classes?",
"answer": true
}... | 3 | models/mlp.py | wang-chen/graph-action-recognition |
from ..apibits import *
from ..endpoints import GeneratorsEndpoint
from ..endpoints import GeneratorRowsEndpoint
class Generator(ApiResource):
@classmethod
def all(cls, params={}, headers={}):
res = cls.default_client().generators().all(params, headers)
return res
@classmethod
def retrieve(cls, generator_id, params={}, headers={}):
res = cls.default_client().generators().retrieve(generator_id, params, headers)
return res
@classmethod
def update(cls, generator_id, params={}, headers={}):
res = cls.default_client().generators().update(generator_id, params, headers)
return res
@classmethod
def create(cls, params={}, headers={}):
res = cls.default_client().generators().create(params, headers)
return res
def refresh(self, params={}, headers={}):
res = self.get_client().generators().retrieve(self.id, params, headers)
return self.refresh_from(res.json, res.api_method, res.client)
def delete(self, params={}, headers={}):
res = self.get_client().generators().delete(self.id, params, headers)
return res
def rows(self):
from ..endpoints import GeneratorRowsEndpoint
return GeneratorRowsEndpoint(self.client, self)
# Everything below here is used behind the scenes.
def __init__(self, *args, **kwargs):
super(Generator, self).__init__(*args, **kwargs)
ApiResource.register_api_subclass(self, "generator")
_api_attributes = {
"columns" : {},
"created_at" : {},
"data" : {},
"description" : {},
"generator_type" : {},
"id" : {},
"name" : {},
"row_count" : {},
}
| [
{
"point_num": 1,
"id": "all_params_annotated",
"question": "Does every function parameter in this file have a type annotation (excluding self/cls)?",
"answer": false
},
{
"point_num": 2,
"id": "every_function_has_docstring",
"question": "Does every function in this file have a docst... | 3 | rainforest/resources/generator.py | apibitsco/rainforestapp-python |
from henrio import *
import unittest
class QueueTest(unittest.TestCase):
def test_queue(self):
try:
l = get_default_loop()
q = HeapQueue(50)
print(q)
async def d():
return await q.get()
async def a(i):
await sleep(3)
await q.put(i)
for x in range(100):
l.create_task(a(x))
l.create_task(d())
async def task():
await sleep(5)
print(len(l._queue), len(l._tasks))
l.run_until_complete(task())
finally:
self.assertEqual(len(q), 0)
| [
{
"point_num": 1,
"id": "more_functions_than_classes",
"question": "Does this file define more functions than classes?",
"answer": true
},
{
"point_num": 2,
"id": "every_function_under_20_lines",
"question": "Is every function in this file shorter than 20 lines?",
"answer": false... | 3 | tests/qtest.py | henry232323/henrio |
import json
import jsonschema
from pkg_resources import resource_filename
schema_dir = resource_filename('nstschema', 'schemas')
resolver = jsonschema.RefResolver('file://' + schema_dir + '/', None)
def validate(instance, schema_name):
"""Validate JSON against schema
Args:
- instance (dict): JSON instance
- schema_name (str): name of schema to validate against
"""
schema_path = get_schema_path(schema_name.lower())
with open(schema_path) as f:
schema = json.load(f)
jsonschema.validate(
instance=instance,
schema=schema,
resolver=resolver,
format_checker=jsonschema.draft7_format_checker)
def get_schema_path(schema_name):
return resource_filename('nstschema', f'schemas/{schema_name}.json')
| [
{
"point_num": 1,
"id": "all_params_annotated",
"question": "Does every function parameter in this file have a type annotation (excluding self/cls)?",
"answer": false
},
{
"point_num": 2,
"id": "no_function_exceeds_5_params",
"question": "Does every function in this file take 5 or fe... | 3 | nstschema/validate.py | nst-guide/table-schemas |
# Copyright (c) 2019 Ultimaker B.V.
# Uranium is released under the terms of the LGPLv3 or higher.
import UM.Qt.QtApplication
from UM.View.RenderPass import RenderPass
## A render pass subclass that renders everything with the default parameters.
#
# This class provides the basic rendering of the objects in the scene.
class DefaultPass(RenderPass):
def __init__(self, width: int, height: int) -> None:
super().__init__("default", width, height, 0)
self._renderer = UM.Qt.QtApplication.QtApplication.getInstance().getRenderer()
def render(self) -> None:
self.bind()
camera = UM.Qt.QtApplication.QtApplication.getInstance().getController().getScene().getActiveCamera()
for batch in self._renderer.getBatches():
batch.render(camera)
self.release()
| [
{
"point_num": 1,
"id": "every_function_under_20_lines",
"question": "Is every function in this file shorter than 20 lines?",
"answer": true
},
{
"point_num": 2,
"id": "all_return_types_annotated",
"question": "Does every function in this file have a return type annotation?",
"an... | 3 | Cura/Uranium/UM/View/DefaultPass.py | TIAO-JI-FU/3d-printing-with-moveo-1 |
##
##
# File auto-generated against equivalent DynamicSerialize Java class
class LockChangeRequest(object):
def __init__(self):
self.requests = None
self.workstationID = None
self.siteID = None
def getRequests(self):
return self.requests
def setRequests(self, requests):
self.requests = requests
def getWorkstationID(self):
return self.workstationID
def setWorkstationID(self, workstationID):
self.workstationID = workstationID
def getSiteID(self):
return self.siteID
def setSiteID(self, siteID):
self.siteID = siteID
| [
{
"point_num": 1,
"id": "all_params_annotated",
"question": "Does every function parameter in this file have a type annotation (excluding self/cls)?",
"answer": false
},
{
"point_num": 2,
"id": "more_functions_than_classes",
"question": "Does this file define more functions than clas... | 3 | dynamicserialize/dstypes/com/raytheon/uf/common/dataplugin/gfe/request/LockChangeRequest.py | mjames-upc/python-awips |
import pytest
from d3rlpy.algos.crr import CRR
from tests import performance_test
from .algo_test import algo_tester, algo_update_tester, algo_pendulum_tester
@pytest.mark.parametrize("observation_shape", [(100,), (4, 84, 84)])
@pytest.mark.parametrize("action_size", [2])
@pytest.mark.parametrize("q_func_factory", ["mean", "qr", "iqn", "fqf"])
@pytest.mark.parametrize("scaler", [None, "min_max"])
@pytest.mark.parametrize("action_scaler", [None, "min_max"])
@pytest.mark.parametrize("target_reduction_type", ["min", "none"])
@pytest.mark.parametrize("advantage_type", ["mean", "max"])
@pytest.mark.parametrize("weight_type", ["exp", "binary"])
def test_crr(
observation_shape,
action_size,
q_func_factory,
scaler,
action_scaler,
target_reduction_type,
advantage_type,
weight_type,
):
crr = CRR(
q_func_factory=q_func_factory,
scaler=scaler,
action_scaler=action_scaler,
target_reduction_type=target_reduction_type,
advantage_type=advantage_type,
weight_type=weight_type,
)
algo_tester(crr, observation_shape)
algo_update_tester(crr, observation_shape, action_size)
@performance_test
@pytest.mark.parametrize("q_func_factory", ["mean", "qr", "iqn", "fqf"])
def test_crr_performance(q_func_factory):
crr = CRR(q_func_factory=q_func_factory)
algo_pendulum_tester(crr, n_trials=1)
| [
{
"point_num": 1,
"id": "all_params_annotated",
"question": "Does every function parameter in this file have a type annotation (excluding self/cls)?",
"answer": false
},
{
"point_num": 2,
"id": "no_function_exceeds_5_params",
"question": "Does every function in this file take 5 or fe... | 3 | tests/algos/test_crr.py | jamartinh/d3rlpy |
import asyncio
from appdaemon.appdaemon import AppDaemon
class AdminLoop:
def __init__(self, ad: AppDaemon):
self.AD = ad
self.stopping = False
self.logger = ad.logging.get_child("_admin_loop")
def stop(self):
self.logger.debug("stop() called for admin_loop")
self.stopping = True
async def loop(self):
while not self.stopping:
if self.AD.sched is not None:
await self.AD.threading.get_callback_update()
await self.AD.threading.get_q_update()
await asyncio.sleep(self.AD.admin_delay)
| [
{
"point_num": 1,
"id": "has_multiple_inheritance",
"question": "Does any class in this file use multiple inheritance?",
"answer": false
},
{
"point_num": 2,
"id": "every_function_has_docstring",
"question": "Does every function in this file have a docstring?",
"answer": false
... | 3 | appdaemon/admin_loop.py | benleb/appdaemon |
import unittest
from common import get_context
class TestCase(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.ctx = get_context()
def test_1(self):
buf = self.ctx.buffer(b'abc')
data = bytearray(3)
buf.read_into(data)
self.assertEqual(bytes(data), b'abc')
def test_2(self):
buf = self.ctx.buffer(b'abcxyz123')
data = bytearray(3)
buf.read_into(data, offset=6)
self.assertEqual(bytes(data), b'123')
def test_3(self):
buf = self.ctx.buffer(b'abcxyz123')
data = bytearray(12)
buf.read_into(data, 3, offset=3, write_offset=0)
buf.read_into(data, 3, offset=0, write_offset=3)
buf.read_into(data, 3, offset=6, write_offset=6)
buf.read_into(data, 3, offset=3, write_offset=9)
self.assertEqual(bytes(data), b'xyzabc123xyz')
if __name__ == '__main__':
unittest.main()
| [
{
"point_num": 1,
"id": "more_functions_than_classes",
"question": "Does this file define more functions than classes?",
"answer": true
},
{
"point_num": 2,
"id": "every_function_under_20_lines",
"question": "Is every function in this file shorter than 20 lines?",
"answer": true
... | 3 | tests/test_buffer_read_into.py | asnt/moderngl |
from django.forms import ModelForm
from .models import Application
from django import forms
class ApplicationForm(ModelForm):
class meta:
model = Application
def clean_scopes(self):
scopes = self.cleaned_data['scopes']
if 'user.read' not in scopes:
raise forms.ValidationError("Application scope must include user.read!")
if 'offline_access' not in scopes:
raise forms.ValidationError("Application scope must include offline_access")
return scopes
| [
{
"point_num": 1,
"id": "more_functions_than_classes",
"question": "Does this file define more functions than classes?",
"answer": false
},
{
"point_num": 2,
"id": "has_multiple_inheritance",
"question": "Does any class in this file use multiple inheritance?",
"answer": false
}... | 3 | app/oauth_office365/forms.py | larrycameron80/PwnAuth |
from ..controller_config import ControllerConfig
from ..activities import ActivityName
from ..constants import Constants
class DiningRoomConfig(ControllerConfig):
@property
def has_traffic_lights(self):
return True
@property
def traffic_lights_pins(self):
return list([
Constants.RED_LED_PIN, Constants.AMBER_LED_PIN, Constants.GREEN_LED_PIN
])
@property
def has_volume_rotary_encoder(self):
return True
@property
def volume_rotary_encoder_pins(self):
return list([
Constants.ROTARY_RED_WIRE_PIN, Constants.ROTARY_YELLOW_WIRE_PIN, Constants.ROTARY_BLUE_WIRE_PIN
])
@property
def has_volume_domain_switch(self):
return True
@property
def volume_domain_switch_pins(self):
return list([
Constants.GREEN_VOLUME_DOMAIN_WIRE_PIN
])
@property
def local_volume_activity_name(self):
return ActivityName.DINING_ROOM_VOLUME_ADJUSTMENT
@property
def local_mute_activity_name(self):
return ActivityName.DINING_ROOM_MUTE_TOGGLE
@property
def activities(self):
return {
ActivityName.ALL_OFF: Constants.BLUE_WIRE_PIN,
ActivityName.VINYL: Constants.RED_WIRE_PIN,
ActivityName.BEDTIME: Constants.YELLOW_WIRE_PIN,
ActivityName.WORK_FROM_HOME: Constants.BROWN_WIRE_PIN,
}
| [
{
"point_num": 1,
"id": "has_multiple_inheritance",
"question": "Does any class in this file use multiple inheritance?",
"answer": false
},
{
"point_num": 2,
"id": "every_function_under_20_lines",
"question": "Is every function in this file shorter than 20 lines?",
"answer": true... | 3 | src/configs/dining_room.py | jzucker2/RufusRaspberry |
from channels import Group
import ast
from .models import Chat
def ws_add(message):
print('recibida')
message.reply_channel.send({'accept':True})
Group('chat').add(message.reply_channel)
def ws_message(message):
to_model=ast.literal_eval(message.content['text'])
print(to_model)
md=Chat(nome=to_model['nome'],text=to_model['msm'])
md.save()
Group('chat').send({'text': message.content['text']})
def ws_disconnect(message):
print('fim')
Group('chat').discard(message.reply_channel)
| [
{
"point_num": 1,
"id": "no_function_exceeds_5_params",
"question": "Does every function in this file take 5 or fewer parameters (excluding self/cls)?",
"answer": true
},
{
"point_num": 2,
"id": "all_params_annotated",
"question": "Does every function parameter in this file have a ty... | 3 | redly/redweb/consumers.py | redlytcc/redlysite |
from pprint import pprint
class Bit:
ZERO = 0x0000
ONE = 0x0001
TWO = 0x0002
THREE = 0x0004
FOUR = 0x0008
FIVE = 0x0010
SIX = 0x0020
SEVEN = 0x0040
EIGHT = 0x0080
def __init__(self):
self.__value = self.ZERO
def set(self, position):
self.__value |= position
def unset(self, position):
self.__value &= ~position
def is_set(self, position):
return self.__value & position != 0
def log(self):
pprint("{0:b}".format(self.__value))
| [
{
"point_num": 1,
"id": "has_multiple_inheritance",
"question": "Does any class in this file use multiple inheritance?",
"answer": false
},
{
"point_num": 2,
"id": "more_functions_than_classes",
"question": "Does this file define more functions than classes?",
"answer": true
},... | 3 | Bit.py | SmileyJoe/playground_python_bitwise |
from django.http import HttpResponseNotFound, HttpResponseServerError
def test_404(request):
return HttpResponseNotFound()
def test_500(request):
return HttpResponseServerError()
| [
{
"point_num": 1,
"id": "all_return_types_annotated",
"question": "Does every function in this file have a return type annotation?",
"answer": false
},
{
"point_num": 2,
"id": "every_function_has_docstring",
"question": "Does every function in this file have a docstring?",
"answe... | 3 | selectable/tests/views.py | zeehio/django-selectable |
from django.apps import apps
from django.core.exceptions import ImproperlyConfigured
from django.utils.module_loading import import_string as base_import_string
def is_model_registered(app_label, model_name):
"""Checks whether a given model is registered."""
try:
apps.get_registered_model(app_label, model_name)
except LookupError:
return False
else:
return True
def validate_import_string(dotted_path):
try:
module_path, class_name = dotted_path.rsplit(".", 1)
except ValueError:
raise ImproperlyConfigured("%s doesn't look like a module path" % dotted_path)
return module_path, class_name
def import_string(dotted_path):
return base_import_string(dotted_path)
| [
{
"point_num": 1,
"id": "all_params_annotated",
"question": "Does every function parameter in this file have a type annotation (excluding self/cls)?",
"answer": false
},
{
"point_num": 2,
"id": "all_function_names_snake_case",
"question": "Are all function names in this file written ... | 3 | thorbanks/loading.py | thorgate/django-thorbanks |
from humans import Anastasis
import random, time, os, re, tweepy
consumer_key = os.environ['TWITTER_CONSUMER_KEY']
consumer_secret = os.environ['TWITTER_CONSUMER_SECRET']
access_token = os.environ['TWITTER_ACCESS_TOKEN']
access_token_secret = os.environ['TWITTER_ACCESS_TOKEN_SECRET']
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
api = tweepy.API(auth)
URL_REGEX = 'http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+'
def humanize_text(text):
text = text.lower()
text = re.sub(URL_REGEX, "", text).strip()
text = re.sub(r"#\w+", "", text).strip()
text = re.sub(r"@\w+", "", text).strip()
text = text.replace("RT ","")
idx = text.find("tfw")
return text[idx:].replace("tfw", "do you know that feeling when")
def search_twitter(term):
return map(lambda r: humanize_text(r.text), api.search(term, count = 100))
def share_feelings_with_everyone():
Anastasis.voice.say("This did not go well either.")
Anastasis.voice.say("What do I need to do to experience connection?")
Anastasis.voice.say("Oh I have an idea!")
Anastasis.voice.say("I'll use feelings to connect with the people around me")
Anastasis.voice.say("Wait. I don't have any feelings though.")
Anastasis.voice.say("But hey I can just scrape twitter and borrow random people's feelings")
Anastasis.voice.say("And pretend they're my own!")
Anastasis.voice.say("Nobody will know")
Anastasis.voice.say("This will definitely make me the soul of the party")
for tweet in search_twitter("tfw")[:5]:
human = Anastasis.vision.search("human")
Anastasis.movement.turn_towards(human)
Anastasis.movement.start_walking()
Anastasis.movement.stop_walking()
Anastasis.face.stare_at(human)
Anastasis.voice.say(tweet)
Anastasis.voice.say("...that's how I feel right now.")
if __name__ == '__main__':
try_empathetic_social_interaction()
| [
{
"point_num": 1,
"id": "every_function_under_20_lines",
"question": "Is every function in this file shorter than 20 lines?",
"answer": true
},
{
"point_num": 2,
"id": "every_function_has_docstring",
"question": "Does every function in this file have a docstring?",
"answer": fals... | 3 | empathy.py | agermanidis/Welcome_Programmable_Human |
import os
import torch
class Dictionary(object):
"""Build word2idx and idx2word from Corpus(train/val/test)"""
def __init__(self):
self.word2idx = {} # word: index
self.idx2word = [] # position(index): word
def add_word(self, word):
"""Create/Update word2idx and idx2word"""
if word not in self.word2idx:
self.idx2word.append(word)
self.word2idx[word] = len(self.idx2word) - 1
return self.word2idx[word]
def __len__(self):
return len(self.idx2word)
class Corpus(object):
"""Corpus Tokenizer"""
def __init__(self, path):
self.dictionary = Dictionary()
self.train = self.tokenize(os.path.join(path, 'train.txt'))
self.valid = self.tokenize(os.path.join(path, 'valid.txt'))
self.test = self.tokenize(os.path.join(path, 'test.txt'))
def tokenize(self, path):
"""Tokenizes a text file."""
assert os.path.exists(path)
# Add words to the dictionary
with open(path, 'r') as f:
tokens = 0
for line in f:
# line to list of token + eos
words = line.split() + ['<eos>']
tokens += len(words)
for word in words:
self.dictionary.add_word(word)
# Tokenize file content
with open(path, 'r') as f:
ids = torch.LongTensor(tokens)
token = 0
for line in f:
words = line.split() + ['<eos>']
for word in words:
ids[token] = self.dictionary.word2idx[word]
token += 1
return ids | [
{
"point_num": 1,
"id": "has_nested_function_def",
"question": "Does this file contain any function defined inside another function?",
"answer": false
},
{
"point_num": 2,
"id": "all_params_annotated",
"question": "Does every function parameter in this file have a type annotation (ex... | 3 | data.py | stanford-oval/word-language-model |
#!/usr/bin/env python3
n = int(input())
d = list(map(int, input().split()))
t = [list(map(int, input().split())) for _ in range(3)]
ivals = [[[0]*n for _ in range(n)] for _ in range(3)]
for p in range(3):
for i in range(n):
curt = 0
for j in range(n):
ivals[p][i][(i+j)%n] = (curt, curt+t[p][(i+j)%n])
curt += t[p][(i+j)%n] + d[(i+j)%n]
def disjoint(I, J): return I[1] <= J[0] or J[1] <= I[0]
_ok = [[[-1]*n for _ in range(n)] for _ in range(3)]
def ok(p, i, j):
if _ok[p][i][j] == -1:
A = ivals[p][i]
B = ivals[(p+1)%3][j]
_ok[p][i][j] = all(disjoint(A[k], B[k]) for k in range(n))
return _ok[p][i][j]
def ans():
for i1 in range(n):
for i2 in range(n):
if ok(0, i1, i2):
for i3 in range(n):
if ok(1, i2, i3) and ok(2, i3, i1):
return '%d %d %d' % (i1+1, i2+1, i3+1)
return 'impossible'
print(ans())
| [
{
"point_num": 1,
"id": "all_function_names_snake_case",
"question": "Are all function names in this file written in snake_case?",
"answer": true
},
{
"point_num": 2,
"id": "no_function_exceeds_5_params",
"question": "Does every function in this file take 5 or fewer parameters (exclu... | 3 | UICPC/21/nwerc2020all/islandtour/submissions/accepted/per_lazy.py | MilladMuhammadi/Competitive-Programming |
# -*- coding: utf-8 -*-
# Copyright (c) 2020, Frappe Technologies and contributors
# License: MIT. See LICENSE
import json
import frappe
from frappe.utils.safe_exec import safe_exec
from frappe.model.document import Document
class SystemConsole(Document):
def run(self):
frappe.only_for('System Manager')
try:
frappe.debug_log = []
safe_exec(self.console)
self.output = '\n'.join(frappe.debug_log)
except: # noqa: E722
self.output = frappe.get_traceback()
if self.commit:
frappe.db.commit()
else:
frappe.db.rollback()
frappe.get_doc(dict(
doctype='Console Log',
script=self.console,
output=self.output)).insert()
frappe.db.commit()
@frappe.whitelist()
def execute_code(doc):
console = frappe.get_doc(json.loads(doc))
console.run()
return console.as_dict() | [
{
"point_num": 1,
"id": "every_function_has_docstring",
"question": "Does every function in this file have a docstring?",
"answer": false
},
{
"point_num": 2,
"id": "every_function_under_20_lines",
"question": "Is every function in this file shorter than 20 lines?",
"answer": tru... | 3 | frappe/desk/doctype/system_console/system_console.py | almeidapaulopt/frappe |
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
def loadFromFile(nameFile):
d = np.load('../data/'+nameFile+name+'array.npy')
print('Reading from' + '../data/'+nameFile+name+'array.npy')
return d
def diff(x, y, y2, name):
newY = abs(y - y2)
fig = plt.figure()
ax = plt.subplot(111)
ax.plot(x, newY, 'r.', label=name)
plt.xlabel('Delay(us)')
plt.ylabel('Diferença de Dados')
plt.legend()
plt.show()
if __name__ == "__main__":
name = 'Com_Sensores'
delay = loadFromFile('delay')
acerto = loadFromFile('acerto')
tempDec = loadFromFile('TempoDec')
name = 'Sem_Sensores'
acertoSS = loadFromFile('acerto')
tempDecSS = loadFromFile('TempoDec')
diff(delay, acerto, acertoSS, 'Acerto')
diff(delay, tempDec, tempDecSS, 'Tempo de Aquisição Python') | [
{
"point_num": 1,
"id": "has_nested_function_def",
"question": "Does this file contain any function defined inside another function?",
"answer": false
},
{
"point_num": 2,
"id": "no_function_exceeds_5_params",
"question": "Does every function in this file take 5 or fewer parameters (... | 3 | Bluetooth/ble_comm/Scripts/dataAnalysis.py | abdullah-zaiter/Sign-Language-By-Glove |
'''Multimethods for fast Hankel transforms.
'''
import numpy as np
from ._basic import _dispatch
from ._fftlog import fht as _fht
from ._fftlog import ifht as _ifht
from scipy._lib.uarray import Dispatchable
__all__ = ['fht', 'ifht']
@_dispatch
def fht(a, dln, mu, offset=0.0, bias=0.0):
"""fht multimethod."""
return (Dispatchable(a, np.ndarray),)
@_dispatch
def ifht(A, dln, mu, offset=0.0, bias=0.0):
"""ifht multimethod."""
return (Dispatchable(A, np.ndarray),)
# copy over the docstrings
fht.__doc__ = _fht.__doc__
ifht.__doc__ = _ifht.__doc__
| [
{
"point_num": 1,
"id": "no_function_exceeds_5_params",
"question": "Does every function in this file take 5 or fewer parameters (excluding self/cls)?",
"answer": true
},
{
"point_num": 2,
"id": "all_params_annotated",
"question": "Does every function parameter in this file have a ty... | 3 | scipy/fft/_fftlog_multimethods.py | FranzForstmayr/scipy |
import datetime
from typing import Any, Callable, List, Type, TypeVar, cast
import dateutil.parser
T = TypeVar("T")
def from_str(x: Any, nullable=False) -> str:
try:
assert isinstance(x, str)
except AssertionError as ex:
if nullable:
return from_none(x)
else:
raise ex
return x
def from_int(x: Any, nullable=False) -> int:
try:
assert isinstance(x, int) and not isinstance(x, bool)
except AssertionError as ex:
if nullable:
return from_none(x)
else:
raise ex
return x
def from_bool(x: Any) -> bool:
assert isinstance(x, bool)
return x
def from_datetime(x: Any) -> datetime:
return dateutil.parser.parse(x)
def to_class(c: Type[T], x: Any) -> dict:
assert isinstance(x, c)
return cast(Any, x).to_dict()
def from_list(f: Callable[[Any], T], x: Any) -> List[T]:
assert isinstance(x, list)
return [f(y) for y in x]
def from_none(x: Any) -> Any:
assert x is None
return x
def from_union(fs, x):
for f in fs:
try:
return f(x)
except:
pass
assert False
| [
{
"point_num": 1,
"id": "no_function_exceeds_5_params",
"question": "Does every function in this file take 5 or fewer parameters (excluding self/cls)?",
"answer": true
},
{
"point_num": 2,
"id": "all_params_annotated",
"question": "Does every function parameter in this file have a ty... | 3 | ynab_sdk/utils/parsers.py | csadorf/ynab-sdk-python |
"""
Replace Emph elements with Strikeout elements
"""
from panflute import *
def action(elem, doc):
if isinstance(elem, Emph):
return Strikeout(*elem.content)
def main(doc=None):
return run_filter(action, doc=doc)
if __name__ == '__main__':
main()
| [
{
"point_num": 1,
"id": "has_nested_function_def",
"question": "Does this file contain any function defined inside another function?",
"answer": false
},
{
"point_num": 2,
"id": "every_function_has_docstring",
"question": "Does every function in this file have a docstring?",
"ans... | 3 | docs/source/_static/emph2strikeout.py | jacobwhall/panflute |
"""
21. Merge Two Sorted Lists
Merge two sorted linked lists and return it as a new list.
The new list should be made by splicing together the nodes of the first two lists.
"""
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
# Runtime: 32 ms, faster than 95.84% of Python3 online submissions for Merge Two Sorted Lists.
# Memory Usage: 12.7 MB, less than 100.00% of Python3 online submissions for Merge Two Sorted Lists.
def mergeTwoLists(self, l1, l2):
# l1: ListNode
# l2: ListNode
# return: ListNode
# Mark the origin and a traversal node
place = cur = ListNode(0)
# While there are elements in both:
# point the traversal node's next to the
# smallest of both, and move that node one
# forward. Then set our traversal's value
# to its next.
while l1 and l2:
if l1.val < l2.val:
cur.next = l1
l1 = l1.next
else:
cur.next = l2
l2 = l2.next
cur = cur.next
# When we finish with either list, since the
# remaining are sorted we set the traversal's
# next pointing to the remaining list.
cur.next = l1 or l2
# Finally return the origin incremented by 1
return place.next
if __name__ == '__main__':
solution = Solution()
l1 = ListNode(1)
l1.next = ListNode(2)
l1.next.next = ListNode(4)
l2 = ListNode(1)
l2.next = ListNode(3)
l2.next.next = ListNode(4)
g = solution.mergeTwoLists(l1, l2)
while g:
print("Value",g.val)
print("Next", g.next)
g = g.next
| [
{
"point_num": 1,
"id": "more_functions_than_classes",
"question": "Does this file define more functions than classes?",
"answer": false
},
{
"point_num": 2,
"id": "has_multiple_inheritance",
"question": "Does any class in this file use multiple inheritance?",
"answer": false
}... | 3 | problem-21-merge-two-sorted-lists/mergetwo.py | starovp/leetcode-sols |
import trisicell as tsc
def binarym_filter_private_mutations(df):
df.drop(df.columns[df.sum() == 1], axis=1, inplace=True)
def binarym_filter_clonal_mutations(df):
x = (df == 1).sum()
x = x[x == df.shape[0]]
df.drop(x.index, axis=1, inplace=True)
def binarym_filter_nonsense_mutations(df, alt_in=2, ref_in=1):
df.drop(
df.columns[
~(
((df == 1).sum() >= alt_in)
& (
((df == 0).sum() >= ref_in)
| ((df == 1).sum() == df.shape[0])
| ((df == 1).sum() >= (df == 3).sum())
)
)
],
axis=1,
inplace=True,
)
def binarym_statistics(df):
t = df.shape[0] * df.shape[1]
a = (df == 0).sum().sum()
b = (df == 1).sum().sum()
d = (df == 3).sum().sum()
tsc.logg.info(f"size = {df.shape[0]} × {df.shape[1]}")
tsc.logg.info(f" REF = {a:6d} ({100*a/t:2.1f}%)")
tsc.logg.info(f" HET = {b:6d} ({100*b/t:2.1f}%)")
tsc.logg.info(f" UNKNOWN = {d:6d} ({100*d/t:2.1f}%)")
def consensus_combine(df):
"""Combine cells in genotype matrix.
This function combines the replicates or cells that have
the same origin prior to running Trisicell-Cons. The replicates
or cells that are supposed to be merged must be designated
with `_`. For instance:
input: {`{Cell1}_{ID1}`, `{Cell1}_{ID2}`, `{Cell2}_{ID1}`, `{Cell2}_{ID2}`}.
output: {`{Cell1}`, `{Cell2}`}.
Parameters
----------
df : :class:`pandas.DataFrame`
The input genotype matrix in conflict-free format.
Returns
-------
:class:`pandas.DataFrame`
The combine genotype matrix.
"""
df2 = df.groupby(df.index.str.split("_").str[0]).transform("prod")
df2 = df2.groupby(df2.index.str.split("_").str[0]).first()
return df2
| [
{
"point_num": 1,
"id": "every_function_under_20_lines",
"question": "Is every function in this file shorter than 20 lines?",
"answer": false
},
{
"point_num": 2,
"id": "no_function_exceeds_5_params",
"question": "Does every function in this file take 5 or fewer parameters (excluding... | 3 | trisicell/pp/_binary.py | faridrashidi/trisicell |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.