source string | points list | n_points int64 | path string | repo string |
|---|---|---|---|---|
def credit(valor):
return ('Valor créditado R${:.2f}'.format(valor))
def debit(valor):
return('Valor debitado R${:.2f}'.format(valor))
| [
{
"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_return_types_annotated",
"question": "Does every function in this file have a return type annotation?",
"answe... | 3 | Curso Python Completo - Udemy/py/MeusModulos/ContaCorrente.py | Cauenumo/Python |
from django.test import TestCase
from adminplus.sites import AdminSitePlus
class AdminPlusTests(TestCase):
def test_decorator(self):
"""register_view works as a decorator."""
site = AdminSitePlus()
@site.register_view(r'foo/bar')
def foo_bar(request):
return 'foo-bar'
urls = site.get_urls()
assert any(u.resolve('foo/bar') for u in urls)
def test_function(self):
"""register_view works as a function."""
site = AdminSitePlus()
def foo(request):
return 'foo'
site.register_view('foo', view=foo)
urls = site.get_urls()
assert any(u.resolve('foo') for u in urls)
def test_path(self):
"""Setting the path works correctly."""
site = AdminSitePlus()
def foo(request):
return 'foo'
site.register_view('foo', view=foo)
site.register_view('bar/baz', view=foo)
site.register_view('baz-qux', view=foo)
urls = site.get_urls()
matches = lambda u: lambda p: p.resolve(u)
foo_urls = filter(matches('foo'), urls)
self.assertEqual(1, len(foo_urls))
bar_urls = filter(matches('bar/baz'), urls)
self.assertEqual(1, len(bar_urls))
qux_urls = filter(matches('baz-qux'), urls)
self.assertEqual(1, len(qux_urls))
def test_urlname(self):
"""Set URL pattern names correctly."""
site = AdminSitePlus()
@site.register_view('foo', urlname='foo')
def foo(request):
return 'foo'
@site.register_view('bar')
def bar(request):
return 'bar'
urls = site.get_urls()
matches = lambda u: lambda p: p.resolve(u)
foo_urls = filter(matches('foo'), urls)
self.assertEqual(1, len(foo_urls))
self.assertEqual('foo', foo_urls[0].name)
bar_urls = filter(matches('bar'), urls)
self.assertEqual(1, len(bar_urls))
assert bar_urls[0].name is None
| [
{
"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 | adminplus/tests.py | TabbedOut/django-adminplus |
#!/usr/bin/env python3
from requests import get
from os import environ
root = environ.get("SERVICE_ROOT", "http://localhost:3000")
def test_hello():
assert get("%s/hello" % root).text \
== "Dead kittens and suffering"
def test_ping():
assert "pong" in get("%s/ping" % root).text
def test_nonexistent():
assert get("%s/nonexistent" % root).status_code == 404
def test_root_redirect():
resp = get(root)
assert resp.history[0].status_code == 302
assert 'kittens' in resp.text
| [
{
"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_function_has_docstring",
"question": "Does every function in this file have a docstring?",
"answer":... | 3 | 5-webbisovellukset/nosetests/test_routes.py | pkalliok/python-kurssi |
import unittest
from flapi_schema.types import AnyOf
class AnyOfTest(unittest.TestCase):
def test_any_of(self):
rule = AnyOf(lambda _: True, lambda _: False)
self.assertTrue(rule({}))
def test_fails(self):
rule = AnyOf(lambda _: False, lambda _: False)
self.assertFalse(rule({}))
| [
{
"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 | tests/types/test_any_of.py | manoadamro/flapi-schema |
# -*- coding: utf-8 -*-
# Copyright 2018 by dhrone. All Rights Reserved.
#
import pytest
import json
from python_jsonschema_objects import ValidationError
from pyASH.exceptions import *
from pyASH.pyASH import pyASH
from pyASH.objects import Request
# Imports for v3 validation
import jsonschema
from jsonschema import validate
import json
from pyASH.validation import validate_message
@pytest.fixture
def setup():
request = {
"directive": {
"header": {
"namespace": "Alexa.PowerController",
"name": "TurnOff",
"payloadVersion": "3",
"messageId": "1bd5d003-31b9-476f-ad03-71d471922820",
"correlationToken": "dFMb0z+PgpgdDmluhJ1LddFvSqZ/jCc8ptlAKulUj90jSqg=="
},
"endpoint": {
"scope": {
"type": "BearerToken",
"token": "access-token-from-skill"
},
"endpointId": "dhroneTV:device_1",
"cookie": {}
},
"payload": {}
}
}
return Request(request)
def validate(request, response):
validateFailed = False
try:
validate_message(request, response)
except:
validateFailed=True
print ('Validation Error')
if validateFailed:
print (response)
raise Exception
def test_INTERNAL_ERROR(setup):
request = setup
try:
raise INTERNAL_ERROR('test message')
except pyASH_EXCEPTION as e:
response = pyASH._errorResponse(request, e)
validate(request, response)
def test_USER_NOT_FOUND_EXCEPTION(setup):
request = setup
try:
raise USER_NOT_FOUND_EXCEPTION('test message')
except pyASH_EXCEPTION as e:
response = pyASH._errorResponse(request, e)
validate(request, response)
| [
{
"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 | test/test_exceptions.py | dhrone/pyASH |
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import division
from __future__ import generators
from __future__ import nested_scopes
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import with_statement
from django.http import HttpResponse
from django.shortcuts import render_to_response
import codecs
def test_transfer(request):
return render_to_response('test_page.html')
def parameter_saver(request):
output_file = codecs.open('data/data.txt', 'a', encoding='utf8')
if request.GET:
output_file.write(str(request.GET) + '\n')
return HttpResponse("GET")
elif request.POST:
output_file.write(str(request.POST) + '\n')
return HttpResponse("POST")
output_file.close()
return HttpResponse("Hello World!") | [
{
"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 | Django/saver.py | JOHNKYON/Data_save |
# Copyright Jonathan Hartley 2013. BSD 3-Clause license, see LICENSE file.
import atexit
import contextlib
import sys
from .ansitowin32 import AnsiToWin32
orig_stdout = None
orig_stderr = None
wrapped_stdout = None
wrapped_stderr = None
atexit_done = False
def reset_all():
if AnsiToWin32 is not None: # Issue #74: objects might become None at exit
AnsiToWin32(orig_stdout).reset_all()
def init(autoreset=False, convert=None, strip=None, wrap=True):
if not wrap and any([autoreset, convert, strip]):
raise ValueError('wrap=False conflicts with any other arg=True')
global wrapped_stdout, wrapped_stderr
global orig_stdout, orig_stderr
orig_stdout = sys.stdout
orig_stderr = sys.stderr
if sys.stdout is None:
wrapped_stdout = None
else:
sys.stdout = wrapped_stdout = \
wrap_stream(orig_stdout, convert, strip, autoreset, wrap)
if sys.stderr is None:
wrapped_stderr = None
else:
sys.stderr = wrapped_stderr = \
wrap_stream(orig_stderr, convert, strip, autoreset, wrap)
global atexit_done
if not atexit_done:
atexit.register(reset_all)
atexit_done = True
def deinit():
if orig_stdout is not None:
sys.stdout = orig_stdout
if orig_stderr is not None:
sys.stderr = orig_stderr
@contextlib.contextmanager
def colorama_text(*args, **kwargs):
init(*args, **kwargs)
try:
yield
finally:
deinit()
def reinit():
if wrapped_stdout is not None:
sys.stdout = wrapped_stdout
if wrapped_stderr is not None:
sys.stderr = wrapped_stderr
def wrap_stream(stream, convert, strip, autoreset, wrap):
if wrap:
wrapper = AnsiToWin32(stream,
convert=convert, strip=strip, autoreset=autoreset)
if wrapper.should_wrap():
stream = wrapper.stream
return stream
| [
{
"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_function_under_20_lines",
"question": "Is every function in this file shorter than 20 lines?",
"answ... | 3 | TimeWrapper_JE/venv/Lib/site-packages/pip/_vendor/colorama/initialise.py | JE-Chen/je_old_repo |
"""String-related Templatetags"""
from django import template
# pylint: disable=invalid-name
register = template.Library()
@register.filter("padded_slice", is_safe=True)
def padded_slice_filter(value, page_number):
"""
Templatetag which takes a value and returns a padded slice
"""
try:
bits = []
padding = 5
page_number = int(page_number)
if page_number - padding < 1:
bits.append(None)
else:
bits.append(page_number - padding)
if page_number + padding > len(value):
bits.append(len(value))
else:
bits.append(page_number + padding)
return value[slice(*bits)]
except (ValueError, TypeError):
# Fail silently.
return value
@register.filter('input_type')
def input_type(form_field):
"""
Filter which returns the name of the formfield widget
"""
return form_field.field.widget.__class__.__name__
| [
{
"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": fals... | 3 | open_connect/connect_core/templatetags/string.py | lpatmo/actionify_the_news |
"""
DOCSTRING
The models store information on the players and their individual games.
"""
from sqlalchemy import Column, Integer, String, DateTime, ForeignKey
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship
Base = declarative_base()
class Player(Base):
"""
A table for players. Includes name and high score.
"""
__tablename__ = "players"
id = Column(Integer, primary_key=True)
name = Column(String(20), unique=True)
high_score = Column(Integer)
games = relationship("Game", backref="games", passive_deletes=True)
def __repr__(self):
return f"<Player (name = '{self.name}', high score = {self.high_score})>"
class Game(Base):
"""
A table for individual games. Includes player id, date, and score.
"""
__tablename__ = "games"
id = Column(Integer, primary_key=True)
score = Column(Integer)
date = Column(DateTime)
player_id = Column(Integer, ForeignKey(column="players.id", ondelete="CASCADE"))
def __repr__(self):
return f"<Game (player_id = '{self.player_id}', score = {self.score}, date = {self.date})>"
| [
{
"point_num": 1,
"id": "more_functions_than_classes",
"question": "Does this file define more functions than classes?",
"answer": false
},
{
"point_num": 2,
"id": "every_class_has_docstring",
"question": "Does every class in this file have a docstring?",
"answer": true
},
{
... | 3 | src/db/models.py | IsakJones/space_invaders |
import re
import hangups
def isEventNotification(update):
if update.event_notification:
return True
return False
def isMessageEvent(update):
if isEventNotification(update):
event = update.event_notification.event
if event.event_type == hangups.hangouts_pb2.EVENT_TYPE_REGULAR_CHAT_MESSAGE:
return True
return False
def newConversationFilter(conversationIdList):
return lambda event: hangups.ConversationEvent(event).conversation_id in conversationIdList
def newMessageFilter(regex):
pattern = re.compile(regex)
return lambda event: bool(pattern.match(hangups.ChatMessageEvent(event).text))
def newUserFilter(gaiaIdList):
return lambda event: hangups.ConversationEvent(event).user_id.gaia_id in gaiaIdList
| [
{
"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 | pearl/nacre/handle.py | dynosaur72/pearl |
class Take(object):
def __init__(self, stage, unit, entity,
not_found_proc, finished_proc):
self._stage = stage
self._unit = unit
self._entity = entity
self._finished_proc = finished_proc
self._not_found_proc = not_found_proc
def enact(self):
if not self._entity.location \
or self._entity.location != (self._unit.x, self._unit.y):
self._not_found_proc()
return
self._entity.location = None
self._stage.delete_entity(self._entity)
self._finished_proc()
return
| [
{
"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": "more_functions_than_classes",
"question": "Does this file define more functions than cla... | 3 | arctia/tasks/take.py | unternehmen/arctia |
import discord
async def get_role_based_on_reputation(self, guild, ranked_amount):
if ranked_amount >= 10:
return await get_role_from_db(self, "experienced_mapper", guild)
elif ranked_amount >= 1:
return await get_role_from_db(self, "ranked_mapper", guild)
else:
return await get_role_from_db(self, "mapper", guild)
async def get_role_from_db(self, setting, guild):
async with self.bot.db.execute("SELECT role_id FROM roles WHERE setting = ? AND guild_id = ?",
[setting, int(guild.id)]) as cursor:
role_id = await cursor.fetchone()
return discord.utils.get(guild.roles, id=int(role_id[0]))
| [
{
"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 | seija/reusables/verification.py | MapsetManagementServer/Seija |
import pandas as pd
def add_data(df, algorithm, data, elapsed, metric):
time_col = (data.name, 'Time(s)')
metric_col = (data.name, data.metric)
try:
df.insert(len(df.columns), time_col, '-')
df.insert(len(df.columns), metric_col, '-')
except:
pass
df.at[algorithm, time_col] = elapsed
df.at[algorithm, metric_col] = metric
def write_results(df, filename, format):
if format == "latex":
tmp_df = df.copy()
tmp_df.columns = pd.MultiIndex.from_tuples(tmp_df.columns)
with open(filename, "a") as file:
file.write(tmp_df.to_latex())
elif format == "csv":
with open(filename, "a") as file:
file.write(df.to_csv())
else:
raise ValueError("Unknown format: " + format)
print(format + " results written to: " + 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": "no_function_exceeds_5_params",
"question": "Does every function in this file take 5 or fewer parameters (excluding sel... | 3 | python/benchmarks/utils/file_utils.py | zeyiwen/gbdt |
import unittest
from passwords import Password
class TestAccount(unittest.TestCase):
def setUp(self):
"""
Set up method to run before each test cases
"""
self.new_password = Password("Instagram", "yahyanoor", "1234")
# The first test
def test_init(self):
"""
test_init test case to test if the object is initialized propely
"""
self.assertEqual(self.new_password.siteName, "Instagram")
self.assertEqual(self.new_password.user_name, "yahyanoor")
self.assertEqual(self.new_password.pass_word, "1234")
# The Second Test
def test_save_account(self):
"""
test_save_account is a test case to see if an account object is saved into the account list
"""
self.new_password.save_password()
self.assertEqual(len(Password.passwords), 1)
def tearDown(self):
"""
This method clear up after a test case is done
"""
Password.passwords = [] | [
{
"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 | passwords_test.py | yahyasaadi/passwordLocker |
#!/usr/bin/env python3
import utils, os, random, time, open_color, arcade
utils.check_version((3,7))
SCREEN_WIDTH = 1000
SCREEN_HEIGHT = 1000
SCREEN_TITLE = "Sprites Example"
class MyGame(arcade.Window):
def __init__(self):
super().__init__(SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_TITLE)
file_path = os.path.dirname(os.path.abspath(__file__))
os.chdir(file_path)
arcade.set_background_color(open_color.white)
self.character_list = arcade.SpriteList()
def setup(self):
x = 100
y = 300
characters = ["gary", "kk", "krabs", "patrick", "pearl", "plankton", "puff", "sandy", "spongebob", "squidward"]
for i in range(10):
character = characters[i]
self.character_sprite = arcade.Sprite("images/{character}.png".format(character=character), 0.4)
self.character_sprite.center_x = x
self.character_sprite.center_y = y
x = x + 250
if x >= 700:
x = 100
y = y + 200
self.character_list.append(self.character_sprite)
def on_draw(self):
arcade.start_render()
self.character_list.draw()
def update(self, delta_time):
pass
def on_mouse_motion(self, x, y, dx, dy):
self.character_sprite.center_x = x
self.character_sprite.center_y = y
def on_mouse_press(self, x, y, button, modifiers):
arcade.set_background_color(open_color.black);
def on_mouse_release(self, x, y, button, modifiers):
arcade.set_background_color(open_color.white);
def main():
""" Main method """
window = MyGame()
window.setup()
arcade.run()
if __name__ == "__main__":
main() | [
{
"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 | main4.py | Annuvian/E04a-Sprites |
import abc
class DBWriter(metaclass=abc.ABCMeta):
@abc.abstractmethod
async def store(self, message_box, message) -> bool:
raise NotImplementedError
@abc.abstractmethod
async def flush(self, flush_all=False) -> None:
raise NotImplementedError
| [
{
"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_return_types_annotated",
"question": "Does every function in this file have a return ... | 3 | circle_core/writer/base.py | glucoseinc/CircleCore |
import string
def find_all_lines(file_path):
with open("text.txt", "r") as file:
all_lines = file.read().split("\n")
return all_lines
def find_count_letters(current_line):
count = 0
for char in current_line:
if char.isalpha():
count += 1
return count
def find_count_marks(current_line):
count_marks = 0
for mark in punctuation_marks:
count_marks += line.count(mark)
return count_marks
punctuation_marks = string.punctuation
lines = find_all_lines("text.txt")
for idx, line in enumerate(lines):
count_letters = find_count_letters(line)
count_marks = find_count_marks(line)
new_line = f'Line {idx + 1}: ' + line + f' ({count_letters})({count_marks})'
with open("output.txt", "a") as file:
file.write(f"{new_line}\n")
| [
{
"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_function_names_snake_case",
"question": "Are all function names in this file written in snake_case?",
"answ... | 3 | Python Advanced/File Handling/Exercise/line_numbers.py | DonikaChervenkova/SoftUni |
# TvNorm.py
import torch
import torch.nn as nn
class TvNorm(nn.Module):
"""
normalization using the total variation; idea is to normalize pixel-wise by the length of the feature vector, i.e.,
MATLAB notation:
z = diag( 1/ sqrt( sum(x.^2,3)+eps)) x
Attributes:
eps: small float so no division by 0
weight: scaling weight for the affine transformation
bias: bias for the affine transformation
"""
def __init__(self, nChan, eps=1e-4):
"""
:param nChan: number of channels for the data you expect to normalize
:param eps: small float so no division by 0
"""
super().__init__()
self.eps = eps
# Tv Norm has no tuning of the scaling weights
# self.weight = nn.Parameter(torch.ones(nChan))
self.register_buffer('weight', torch.ones(nChan))
self.bias = nn.Parameter(torch.zeros(nChan))
def forward(self,x):
"""
:param x: inputs tensor, second dim is channels
example dims: (num images in the batch , num channels, height , width)
:return: normalized version with same dimensions as x
"""
z = torch.pow(x, 2)
z = torch.div(x, torch.sqrt(torch.sum(z, dim=1, keepdim=True) + self.eps))
# assumes that Tensor is formatted ( something , no. of channels, something, something, etc.)
if self.weight is not None:
w = self.weight.unsqueeze(0) # add first dimension
w = w.unsqueeze(-1) # add last dimension
w = w.unsqueeze(-1) # add last dimension
z = z * w
if self.bias is not None:
b = self.bias.unsqueeze(0) # add first dimension
b = b.unsqueeze(-1) # add last dimension
b = b.unsqueeze(-1) # add last dimension
z = z + b
return z
| [
{
"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 | modules/TvNorm.py | EmoryMLIP/DynamicBlocks |
import traceback
import logging
import pkg_resources
from sqlalchemy.exc import SQLAlchemyError
from dispatch.plugins.base import plugins, register
logger = logging.getLogger(__name__)
# Plugin endpoints should determine authentication # TODO allow them to specify (kglisson)
def install_plugin_events(api):
"""Adds plugin endpoints to the event router."""
for plugin in plugins.all():
if plugin.events:
api.include_router(plugin.events, prefix="/events", tags=["events"])
def install_plugins():
"""
Installs plugins associated with dispatch
:return:
"""
for ep in pkg_resources.iter_entry_points("dispatch.plugins"):
logger.info(f"Attempting to load plugin: {ep.name}")
try:
plugin = ep.load()
register(plugin)
logger.info(f"Successfully loaded plugin: {ep.name}")
except SQLAlchemyError:
logger.error(
"Something went wrong with creating plugin rows, is the database setup correctly?"
)
except KeyError as e:
logger.info(f"Failed to load plugin {ep.name} due to missing configuration items. {e}")
except Exception:
logger.error(f"Failed to load plugin {ep.name}:{traceback.format_exc()}")
def get_plugin_properties(json_schema):
for _, v in json_schema["definitions"].items():
return v["properties"]
| [
{
"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/dispatch/common/utils/cli.py | sfc-gh-pkommini/dispatch |
from typing import TYPE_CHECKING, Optional
from app.models import TimestampedModel, models
from studying.models import Study
if TYPE_CHECKING:
from chains.models.chain import Chain
class ProgressQuerySet(models.QuerySet):
def get_last_progress(self, chain: 'Chain', study: Study) -> Optional['Progress']:
return self.filter(study=study, message__chain=chain).order_by('-created').first()
class Progress(TimestampedModel):
objects = models.Manager.from_queryset(ProgressQuerySet)()
study = models.ForeignKey('studying.Study', on_delete=models.CASCADE)
message = models.ForeignKey('chains.Message', on_delete=models.CASCADE)
success = models.BooleanField(default=True)
class Meta:
constraints = [
models.UniqueConstraint(fields=['study', 'message'], name='single_message_per_study'),
]
indexes = [
models.Index(fields=['study', 'message']),
]
def __str__(self) -> str:
return f'{self.study.student.email} {self.message.template_id}'
__all__ = [
'Progress',
]
| [
{
"point_num": 1,
"id": "has_multiple_inheritance",
"question": "Does any class in this file use multiple inheritance?",
"answer": false
},
{
"point_num": 2,
"id": "all_return_types_annotated",
"question": "Does every function in this file have a return type annotation?",
"answer... | 3 | src/chains/models/progress.py | tough-dev-school/education-backend |
import pytest
from django.urls import resolve, reverse
from ginger_arxiv.users.models import User
pytestmark = pytest.mark.django_db
def test_detail(user: User):
assert (
reverse("users:detail", kwargs={"username": user.username})
== f"/users/{user.username}/"
)
assert resolve(f"/users/{user.username}/").view_name == "users:detail"
def test_update():
assert reverse("users:update") == "/users/~update/"
assert resolve("/users/~update/").view_name == "users:update"
def test_redirect():
assert reverse("users:redirect") == "/users/~redirect/"
assert resolve("/users/~redirect/").view_name == "users:redirect"
| [
{
"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 | ginger_arxiv/users/tests/test_urls.py | pjhoberman/ginger-arxiv |
import os
import math
from PIL import Image
import requests
from io import BytesIO
from torchvision import transforms, utils
class DataLoader():
def __init__(self):
pass
def load(self, url, size):
try:
response = requests.get(url)
img = Image.open(BytesIO(response.content)).convert('RGB')
except:
return None
t = transforms.Compose([transforms.Resize(size),
transforms.CenterCrop(size),
transforms.RandomHorizontalFlip(),
transforms.ToTensor(),
# transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
])
res = (t(img) * 255).int()
return res.reshape((size*size*3))
def save_imagenet_subset(self, root, name, class_wnids, image_size, max_images=None):
with open(os.path.join(root, name) + '.data', 'w+') as data:
with open(os.path.join(root, name) + '.label', 'w+') as label:
for i, wnid in enumerate(class_wnids):
urls = requests.get('http://www.image-net.org/api/text/imagenet.synset.geturls?wnid=' + wnid).content
urls = urls.split(b"\n")
images = 0
for u in range(len(urls)):
if max_images is not None and images+1 > max_images / len(class_wnids):
break
img = self.load(urls[u].decode('utf-8'), image_size)
if img is None:
continue
images += 1
data.write(' '.join([str(rgb) for rgb in img.numpy()]) + '\n')
label.write(str(i) + '\n')
missing = math.floor(max_images/len(class_wnids)) - images
if missing > 0:
print('Wnid', wnid, 'needs', missing, 'more images.') | [
{
"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 | autoPyTorch/data_management/data_loader.py | mens-artis/Auto-PyTorch |
# coding: utf-8
"""
OpenAPI Petstore
This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501
The version of the OpenAPI document: 1.0.0
Generated by: https://openapi-generator.tech
"""
from __future__ import absolute_import
import unittest
import petstore_api
from petstore_api.api.another_fake_api import AnotherFakeApi # noqa: E501
class TestAnotherFakeApi(unittest.TestCase):
"""AnotherFakeApi unit test stubs"""
def setUp(self):
self.api = AnotherFakeApi() # noqa: E501
def tearDown(self):
pass
def test_call_123_test_special_tags(self):
"""Test case for call_123_test_special_tags
To test special tags # noqa: E501
"""
pass
if __name__ == '__main__':
unittest.main()
| [
{
"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": "every_function_has_docstring",
"question": "Does every function in this file have a docstring?",
"answer"... | 3 | samples/client/petstore/python-experimental/test/test_another_fake_api.py | therockstorm/openapi-generator |
import psutil
def cpu(locacao):
cpu_freq = psutil.cpu_freq() # 0-Freq atual 1-min 2-max
cpu_percent = psutil.cpu_percent(interval=0.1) # porcentagem de uso do processador
cpu_status = (str(int(cpu_freq[0]))+ ' Ghz' , str(int(cpu_freq[1]))+ ' Ghz', str(int(cpu_freq[2]))+ ' Ghz', int(cpu_percent))
return cpu_status[locacao]
def memoria(Locacao):
memory = psutil.virtual_memory() # 0-total bit 1-usavel 2-porcentagem de uso 3-usado 4-livre
ram_memory = (memory[0]/1000000,memory[1]/1000000,memory[2],memory[3]/1000000,memory[4]/1000000)
memo = (str(int(ram_memory[0])) + ' Mb',str(int(ram_memory[1])) + ' Mb',int(ram_memory[2]),str(int(ram_memory[3])) + ' Mb',str(int(ram_memory[4])) + ' Mb')
return memo[Locacao]
def disco(Locacao):
disk_partitions = psutil.disk_partitions() # 0-local 1-ponto de montagem 2-type 3-opts 4-tamanho max de nome
disk_usage = psutil.disk_usage("C://") # 0-tamanho total byte 1-usado 2-vazio 3-porcentagem de de alocação
disk_user = (disk_usage[0]/1000000000,disk_usage[1]/1000000000,disk_usage[2]/1000000000,disk_usage[3])
disk_status = ('%.2f GB' % float(disk_user[0]), '%.2f GB' % float(disk_user[1]), '%.2f GB' % float(disk_user[2]), int(disk_user[3]))
return disk_status[Locacao]
| [
{
"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 | Codigo Fonte/Func_monitor.py | Kaioguilherme1/Monitor_de_processos_Pyside2 |
import six
if six.PY3:
long = int # pragma: PY3
else:
long = long # pragma: PY2
def b(arg):
"""Convert `arg` to bytes."""
if isinstance(arg, six.text_type):
arg = arg.encode("latin-1")
return arg
def u(arg):
"""Convert `arg` to text."""
if isinstance(arg, six.binary_type):
arg = arg.decode('ascii', 'replace')
return arg
| [
{
"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": true... | 3 | src/AuthEncoding/compat.py | gocept/AuthEncoding |
#!/usr/bin/env python
import fileinput
DELTAS = {
'U': (0, 1),
'D': (0, -1),
'L': (-1, 0),
'R': (1, 0),
}
def trace(path):
x, y = 0, 0
grid = {}
n = 1
for direction, d in path:
dx, dy = DELTAS[direction]
for i in range(0, d):
x += dx
y += dy
xy = (x, y)
if xy not in grid:
grid[xy] = n
n += 1
return grid
def parse_path(path_str):
return [(part[0], int(part[1:])) for part in path_str.split(',')]
def manhattan(xy):
return abs(xy[0]) + abs(xy[1])
def find_intersections(grid1, grid2):
return [
*sorted((
(grid1[xy] + grid2[xy], xy)
for xy in grid1.keys()
if xy in grid2)
)
]
if __name__ == '__main__':
wires = [parse_path(line) for line in fileinput.input()]
wire1, wire2 = wires
ixns = find_intersections(trace(wire1), trace(wire2))
print(ixns)
| [
{
"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 | day3.py | danvk/advent2019 |
import os
import sys
import platform
import datetime
from pathlib import Path
import skimage.color
import imageio
import sunpy.io.fits
BITFACTOR = 255
def get_created_time(path_to_file):
if platform.system() == 'Windows':
return os.path.getctime(path_to_file)
else:
stat = os.stat(path_to_file)
try:
return datetime.datetime.fromtimestamp(
stat.st_birthtime or stat.st_ctime
)
except AttributeError:
return datetime.datetime.fromtimestamp(stat.st_mtime)
def convert_png_to_fits(read_path, write_path):
if isinstance(read_path, str):
read_path = Path(read_path)
if isinstance(write_path, str):
write_path = Path(write_path)
write_path.mkdir(exist_ok=True)
all_files = read_path.glob('**/*')
png_files = [
x for x in all_files if x.is_file() and
x.name.endswith('.png')
]
for png_file in png_files:
try:
im = skimage.color.rgb2gray(
imageio.imread(
png_file
)
) * BITFACTOR
except Exception:
sys.stdout.write(
'Invalid Image file: {}\n'.format(
png_file.absolute()
)
)
continue
png_filename = png_file.name + '.fits'
write_path_fits = write_path / png_filename
header = dict()
header['obstime'] = get_created_time(png_file).isoformat()
sunpy.io.fits.write(write_path_fits, im, header, overwrite=True)
| [
{
"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": "has_nested_function_def",
"question": "Does this file contain any function defined inside another function?",
... | 3 | convert_all_to_fits.py | harshmathur1990/CollegeLevelSpectrograph |
import pytest
@pytest.fixture(scope="session")
def setupSession2():
print("\nSetting up Session 2")
@pytest.fixture(scope="module", autouse=True)
def setupModule2():
print("\nSetting up Module 2")
@pytest.fixture(scope="function", autouse=True)
def setupFunction2():
print("\nSetting up Function 2")
@pytest.fixture(scope="class", autouse=True)
def setupClass2():
print("\nSetting up Class 2")
class TestClass:
def test1(self):
print("\nTest 1 of Class")
def test2(self):
print("\nTest 2 of Class")
| [
{
"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 | python/test_file2.py | anbansal/TDD |
import time
import unittest
from signage_air_quality.air_quality_packet import AirQualityPacket
class TestAirQualityPacket(unittest.TestCase):
def test_to_bytes(self):
now = time.strptime("Mon Jan 13 21:00:00 2020")
timestamp = int(time.mktime(now))
packet = AirQualityPacket(56, 'O3', timestamp).to_bytes()
self.assertEqual(chr(packet[0]) + chr(packet[1]), "!Q")
self.assertEqual(packet[2], 56) # little-endian
self.assertEqual(packet[3], 0) # little-endian
self.assertEqual(chr(packet[4]), "O")
def test_from_bytes(self):
bs = b'!Q8\x00O\xa0 \x1d^\xcb'
packet = AirQualityPacket.from_bytes(bs)
self.assertEqual(packet.metric, 'O3')
self.assertEqual(packet.value, 56)
self.assertEqual(packet.timestamp, 1578967200)
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_air_quality_packet.py | ulfmagnetics/signage_air_quality |
######################################################################
# Copyright (c)
# John Holland <john@zoner.org>
# All rights reserved.
#
# This software is licensed as described in the file LICENSE.txt, which
# you should have received as part of this distribution.
#
######################################################################
"""
Visitor - Visits an error_handler composite
"""
class error_visitor(object):
"""
"""
def __init__(self, fd):
"""
Params: fd - target file
"""
pass
def visit_root_pre(self, errh):
"""
@param errh: Error handler
@type errh: L{error_handler.err_handler}
"""
pass
def visit_root_post(self, errh):
"""
@param errh: Error handler
@type errh: L{error_handler.err_handler}
"""
pass
def visit_isa_pre(self, err_isa):
pass
def visit_isa_post(self, err_isa):
"""
Params: err_isa - error_isa instance
"""
pass
def visit_gs_pre(self, err_gs):
pass
def visit_gs_post(self, err_gs):
"""
Params: err_gs - error_gs instance
"""
pass
def visit_st_pre(self, err_st):
pass
def visit_st_post(self, err_st):
"""
Params: err_st - error_st instance
"""
pass
def visit_seg(self, err_seg):
"""
Params: err_seg - error_seg instance
"""
pass
def visit_ele(self, err_ele):
"""
Params: err_ele - error_ele instance
"""
pass
| [
{
"point_num": 1,
"id": "has_multiple_inheritance",
"question": "Does any class in this file use multiple inheritance?",
"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 | pyx12/error_visitor.py | arenius/pyx12 |
class GitManager:
def __init__(self, executor):
self.executor = executor
def clone(self, host, remote_url, target_dir):
self.executor.execute(host, f"git clone {remote_url} {target_dir}")
def fetch(self, host, target_dir, remote="origin"):
self.executor.execute(host, f"git -C {target_dir} fetch --prune --tags {remote}")
def checkout(self, host, target_dir, branch="main"):
self.executor.execute(host, f"git -C {target_dir} checkout {branch}")
def rebase(self, host, target_dir, remote="origin", branch="main"):
self.executor.execute(host, f"git -C {target_dir} rebase {remote}/{branch}")
def get_revision_from_timestamp(self, host, target_dir, timestamp):
get_revision_from_timestamp_command = f"git -C {target_dir} rev-list -n 1 --before=\"{timestamp}\" --date=iso8601 origin/main"
return self.executor.execute(host, get_revision_from_timestamp_command, output=True)[0].strip()
def get_revision_from_local_repository(self, host, target_dir):
return self.executor.execute(host, f"git -C {target_dir} rev-parse --short HEAD", output=True)[0].strip()
| [
{
"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 | osbenchmark/builder/utils/git_manager.py | engechas/opensearch-benchmark |
import os.path
import numpy as np
import librosa
from pydub import AudioSegment
def chunk(incoming, n_chunk):
input_length = incoming.shape[1]
chunk_length = input_length // n_chunk
outputs = []
for i in range(incoming.shape[0]):
for j in range(n_chunk):
outputs.append(incoming[i, j*chunk_length:(j+1)*chunk_length, :])
outputs = np.array(outputs)
return outputs
def audio_read(f):
y, sr = librosa.core.load("data" + os.path.sep + f.name, sr=22050)
d = librosa.core.get_duration(y=y, sr=sr)
S = librosa.feature.melspectrogram(y, sr=sr, n_fft=2048, hop_length=512, n_mels=128)
S = np.transpose(np.log(1+10000*S))
S = np.expand_dims(S, axis=0)
return y, S, int(d)
def positional_encoding(batch_size, n_pos, d_pos):
# keep dim 0 for padding token position encoding zero vector
position_enc = np.array([
[pos / np.power(10000, 2 * (j // 2) / d_pos) for j in range(d_pos)]
if pos != 0 else np.zeros(d_pos) for pos in range(n_pos)])
position_enc[1:, 0::2] = np.sin(position_enc[1:, 0::2]) # dim 2i
position_enc[1:, 1::2] = np.cos(position_enc[1:, 1::2]) # dim 2i+1
position_enc = np.tile(position_enc, [batch_size, 1, 1])
return position_enc
| [
{
"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 | pop_music_highlighter/lib.py | ka5par/MIR |
import os
import datetime
import hashlib
import pexpect
from config import *
from common import openssl, jsonMessage, gencrl
from OpenSSL import crypto
# 通过证书文件吊销证书
def revokeFromCert(cert):
# 读取证书数据
try:
x509_obj = crypto.load_certificate(crypto.FILETYPE_PEM, cert)
# get_serial_number返回10进制的serial,需转为16进制
serial = hex(x509_obj.get_serial_number())[2:]
except crypto.Error:
return jsonMessage(status=-1,
msg="[ERROR]: Wrong certificate (X509) format!")
# 存到临时文件夹里
path = os.path.join(
'/tmp',
hashlib.md5(str(datetime.datetime.now()).encode('utf-8')).hexdigest() +
"_revokecert.crt")
with open(path, "w") as f:
f.write(cert.decode('utf8'))
return revoking(path, serial)
# 通过serial吊销证书,方法是去CA/newcerts文件夹下寻找相应证书的备份
# @serial:必须为16进制格式
def revokeFromSerial(serial):
path = os.path.join(CA_NEWCERTS, serial + ".pem")
if not os.path.exists(path):
msg = "[ERROR]: This may be an invalid serial number!"
return jsonMessage(-1, msg)
return revoking(path, serial)
def revoking(certfile, serial):
child = openssl('ca', '-revoke', certfile)
ret = child.expect(
['Already revoked', 'Revoking Certificate', pexpect.EOF])
if ret == 0:
msg = "[ERROR]: This certificate is revoked!"
return jsonMessage(-1, msg)
elif ret == 1:
msg = "Revoke Certificate success! Serial number is " + serial
# 重新生成一遍证书文件
gencrl()
return jsonMessage(0, msg, {"Serial Number": serial})
elif ret == 2:
msg = "[ERROR]: Revoke failed, unknown error!"
return jsonMessage(-1, msg)
| [
{
"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 | revoke.py | jarviswwong/openssl-ca-server |
# THIS FILE IS AUTO-GENERATED. DO NOT EDIT
from verta._swagger.base_type import BaseType
class ModeldbGetExperimentRunByNameResponse(BaseType):
def __init__(self, experiment_run=None):
required = {
"experiment_run": False,
}
self.experiment_run = experiment_run
for k, v in required.items():
if self[k] is None and v:
raise ValueError('attribute {} is required'.format(k))
@staticmethod
def from_json(d):
from .ModeldbExperimentRun import ModeldbExperimentRun
tmp = d.get('experiment_run', None)
if tmp is not None:
d['experiment_run'] = ModeldbExperimentRun.from_json(tmp)
return ModeldbGetExperimentRunByNameResponse(**d)
| [
{
"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 | client/verta/verta/_swagger/_public/modeldb/model/ModeldbGetExperimentRunByNameResponse.py | stefan-petrov-toptal/modeldb |
from functools import wraps
from django.http import HttpResponseRedirect
from .utils import get_dropbox_auth_flow
from .views import DROPBOX_ACCESS_TOKEN
def require_dropbox_session(next_url=None):
"""
Any view that is wrapped with this will redirect to the dropbox authorization site if the user does not
have an access_token in their session.
@params
next_url - The next_url to go to after redirect. Can be a function or string. If it's a function it will
receive the same parameters as the view
"""
def decorator(view_func):
@wraps(view_func)
def inner(request, *args, **kwargs):
if not request.session.get(DROPBOX_ACCESS_TOKEN, None):
url = '/'
if hasattr(next_url, '__call__'):
url = next_url(request, *args, **kwargs)
elif next_url:
url = next_url
request.session['dropbox_next_url'] = url
authorize_url = get_dropbox_auth_flow(request.session).start()
return HttpResponseRedirect(authorize_url)
return view_func(request, *args, **kwargs)
return inner
return decorator
| [
{
"point_num": 1,
"id": "has_nested_function_def",
"question": "Does this file contain any function defined inside another function?",
"answer": true
},
{
"point_num": 2,
"id": "every_function_has_docstring",
"question": "Does every function in this file have a docstring?",
"answ... | 3 | corehq/apps/dropbox/decorators.py | dimagilg/commcare-hq |
def identity(x):
return x
def always_false(x):
return False
def always_true(x):
return True
def add(x, y):
return x + y
| [
{
"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/functions.py | apragacz/functoolsplus |
import logging
from subprocess import Popen, PIPE, STDOUT
from lib.parse.sen_ascii_parse import SenAsciiParse
class SenBinParse:
def __init__(self):
self.ascii_parser = SenAsciiParse()
def parse_packet(self, packet, with_header=True):
if len(packet) < 10:
return
length = len(packet)
status = 0
data = packet
invalid_chunks = 0
if with_header:
length, status = packet[:2]
data = packet[2:-1]
invalid_chunks = packet[-1]
logging.debug("BIN IN: CHK=%d" % invalid_chunks)
#if invalid_chunks != 0:
# return
parser = Popen(['moveon-sen-parser', str(invalid_chunks)], stdout=PIPE, stdin=PIPE, stderr=STDOUT)
stdout = parser.communicate(input=data)[0]
logging.debug("BIN OUT: %s" % stdout.strip().decode())
for line in stdout.decode().splitlines():
for data in self.ascii_parser.parse_packet(line, "com"):
yield data
| [
{
"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": "more_functions_than_classes",
"question": "Does this file define more functions than classes?",
"answer": true... | 3 | tools/grafana/daemon/lib/parse/sen_bin_parse.py | Flowm/move-on-helium-sensors |
import os
import pytest
from xebec.src import _validate as vd
def test_validate_table(data_paths, tmp_path):
err_biom = os.path.join(tmp_path, "err.biom")
with open(err_biom, "w") as f:
f.write("kachow")
with pytest.raises(ValueError) as exc_info:
vd.validate_table(err_biom)
exp_err_msg = "Table is empty!"
assert str(exc_info.value) == exp_err_msg
with pytest.raises(FileNotFoundError) as exc_info:
vd.validate_table("NOT A FILE")
exp_err_msg = "[Errno 2] No such file or directory: 'NOT A FILE'"
assert str(exc_info.value) == exp_err_msg
def test_validate_metadata(data_paths, tmp_path):
err_md = os.path.join(tmp_path, "err.tsv")
with open(err_md, "w") as f:
f.write("kerblam")
with pytest.raises(ValueError) as exc_info:
vd.validate_metadata(err_md)
exp_err_msg = "Metadata is empty!"
assert str(exc_info.value) == exp_err_msg
with pytest.raises(FileNotFoundError) as exc_info:
vd.validate_metadata("NOT A FILE")
exp_err_msg = "[Errno 2] No such file or directory: 'NOT A FILE'"
assert str(exc_info.value) == exp_err_msg
def test_validate_metadata(data_paths, tmp_path):
with pytest.raises(FileNotFoundError) as exc_info:
vd.validate_tree("NOT A FILE")
exp_err_msg = "[Errno 2] No such file or directory: 'NOT A FILE'"
assert str(exc_info.value) == exp_err_msg
| [
{
"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 | xebec/tests/test_validate.py | gibsramen/xebec |
import torch.nn as nn
import torch.nn.functional as F
class RNNAgent(nn.Module):
def __init__(self, input_shape, args):
super(RNNAgent, self).__init__()
self.args = args
self.fc1 = nn.Linear(input_shape, args.rnn_hidden_dim)
self.rnn = nn.GRUCell(args.rnn_hidden_dim, args.rnn_hidden_dim)
if not args.levin_flag_quantile:
self.fc2 = nn.Linear(args.rnn_hidden_dim, args.n_actions)
else:
self.fc2 = nn.Linear(args.rnn_hidden_dim, args.n_actions * args.N_QUANT)
def init_hidden(self):
# make hidden states on same device as model
# 主要是在 controllers 中使用
return self.fc1.weight.new(1, self.args.rnn_hidden_dim).zero_()
def forward(self, inputs, hidden_state):
mb_size = inputs.size(0)
x = F.relu(self.fc1(inputs))
h_in = hidden_state.reshape(-1, self.args.rnn_hidden_dim)
h = self.rnn(x, h_in)
if not self.args.levin_flag_quantile:
q = self.fc2(h)
else:
q = self.fc2(h).view(mb_size, self.args.n_actions, self.args.N_QUANT)
return q, h
| [
{
"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 | src_convention/modules/agents/rnn_agent.py | halleanwoo/AGMA |
from copy import deepcopy
import factory.random
import pytest
from api.factories import DeliveryLogFactory
from common.tests.mock_data import QURIIRI_SMS_RESPONSE
from django.contrib.auth.models import AnonymousUser
from freezegun import freeze_time
from rest_framework.authtoken.models import Token
from rest_framework.test import APIClient
from users.factories import UserFactory
import quriiri
@pytest.fixture(autouse=True)
def setup_test_environment():
factory.random.reseed_random("777")
with freeze_time("2020-01-04"):
yield
@pytest.fixture
def anonymous_api_client():
return _create_api_client_with_user(AnonymousUser())
@pytest.fixture
def token_api_client():
return _create_api_client_with_user(UserFactory())
@pytest.fixture
def delivery_log():
return DeliveryLogFactory()
@pytest.fixture
def mock_send_sms(monkeypatch):
def mock_send_sms(*args, **kwargs):
return deepcopy(QURIIRI_SMS_RESPONSE)
monkeypatch.setattr(
quriiri.send.Sender, "send_sms", mock_send_sms,
)
def _create_api_client_with_user(user=None):
client = APIClient()
if user and user.is_authenticated:
token, _ = Token.objects.get_or_create(user=user)
client.credentials(HTTP_AUTHORIZATION="Token " + token.key)
return client
| [
{
"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_function_names_snake_case",
"question": "Are all function names in this file written in snake_case?",
"answ... | 3 | common/tests/conftest.py | City-of-Helsinki/notification-service-api |
import ast
from typing_extensions import final
from wemake_python_styleguide.types import AnyFunctionDef
from wemake_python_styleguide.violations.consistency import (
MultilineFunctionAnnotationViolation,
)
from wemake_python_styleguide.visitors.base import BaseNodeVisitor
from wemake_python_styleguide.visitors.decorators import alias
@final
@alias('visit_any_function', (
'visit_FunctionDef',
'visit_AsyncFunctionDef',
))
class WrongAnnotationVisitor(BaseNodeVisitor):
"""Ensures that annotations are used correctly."""
def visit_any_function(self, node: AnyFunctionDef) -> None:
"""
Checks return type annotations.
Raises:
MultilineFunctionAnnotationViolation
"""
self._check_return_annotation(node)
self.generic_visit(node)
def visit_arg(self, node: ast.arg) -> None:
"""
Checks arguments annotations.
Raises:
MultilineFunctionAnnotationViolation
"""
self._check_arg_annotation(node)
self.generic_visit(node)
def _check_return_annotation(self, node: AnyFunctionDef) -> None:
if not node.returns:
return
for sub_node in ast.walk(node.returns):
lineno = getattr(sub_node, 'lineno', None)
if lineno and lineno != node.returns.lineno:
self.add_violation(MultilineFunctionAnnotationViolation(node))
return
def _check_arg_annotation(self, node: ast.arg) -> None:
for sub_node in ast.walk(node):
lineno = getattr(sub_node, 'lineno', None)
if lineno and lineno != node.lineno:
self.add_violation(MultilineFunctionAnnotationViolation(node))
return
| [
{
"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 | wemake_python_styleguide/visitors/ast/annotations.py | KJagiela/wemake-python-styleguide |
from __future__ import annotations
from dataclasses import dataclass
from abc import abstractmethod
import sys
from typing import Dict, Tuple, Iterable, List
from typeguard import typechecked
from Data import DataPipelineOutput
_SURVEYPIPELINE = Dict[str, any] = {}
def register_surveypipeline(name):
"""Decorator used register a survey pipeline
Args:
name: Name of the architecture
"""
def register_class(cls, name):
_SURVEYPIPELINE[name] = cls
setattr(sys.modules[__name__], name, cls)
return cls
if isinstance(name, str):
name = name.lower()
return lambda c: register_class(c, name)
cls = name
name = cls.__name__
register_class(cls, name.lower())
return cls
@dataclass
class BaseSurveyPipelineConfig:
name: str = "BaseSurveyPipelineConfig"
class BaseInferenceOutput:
pass
@dataclass
class BaseSurveyInput:
data_output: Iterable[DataPipelineOutput]
inference_output: Iterable[BaseInferenceOutput]
@dataclass
class BaseSurveyOutput:
HTML: str
@typechecked
class BaseSurveyPipeline:
def __init__(self, config: BaseSurveyPipelineConfig):
self.config = config
@abstractmethod
def create_htmlfile(self, input: BaseSurveyInput) -> BaseSurveyOutput:
raise Exception("Must be overridden in child class")
@abstractmethod
def create_report(self):
# create output from completion of task
return None
def get_surveylines(name: str) -> BaseSurveyPipeline:
"""
:param name:
Name refers to the name of corresponding survey pipeline
:return:
A survey pipeline from the decorator registry
"""
return _SURVEYPIPELINE[name.lower()]
def get_surveypipelines_names() -> List[str]:
"""
Gets the list of surveypipeline names
:return:
A list of survey pipeline names
"""
return _SURVEYPIPELINE.keys()
| [
{
"point_num": 1,
"id": "has_nested_function_def",
"question": "Does this file contain any function defined inside another function?",
"answer": true
},
{
"point_num": 2,
"id": "every_function_under_20_lines",
"question": "Is every function in this file shorter than 20 lines?",
"... | 3 | Surveys/__init__.py | EleutherAI/adaptive-hit |
import argparse
import discretisedfield as df
def convert_files(input_files, output_files):
for input_file, output_file in zip(input_files, output_files):
field = df.Field.fromfile(input_file)
field.write(output_file)
def main():
parser = argparse.ArgumentParser(
prog='ovf2vtk',
description='ovf2vtk - ovf to VTK format conversion'
)
parser.add_argument('--infile', type=argparse.FileType('r'),
help='One or more input files', nargs='+',
required=True)
parser.add_argument('--outfile', type=argparse.FileType('w'), nargs='+',
help='One or more output files, optional')
args = parser.parse_args()
if args.outfile:
if len(args.infile) == len(args.outfile):
input_files = [f.name for f in args.infile]
output_files = [f.name for f in args.outfile]
else:
print('\nError: The number of input and output '
'files does not match.')
return 0
else:
input_files = [f.name for f in args.infile]
output_files = [f'{f.split(".")[0]}.vtk' for f in input_files]
convert_files(input_files, output_files)
if __name__ == "__main__":
main()
| [
{
"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 | discretisedfield/ovf2vtk.py | minrk/discretisedfield |
import cv2
def mean(image):
return cv2.medianBlur(image, 5)
def gaussian(image):
return cv2.GaussianBlur(image, (5, 5), 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_has_docstring",
"question": "Does every function in this file have a docstring?",
"ans... | 3 | viewer/images/edits/blur.py | Lukasz1928/DICOM-viewer |
from math import ceil, sqrt
def my_sqrt(input_num):
return ceil(sqrt(input_num))
def is_divisible(dividend, divisor):
return dividend % divisor == 0
def is_prime(input_num):
return True
| [
{
"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_function_has_docstring",
"question": "Does every function in this file have a docstring?",
"answer":... | 3 | python/tdd/math/prime.py | xanderyzwich/Playground |
#!/usr/bin/env python3
# -*- config: utf-8 -*-
from functools import lru_cache
import timeit
@lru_cache
def fib(n):
if n == 0 or n == 1:
return n
else:
return fib(n - 2) + fib(n - 1)
@lru_cache
def factorial(n):
if n == 0:
return 1
elif n == 1:
return 1
else:
return n * factorial(n - 1)
if __name__ == '__main__':
r_fib = fib(30)
r_factorial = factorial(30)
print(f'Результат работы рекурсивной функции чисел Фибоначчи(30) = {r_fib}.')
print(f'Время выполнения: {timeit.timeit("r_fib", setup="from __main__ import r_fib")} секунд.')
print(f'Результат работы рекурсивной функции факториала(30) = {r_factorial}. ')
print(f'Время выполнения: {timeit.timeit("r_factorial", setup="from __main__ import r_factorial")} секунд.')
| [
{
"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 | zadanie1.2.py | Alba126/Laba11 |
import abc
class PipelineStepBase(metaclass=abc.ABCMeta):
def take_pipeline(self, left, right):
pass
@abc.abstractmethod
def has_left(self) -> bool:
raise NotImplementedError("Abstract method not implemented!")
@abc.abstractmethod
def has_right(self) -> bool:
raise NotImplementedError("Abstract method not implemented!")
@abc.abstractmethod
def pop_left(self):
raise NotImplementedError("Abstract method not implemented!")
@abc.abstractmethod
def pop_right(self):
raise NotImplementedError("Abstract method not implemented!")
class SymmetricPipelineStepBase(metaclass=abc.ABCMeta):
def take_pipeline(self, value):
pass
@abc.abstractmethod
def has_value(self) -> bool:
raise NotImplementedError("Abstract method not implemented!")
@abc.abstractmethod
def pop(self):
raise NotImplementedError("Abstract method not implemented!")
class SymmetryAdapter(PipelineStepBase):
def take_pipeline(self, left, right):
self.left_handler.take_pipeline(left)
self.right_handler.take_pipeline(right)
def has_left(self) -> bool:
return self.left_handler.has_value()
def has_right(self) -> bool:
return self.right_handler.has_value()
def pop_left(self):
return self.left_handler.pop()
def pop_right(self):
return self.right_handler.pop()
def __init__(self, left_handler: SymmetricPipelineStepBase, right_handler: SymmetricPipelineStepBase):
self.left_handler = left_handler
self.right_handler = right_handler
| [
{
"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": "more_functions_than_classes",
"question": "Does this file define more functions than cla... | 3 | pstep_base.py | Team-Audio/synth-processor |
from graphgallery.sequence import FullBatchSequence
from graphgallery import functional as gf
from graphgallery.gallery import PyTorch
from graphgallery.gallery import Trainer
from graphgallery.nn.models import get_model
@PyTorch.register()
class TrimmedGCN(Trainer):
def process_step(self,
adj_transform="normalize_adj",
attr_transform=None,
graph_transform=None):
graph = gf.get(graph_transform)(self.graph)
adj_matrix = gf.get(adj_transform)(graph.adj_matrix)
node_attr = gf.get(attr_transform)(graph.node_attr)
X, A = gf.astensors(node_attr, adj_matrix.tolil().rows, device=self.device)
# ``A`` and ``X`` are cached for later use
self.register_cache(X=X, A=A)
def builder(self,
hids=[64],
acts=['relu'],
dropout=0.5,
weight_decay=5e-5,
lr=0.01,
tperc=0.45,
bias=False):
model = get_model("TrimmedGCN", self.backend)
model = model(self.graph.num_node_attrs,
self.graph.num_node_classes,
hids=hids,
acts=acts,
tperc=tperc,
dropout=dropout,
weight_decay=weight_decay,
lr=lr,
bias=bias)
return model
def train_sequence(self, index):
labels = self.graph.node_label[index]
sequence = FullBatchSequence([self.cache.X, self.cache.A],
labels,
out_weight=index,
device=self.device)
return sequence
| [
{
"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 | graphgallery/gallery/gallery_model/pytorch/experimental/trimmed_gcn.py | Aria461863631/GraphGallery |
from fastkde import fastKDE
import numpy as np
"""
Fast 2D Kernel Density Estimation with simple point evaluation
"""
class KDEEstimation2D(object):
def __init__(self, X):
self.pdf, self.axes = fastKDE.pdf(X[:, 0], X[:, 1])
def evaluate_points(self, X):
m = X.shape[0]
values = np.array(range(0, m), dtype=float)
for i in range(0, m):
values[i] = self.evaluate_pdf_value(X[i, :])
return values
def evaluate_pdf_value(self, s):
x_up = s[0] <= self.axes[0]
index_up_x = self.get_index_upper(x_up, 0)
x_low = s[0] >= self.axes[0]
index_low_x = self.get_index_lower(x_low)
y_up = s[1] <= self.axes[1]
index_up_y = self.get_index_upper(y_up, 1)
y_low = s[1] >= self.axes[1]
index_low_y = self.get_index_lower(y_low)
# TODO
value = 0.0
for i in range(index_low_x, index_up_x + 1):
for j in range(index_low_y, index_up_y + 1):
value += self.pdf.T[i, j]
value /= 4
return value
def get_index_upper(self, values, index):
c = [i for i in range(0, len(values)) if values[i]]
if len(c) == 0:
up = self.pdf.shape[index] - 2
else:
up = np.min(c)
return up
def get_index_lower(self, values):
c = [i for i in range(0, len(values)) if values[i]]
if len(c) == 0:
up = 0
else:
up = np.max(c)
return up | [
{
"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 | build/lib/oddstream/kde_estimation.py | tartaruszen/oddstream |
import unittest
'''This test file is intended to test the database and the gui to a good extent.
This should:
- create random entries with somewhat random timestamps.
- Save entries to a text file for comparison.
- Enter each entry into the database
- search for some of the random terms.
- Remove database after testing
- Collect and show statistics throughout
- Push buttons to see if there is a place where things break down.'''
class GUITester(object):
def __init__(self):
pass
def randp(self): #new project
pass
def archivep(self): #'x' project
pass
def openp(self): #open project
pass
def move(self):
pass
# def test_empty_note(self):
# """ Tests that empty notes or ones with only space
# charachters don't get put into the database.
# Uses Projects, dates and times to enable checking.
# """
# pass
class TimeTester(object):
def __init__(self):
pass
def start(self):
pass
def stop(self):
pass
def replace(self):
pass
help()
| [
{
"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 | test/test.py | Ghalko/noteTaker |
from flask import Flask, render_template, redirect
import pymongo
from flask_pymongo import PyMongo
import scrape_mars
app = Flask(__name__)
# Setup mongo connection
mongo = PyMongo(app, uri="mongodb://localhost:27017/mars_db")
@app.route("/")
def index():
# Find one record of data from the mongo database
mars_info = mongo.db.mars_list.find_one()
# Return template and data
return render_template("index.html", mars=mars_info)
@app.route("/scrape")
def scrape():
mars_import = scrape_mars.scrape()
# Update the Mongo database using update and upsert=True
mongo.db.mars_list.update({}, mars_import, upsert=True)
return redirect("/", code=302)
if __name__ == "__main__":
app.run(debug=True)
| [
{
"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 | Instructions/Missions_to_Mars/app.py | nguyenkevn/web-scraping-challenge |
#!/usr/bin/env
# -*- coding: utf-8 -*-
# Copyright (C) Victor M. Mendiola Lau - All Rights Reserved
# Unauthorized copying of this file, via any medium is strictly prohibited
# Proprietary and confidential
# Written by Victor M. Mendiola Lau <ryuzakyl@gmail.com>, February 2017
import pylab
from datasets.nir_sugarcane import load_nir_sugarcane
# ---------------------------------------------------------------
def plot_nir_sugarcane_data_set():
# loading the nir sugarcane data set
ds = load_nir_sugarcane()
# removing columns associated with classes and properties
ds = ds.iloc[:, :-5]
# plotting the data set
ds.T.plot(legend=None)
pylab.show()
def plot_nir_sugarcane_juice_process():
# loading the nir sugarcane data set
ds = load_nir_sugarcane()
# getting samples of juice process
ds_juice = ds.loc[ds['Process step'] == 'juice']
# removing columns associated with classes and properties
ds_juice = ds_juice.iloc[:, :-5]
# plotting the data set
ds_juice.T.plot(legend=None)
pylab.show()
| [
{
"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 | datasets/nir_sugarcane/demos.py | ryuzakyl/data-bloodhound |
import json
from .oauth import OAuth2Test
class AmazonOAuth2Test(OAuth2Test):
backend_path = 'social_core.backends.amazon.AmazonOAuth2'
user_data_url = 'https://api.amazon.com/user/profile'
expected_username = 'FooBar'
access_token_body = json.dumps({
'access_token': 'foobar',
'token_type': 'bearer'
})
user_data_body = json.dumps({
'user_id': 'amzn1.account.ABCDE1234',
'email': 'foo@bar.com',
'name': 'Foo Bar'
})
def test_login(self):
self.do_login()
def test_partial_pipeline(self):
self.do_partial_pipeline()
class AmazonOAuth2BrokenServerResponseTest(OAuth2Test):
backend_path = 'social_core.backends.amazon.AmazonOAuth2'
user_data_url = 'https://www.amazon.com/ap/user/profile'
expected_username = 'FooBar'
access_token_body = json.dumps({
'access_token': 'foobar',
'token_type': 'bearer'
})
user_data_body = json.dumps({
'Request-Id': '02GGTU7CWMNFTV3KH3J6',
'Profile': {
'Name': 'Foo Bar',
'CustomerId': 'amzn1.account.ABCDE1234',
'PrimaryEmail': 'foo@bar.com'
}
})
def test_login(self):
self.do_login()
def test_partial_pipeline(self):
self.do_partial_pipeline()
| [
{
"point_num": 1,
"id": "every_class_has_docstring",
"question": "Does every class 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": true... | 3 | social_core/tests/backends/test_amazon.py | rameshananth/social-core |
import multiprocessing
import pandas as pd
def lofo_to_df(lofo_scores, feature_list):
importance_df = pd.DataFrame()
importance_df["feature"] = feature_list
importance_df["importance_mean"] = lofo_scores.mean(axis=1)
importance_df["importance_std"] = lofo_scores.std(axis=1)
for val_score in range(lofo_scores.shape[1]):
importance_df["val_imp_{}".format(val_score)] = lofo_scores[:, val_score]
return importance_df.sort_values("importance_mean", ascending=False)
def parallel_apply(cv_func, feature_list, n_jobs):
pool = multiprocessing.Pool(n_jobs)
manager = multiprocessing.Manager()
result_queue = manager.Queue()
for f in feature_list:
pool.apply_async(cv_func, (f, result_queue))
pool.close()
pool.join()
lofo_cv_result = [result_queue.get() for _ in range(len(feature_list))]
return lofo_cv_result
def flatten_list(nested_list):
return [item for sublist in nested_list for item in sublist]
| [
{
"point_num": 1,
"id": "every_function_has_docstring",
"question": "Does every function in this file have a docstring?",
"answer": false
},
{
"point_num": 2,
"id": "no_function_exceeds_5_params",
"question": "Does every function in this file take 5 or fewer parameters (excluding sel... | 3 | lofo/utils.py | aerdem4/lofo-importance |
# Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import gym
import numpy as np
import unittest
from parl.env.continuous_wrappers import ActionMappingWrapper
class MockEnv(gym.Env):
def __init__(self, low, high):
self.action_space = gym.spaces.Box(low=low, high=high, shape=(3, ))
self._max_episode_steps = 1000
def step(self, action):
self.action = action
def reset(self):
return None
class TestActionMappingWrapper(unittest.TestCase):
def test_action_mapping(self):
origin_act = np.array([-1.0, 0.0, 1.0])
env = MockEnv(0.0, 1.0)
wrapper_env = ActionMappingWrapper(env)
wrapper_env.step(origin_act)
self.assertListEqual(list(env.action), [0.0, 0.5, 1.0])
env = MockEnv(-2.0, 2.0)
wrapper_env = ActionMappingWrapper(env)
wrapper_env.step(origin_act)
self.assertListEqual(list(env.action), [-2.0, 0.0, 2.0])
env = MockEnv(-5.0, 10.0)
wrapper_env = ActionMappingWrapper(env)
wrapper_env.step(origin_act)
self.assertListEqual(list(env.action), [-5.0, 2.5, 10.0])
if __name__ == '__main__':
unittest.main()
| [
{
"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 | parl/env/tests/continuous_wrappers_test.py | lp2333/PARL |
import vtk
class BacklightHandleWidget(vtk.vtkHandleWidget):
def __init__(self, color, handle_size):
self.CreateDefaultRepresentation()
self.GetHandleRepresentation().GetProperty().SetColor(color)
self.GetHandleRepresentation().SetHandleSize(handle_size)
self._initialize_point_widget_backlight(color, handle_size)
self.AddObserver("InteractionEvent", self._widget_get_offset)
def connect_with_renderer(self, renderer):
self._renderer = renderer
def set_position(self, position):
self.GetHandleRepresentation().SetWorldPosition(position)
self._widget_backlight_source.SetCenter(position)
def get_position(self):
return self.GetHandleRepresentation().GetWorldPosition()
def _initialize_point_widget_backlight(self, color, handle_size):
self._widget_backlight_source = vtk.vtkSphereSource()
self._widget_backlight_source.SetRadius(handle_size)
self._widget_backlight_mapper = vtk.vtkDataSetMapper()
self._widget_backlight_actor = vtk.vtkActor()
self._widget_backlight_mapper.SetInputConnection(self._widget_backlight_source.GetOutputPort())
self._widget_backlight_actor.SetMapper(self._widget_backlight_mapper)
self._widget_backlight_actor.GetProperty().SetColor(color)
self._widget_backlight_actor.GetProperty().SetOpacity(0.5)
def _widget_get_offset(self, obj, event):
position = self.GetHandleRepresentation().GetWorldPosition()
self._widget_backlight_source.SetCenter(position)
self.GetInteractor().Initialize()
def On(self):
vtk.vtkHandleWidget.On(self)
self._renderer.AddActor(self._widget_backlight_actor)
self.GetInteractor().Initialize()
def Off(self):
vtk.vtkHandleWidget.Off(self)
self._renderer.RemoveActor(self._widget_backlight_actor)
self.GetInteractor().Initialize()
| [
{
"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 | SplineMeasurement/engine/vtk_widgets/backlight_handle_widget.py | TiNezlobinsky/SplineLV |
import datetime
def parse_ymd(date):
'''
Convert string to `datetime.datetime` object.
Args:
date: string contains year, month, day, split by `-`
Returns:
`datetime.datetime` object
'''
return datetime.datetime(*map(int, date.split('-')))
def next_date(date):
'''Get next date from string'''
return parse_ymd(date) + datetime.timedelta(days=1)
def day_interval(x, y):
'''Get day interval between two strings represent datetime'''
return abs((parse_ymd(x) - parse_ymd(y)).days)
if __name__ == "__main__":
print(day_interval('2018-01-22', '2018-01-24'))
| [
{
"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 | novel/analysis/utils.py | rrcgat/novel-info |
import discord
from discord.ext import commands
from clever_chat import AsyncClient
client = commands.Bot(command_prefix='amogus')
@client.event
async def on_message(message):
if message.author == client.user:
return
if message.channel.id == 854342237461676073:
response = await AsyncClient.get_response(message.content, message.author.id, "Male", "Oxy")
await message.channel.send(response)
@client.event
async def on_ready():
print(f'{client.user.name} is ready!')
client.run(TOKEN) | [
{
"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 | Cleverchat-api/async-tests/discord-implementation.py | DevInfinix/Clever-chat |
# Protean
from protean.core.field.basic import String
from protean.utils.container import BaseContainer
class CustomBaseContainer(BaseContainer):
def __new__(cls, *args, **kwargs):
if cls is CustomBaseContainer:
raise TypeError("CustomBaseContainer cannot be instantiated")
return super().__new__(cls)
class CustomContainer(CustomBaseContainer):
foo = String(max_length=50, required=True)
bar = String(max_length=50, required=True)
| [
{
"point_num": 1,
"id": "more_functions_than_classes",
"question": "Does this file define more functions than classes?",
"answer": false
},
{
"point_num": 2,
"id": "every_class_has_docstring",
"question": "Does every class in this file have a docstring?",
"answer": false
},
{... | 3 | tests/container/elements.py | nadirhamid/protean |
from portfolios.factories.skill_factory import create_skills_with_factory
from django.db import transaction
from django.core.management.base import BaseCommand
class Command(BaseCommand):
help = "Generates dummy data"
def _generate_dummy_data(self):
# Create dummy data
create_skills_with_factory(
num_of_data=7,
delete_old_data=False
)
@transaction.atomic
def handle(self, *args, **kwargs):
# generate data
self._generate_dummy_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": "more_functions_than_classes",
"question": "Does this file define more functions than classes?",
"answer": true
}... | 3 | backend/utils/management/commands/generate_dummy_skills.py | NumanIbnMazid/numanibnmazid.com |
import educative.course1.stacks_queues.stack as s
input_data = [23, 60, 12, 42, 4, 97, 2]
expected_output_data = [2, 4, 12, 23, 42, 60, 97]
# This solution uses a second stack
# 1. until input stack is not empty, we pop the top value and compare it
# with the top value of the second stack
# 2. if value > top of stack 2, we insert the popped value in stack 2
# 3. else while popped value < top of stack 2, we keep pushing top of stack 2 to stack 1
# 4. finally when stack 2 is empty we push the popped value and start over again
# 5. The output will be a sorted stack
# ---------------------------------------------
# NOTE - This can also be done by recursion ---
# ---------------------------------------------
def sort_stack_1(stack):
result = s.Stack(stack.capacity, True) # suppress_printing = True
while not stack.is_empty():
value = stack.pop()
if not result.is_empty() and value >= int(result.peek()):
result.push(value)
else:
while not result.is_empty() and value < int(result.peek()):
stack.push(result.pop())
result.push(value)
return result.prettify()
def main():
input_stack = s.Stack(len(input_data), True) # suppress_printing = True
[input_stack.push(x) for x in input_data]
expected_output_stack = s.Stack(len(expected_output_data), True) # suppress_printing = True
[expected_output_stack.push(x) for x in expected_output_data]
print("Input: \n" + str(input_stack.prettify()))
print("Expected: \n" + str(expected_output_stack.prettify()))
print("Output: \n" + str(sort_stack_1(input_stack)))
if __name__ == '__main__':
main()
| [
{
"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 | educative/course1/stacks_queues/ch5_sort_stack_1.py | liveroot/ambition2020 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from abc import ABCMeta, abstractmethod, abstractproperty
import logging
# https://stackoverflow.com/questions/13646245/is-it-possible-to-make-abstract-classes-in-python
class BaseFilter:
__metaclass__ = ABCMeta
def __init__(self, filterConfig):
self.filterConfig = filterConfig
self.filterType = filterConfig['type']
# data Type is require e.g. Pokemon, Quest, Raid ...
if ('dataType' in self.filterConfig):
self.dataType = self.filterConfig['dataType']
else:
raise ValueError("Missing Field: 'DataType' in Filter. Please check your channels.json. Error raised in Filter with type:", self.filterType )
# name is required
if ('name' in self.filterConfig):
self.name = self.filterConfig['name']
else:
raise ValueError("Missing Field: 'name' in Filter. Please check your channels.json. Error raised in Filter with type:", self.filterType )
# get logger instance
logging.basicConfig( format = '%(asctime)s %(levelname)-10s %(threadName)s %(name)s -- %(message)s',level=logging.INFO)
self.logger = logging.getLogger(__name__)
# custom filter check
self.testConfig()
super(BaseFilter, self).__init__()
'''
Override this method with your own test logic e.g. whitelist
if(pokemon.pokemonId in whitelist):
return True
else:
return False
@return param bool
'''
@abstractmethod
def isSatisfied(self, pokemon):
pass
'''
Filter test method, please override this method with your tests if all fields that are required are set,
if something is missing you must rais a ValueError.
e.g. a whitelist filter need a white list with at least one Pokemon id in it. If this field is not set
raise an ValueError.
'''
@abstractmethod
def testConfig(self):
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": fal... | 3 | filters/baseFilter.py | tharnatoz/PokeKaio |
class Restaurant():
"""A simple Restaurant class."""
def __init__(self, name, cuisine_type):
"""Initialize restaurant name and cuisine type attributes."""
self.restaurant_name = name
self.cuisine_type = cuisine_type
def describe_restaurant(self):
"""Print restaurant description."""
print(self.restaurant_name.title() + ' is a ' + self.cuisine_type +
' restaurant.')
def open_restaurant(self):
"""Simulate open restaurant."""
print(self.restaurant_name.title() + ' is open.')
class IceCreamStand(Restaurant):
"""A specialize restaurant that make ice cream."""
def __init__(self, name, cuisine_type, *flavors):
"""Initialize ice cream restaurant with flavors."""
super().__init__(name, cuisine_type)
self.flavors = [x for x in flavors]
def display_flavors(self):
"""Print ice cream flavors."""
self.describe_restaurant()
print('It has the following flavors:')
for flavor in self.flavors:
print(' - ' + flavor)
restaurant = IceCreamStand('Ice Goods', 'ice cream', 'chocolate', 'vanilla', 'mint')
restaurant.display_flavors()
| [
{
"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_class_has_docstring",
"question": "Does every class in this file have a docstring?"... | 3 | crash_course/ch09/exec/ice_cream_stand.py | dantin/python-by-example |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from lyrics.config import Config
from lyrics.player import Player
from lyrics.window import Window
import sys
import curses
def ErrorHandler(func):
def wrapper(*args, **kwargs):
try:
curses.wrapper(func)
except KeyboardInterrupt:
pass
except curses.error as err:
print('Please increase terminal window size!')
except:
print('Unexpected exception occurred.', sys.exc_info()[0])
return wrapper
@ErrorHandler
def start(stdscr):
defaults = Config('OPTIONS')
if len(sys.argv) >= 2:
player_name = sys.argv[1].strip()
autoswitch = False
else:
player_name = defaults['player'].strip()
autoswitch = defaults.getboolean('autoswitch')
align = defaults['alignment']
if align == 'center':
align = 0
elif align == 'right':
align = 2
else:
align = 1
interval = defaults['interval']
source = defaults['source']
player = Player(player_name, source, autoswitch, align=align)
win = Window(stdscr, player, timeout=interval)
win.main()
if __name__ == '__main__':
if len(sys.argv) >= 2:
if sys.argv[1] == '-t':
try:
artist = sys.argv[2].strip()
title = sys.argv[3].strip()
except IndexError:
print('Please provide track info in format "-t {artist} {title}".')
exit(1)
from lyrics.track import Track
track = Track(artist=artist, title=title)
track.get_lyrics('google')
print(track.track_name)
print('-' * track.width, '\n')
print(track.get_text())
exit(0)
else:
start()
| [
{
"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": "has_nested_function_def",
"question": "Does this file contain any function defined inside another function?",
... | 3 | lyrics/lyrics_in_terminal.py | nisiddharth/lyrics-in-terminal |
from enum import Enum
from typing import Optional, Dict, Any
from pydantic import BaseModel
class Granularity(str, Enum):
"""
Time Series Granuality
"""
seconds = "seconds"
minutes = "minutes"
hours = "hours"
class TimeSeriesConfig(BaseModel):
"""
Time Series Collection config
"""
time_field: str
meta_field: Optional[str]
granularity: Optional[Granularity]
expire_after_seconds: Optional[float]
def build_query(self, collection_name: str) -> Dict[str, Any]:
res: Dict[str, Any] = {"name": collection_name}
timeseries = {"timeField": self.time_field}
if self.meta_field is not None:
timeseries["metaField"] = self.meta_field
if self.granularity is not None:
timeseries["granularity"] = self.granularity
res["timeseries"] = timeseries
if self.expire_after_seconds is not None:
res["expireAfterSeconds"] = self.expire_after_seconds
return res
| [
{
"point_num": 1,
"id": "every_class_has_docstring",
"question": "Does every class in this file have a docstring?",
"answer": true
},
{
"point_num": 2,
"id": "more_functions_than_classes",
"question": "Does this file define more functions than classes?",
"answer": false
},
{
... | 3 | beanie/odm/settings/timeseries.py | paul-finary/beanie |
"""
Given a sorted array (sorted in non-decreasing order) of positive numbers, find the smallest positive integer value that cannot be represented as sum of elements of any subset of given set.
Expected time complexity is O(n).
Examples:
Input: arr[] = {1, 3, 6, 10, 11, 15};
Output: 2
Input: arr[] = {1, 1, 1, 1};
Output: 5
Input: arr[] = {1, 1, 3, 4};
Output: 10
Input: arr[] = {1, 2, 5, 10, 20, 40};
Output: 4
Input: arr[] = {1, 2, 3, 4, 5, 6};
Output: 22
SOLUTION:
We can solve this problem in O(n) time using a simple loop.
Let the input array be arr[0..n-1].
We initialize the result as 1 (smallest possible outcome) and traverse the given array.
Let the smallest element that cannot be represented by elements at indexes from 0 to (i-1) be ‘res’, there are following two possibilities when we consider element at index i:
1) We decide that ‘res’ is the final result: If arr[i] is greater than ‘res’, then we found the gap which is ‘res’ because the elements after arr[i] are also going to be greater than ‘res’.
2) The value of ‘res’ is incremented after considering arr[i]: The value of ‘res’ is incremented by arr[i] (why? If elements from 0 to (i-1) can represent 1 to ‘res-1’, then elements from 0 to i can represent from 1 to ‘res + arr[i] – 1’ be adding ‘arr[i]’ to all subsets that represent 1 to ‘res’)
"""
def smallest_not_subset_sum(arr):
if arr[0] > 1:
return 1
# The largest number that can be generated so far.
largest_possible = 1
for i in range(1, len(arr)):
elem = arr[i]
if elem > largest_possible + 1:
break
largest_possible += elem
return largest_possible + 1
def main():
arr = [5]
ans = smallest_not_subset_sum(arr)
print(ans)
main()
| [
{
"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 | notes/algo-ds-practice/problems/array/smallest_not_subset_sum.py | Anmol-Singh-Jaggi/interview-notes |
import torch
import torch.nn as nn
import torchvision
class NonLocalBlock(nn.Module):
def __init__(self, channel):
super(NonLocalBlock, self).__init__()
self.inter_channel = channel // 2
self.conv_phi = nn.Conv2d(in_channels=channel, out_channels=self.inter_channel, kernel_size=1, stride=1,padding=0, bias=False)
self.conv_theta = nn.Conv2d(in_channels=channel, out_channels=self.inter_channel, kernel_size=1, stride=1, padding=0, bias=False)
self.conv_g = nn.Conv2d(in_channels=channel, out_channels=self.inter_channel, kernel_size=1, stride=1, padding=0, bias=False)
self.softmax = nn.Softmax(dim=1)
self.conv_mask = nn.Conv2d(in_channels=self.inter_channel, out_channels=channel, kernel_size=1, stride=1, padding=0, bias=False)
def forward(self, x):
# [N, C, H , W]
b, c, h, w = x.size()
# [N, C/2, H * W]
x_phi = self.conv_phi(x).view(b, c, -1)
# [N, H * W, C/2]
x_theta = self.conv_theta(x).view(b, c, -1).permute(0, 2, 1).contiguous()
x_g = self.conv_g(x).view(b, c, -1).permute(0, 2, 1).contiguous()
# [N, H * W, H * W]
mul_theta_phi = torch.matmul(x_theta, x_phi)
mul_theta_phi = self.softmax(mul_theta_phi)
# [N, H * W, C/2]
mul_theta_phi_g = torch.matmul(mul_theta_phi, x_g)
# [N, C/2, H, W]
mul_theta_phi_g = mul_theta_phi_g.permute(0,2,1).contiguous().view(b,self.inter_channel, h, w)
# [N, C, H , W]
mask = self.conv_mask(mul_theta_phi_g)
out = mask + x
return out
if __name__=='__main__':
model = NonLocalBlock(channel=16)
print(model)
input = torch.randn(1, 16, 64, 64)
out = model(input)
print(out.shape) | [
{
"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 | models/Attention/NonLocalBlock.py | Dou-Yu-xuan/deep-learning-visal |
#!/usr/bin/env python3
"""
Possible string formats:
<author(s)> <title> <source> <year>
"""
import re
import pdf
CRED = '\033[91m'
CGREEN = '\33[32m'
CYELLOW = '\33[33m'
CBLUE = '\33[34m'
CVIOLET = '\33[35m'
CBEIGE = '\33[36m'
CWHITE = '\33[37m'
CEND = '\033[0m'
def extract_references_list_by_keyword(text, keyword):
print(text)
match_res = re.search(keyword, text)
ref_text = text[match_res.span()[0]:]
# print(ref_text)
# WARNING: not more than 999 references!
index_re = re.compile('\[[0-9]([0-9]|)([0-9]|)\]')
ref_pos = []
for ref in index_re.finditer(ref_text):
ref_pos.append(ref.span()[0])
ref_pos.append(len(ref_text))
for i in range(len(ref_pos)-1):
print(CYELLOW + ref_text[ref_pos[i]:ref_pos[i+1]] + CEND)
def extract_references_list(text):
res = []
buffer = ""
state = 0
for i in reversed(range(0, len(text)-1)):
c = text[i]
buffer = c + buffer
if state == 0:
if c == ']':
state = 1
elif state == 1:
if c in ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']:
state = 2
else:
state = 0
elif state == 2:
if c == '[':
res.append(buffer)
if buffer[1] == '1' and buffer[2] == ']':
break
state = 0
buffer = ""
else:
print("Unknown state")
raise
return reversed(res)
def extract_article_from_reference(string):
pass
# return (autors, title, date)
if __name__ == '__main__':
import sys
text = pdf.extract_text(sys.argv[1])
print(text)
# zextract_references_list_by_keyword('REFERENCES')
ref_list = extract_references_list(text)
for ref in ref_list:
print(CYELLOW + ref + CEND)
| [
{
"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 | parse_reference.py | Dewdis/scholar_tree |
import logging
import functools
log = logging.getLogger('decorators')
log.setLevel(logging.INFO)
decorated = set()
def deflog(f):
log.debug('decorating function: %s', f.__name__)
decorated.add(f.__name__)
@functools.wraps(f)
def wrapped(*args, **kwargs):
log.debug('calling function: %s', f.__name__)
ret = f(*args, **kwargs)
return ret
return wrapped
class DecTest:
@deflog
def hi(self):
log.debug('hi')
| [
{
"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 | python/tests/decorators.py | levinsamuel/rand |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import os, re, xml.dom.minidom
#errorXMLInfo = [['zh_TW', '3', 's0101m.mul1.xml'],
# ['zh_TW', '3', 's0102m.mul2.xml'],
# ['zh_TW', '5', 's0102m.mul6.xml'],
# ['zh_TW', '3', 's0102m.mul8.xml'],
# ['zh_TW', '3', 's0103m.mul7.xml'],
# ['zh_TW', '3', 's0402m2.mul6.xml']]
errorXMLInfo = []
def replacement(match):
pElmString = match.group()
dom = xml.dom.minidom.parseString(pElmString.encode('utf-8'))
pElm = dom.documentElement
#print(pElm.toxml())
return pElm.toxml()
def subXML(f):
content = f.read().decode('UTF-16BE')
re.sub(r'<p\srend=.+>.+</p>', replacement, content)
return content
def convertXMLEncoding(path):
print('processing ' + path + ' ...')
with open(path, 'r') as f:
content = subXML(f)
with open(os.path.basename(path), 'w') as f:
f.write(content.encode('utf-8'))
def convertXMLEncoding2(path):
print('processing ' + path + ' ...')
os.system('iconv -f UTF-16BE -t UTF-8 %s' % path)
with open(path, 'r') as f:
newFileContent = re.sub(r'encoding="UTF-16"', r'encoding="UTF-8"', f.read())
with open(path, 'w') as f:
f.write(newFileContent)
if __name__ == '__main__':
for xmlInfo in errorXMLInfo:
path = os.path.join( os.path.join(os.path.dirname(__file__), '../translation'), '%s/%s/%s' % (xmlInfo[0], xmlInfo[1], xmlInfo[2]))
if not os.path.isfile(path):
print('not file: %s' % path)
exit(1)
#convertXMLEncoding(path)
convertXMLEncoding2(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": "every_function_under_20_lines",
"question": "Is every function in this file shorter than ... | 3 | docs/obsoleted/pytools/fixFirefoxXMLParsingError.py | sup6/pali |
import ecc
import random
import itertools
def concat(chunks):
return bytearray(itertools.chain.from_iterable(chunks))
def test_random():
r = random.Random(0)
x = bytearray(r.randrange(0, 256) for i in range(16 * 1024))
y = ecc.encode(x)
x_ = concat(ecc.decode(y))
assert x_[:len(x)] == x
assert all(v == 0 for v in x_[len(x):])
def test_file():
data = open('data.send').read()
enc = ecc.encode(data)
assert concat(ecc.decode(enc)) == data
| [
{
"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 | test_ecc.py | RagnarDanneskjold/amodem |
import pkg_resources
try:
import click
except ImportError:
raise Exception('Missing CLI dependencies. To use WASH from CLI, please run following command:/n'
'pip install wash-lang-prototype[cli]')
@click.group()
@click.option('--debug', default=False, is_flag=True, help="Debug/trace output.")
@click.pass_context
def wash_lang_prototype(context, debug):
context.obj = {'debug': debug}
def register_wash_lang_prototype_subcommands():
"""
Find and use all WASH sub-commands registered through the extension point.
Entry point used for command registration is `wash_commands`.
In this entry point you should register a callable that accepts the top level
click `wash_lang_prototype` command and register additional command(s) on it.
"""
global wash_lang_prototype
for subcommand in pkg_resources.iter_entry_points(group='wash_commands'):
subcommand.load()(wash_lang_prototype)
# Register sub-commands specified through extension points.
register_wash_lang_prototype_subcommands()
| [
{
"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 | wash_lang_prototype/cli/__init__.py | Tim6FTN/JSD |
from src.actions.action import Action
from src.mapfeatures.intersection import Intersection
from src.playerprofile import PlayerProfile
from typing import Dict
class BuildRoad(Action):
def __init__(self, destination_id: int):
self.destination_id = destination_id
def __repr__(self):
return f'buildroad {self.destination_id}'
def apply_action(self, player_profile: PlayerProfile, intersections: Dict[int, Intersection]):
player_profile.resources['WOOD'] -= 100
player_profile.resources['CLAY'] -= 100
player_profile.add_road(self.destination_id)
| [
{
"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 | src/actions/buildroad.py | MarinVlaic/AIBG |
from __future__ import print_function
from .generalized import Scraper
class DuckDuckGo(Scraper):
"""Scrapper class for DuckDuckGo"""
def __init__(self):
Scraper.__init__(self)
self.url = 'https://duckduckgo.com/html'
self.defaultStart = 0
self.startKey = 's'
self.name = 'duckduckgo'
@staticmethod
def parse_response(soup):
""" Parse the response and return set of urls
Returns: urls (list)
[[Tile1,url1], [Title2, url2],..]
"""
urls = []
for links in soup.findAll('a', {'class': 'result__a'}):
urls.append({'title': links.getText(),
'link': links.get('href')})
print('DuckDuckGo parsed: ' + str(urls))
return urls
| [
{
"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 | app/scrapers/duckduckgo.py | souravbadami/query-server |
import unittest
from plugins.lyrics import lyrics
# TODO: add tests for PyLyricsClone
class Lyrics_Test(unittest.TestCase):
def setUp(self):
self.song_name = "everybody dies"
self.artist_name = "ayreon"
self.complete_info = "everybody dies-ayreon"
self.wrong_info = "everybody dies-arebon"
self.module = lyrics()
def test_lyrics_found_given_full_parameters(self):
self.assertIsNotNone(self.module.find(self.complete_info))
def test_lyrics_not_found_given_incomplete_parameter(self):
self.assertEqual(self.module.find(self.song_name),
"you forgot to add either song name or artist name")
def test_lyrics_not_found_given_wrong_parameter(self):
self.assertEqual(self.module.find(
self.wrong_info), "Song or Singer does not exist or the API does not have lyrics")
def test_split_works(self):
self.assertEqual(self.module.parse(self.complete_info), [
"everybody dies", "ayreon"])
| [
{
"point_num": 1,
"id": "has_multiple_inheritance",
"question": "Does any class in this file use multiple inheritance?",
"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 | jarviscli/tests/test_auto/test_lyrics.py | InEdited/Jarvis |
from direct.distributed.ClockDelta import *
from direct.showbase import DirectObject
from direct.directnotify import DirectNotifyGlobal
from direct.task import Task
import random
from . import TreasurePlannerAI
class RegenTreasurePlannerAI(TreasurePlannerAI.TreasurePlannerAI):
notify = DirectNotifyGlobal.directNotify.newCategory('RegenTreasurePlannerAI')
def __init__(self, zoneId, treasureConstructor, taskName, spawnInterval, maxTreasures, callback = None):
TreasurePlannerAI.TreasurePlannerAI.__init__(self, zoneId, treasureConstructor, callback)
self.taskName = '%s-%s' % (taskName, zoneId)
self.spawnInterval = spawnInterval
self.maxTreasures = maxTreasures
def start(self):
self.preSpawnTreasures()
self.startSpawning()
def stop(self):
self.stopSpawning()
def stopSpawning(self):
taskMgr.remove(self.taskName)
def startSpawning(self):
self.stopSpawning()
taskMgr.doMethodLater(self.spawnInterval, self.upkeepTreasurePopulation, self.taskName)
def upkeepTreasurePopulation(self, task):
if self.numTreasures() < self.maxTreasures:
self.placeRandomTreasure()
taskMgr.doMethodLater(self.spawnInterval, self.upkeepTreasurePopulation, self.taskName)
return Task.done
def placeRandomTreasure(self):
self.notify.debug('Placing a Treasure...')
spawnPointIndex = self.nthEmptyIndex(random.randrange(self.countEmptySpawnPoints()))
self.placeTreasure(spawnPointIndex)
def preSpawnTreasures(self):
for i in range(self.maxTreasures):
self.placeRandomTreasure()
| [
{
"point_num": 1,
"id": "more_functions_than_classes",
"question": "Does this file define more functions than classes?",
"answer": true
},
{
"point_num": 2,
"id": "no_function_exceeds_5_params",
"question": "Does every function in this file take 5 or fewer parameters (excluding self/... | 3 | toontown/safezone/RegenTreasurePlannerAI.py | TheFamiliarScoot/open-toontown |
import time
import torch
from torchtext.experimental.datasets import AG_NEWS
from torchtext.experimental.vectors import FastText as FastTextExperimental
from torchtext.vocab import FastText
def benchmark_experimental_vectors():
def _run_benchmark_lookup(tokens, vector):
t0 = time.monotonic()
for token in tokens:
vector[token]
print("Lookup time:", time.monotonic() - t0)
train, = AG_NEWS(data_select='train')
vocab = train.get_vocab()
tokens = []
for (label, text) in train:
for id in text.tolist():
tokens.append(vocab.itos[id])
# existing FastText construction
print("Existing FastText - Not Jit Mode")
t0 = time.monotonic()
fast_text = FastText()
print("Construction time:", time.monotonic() - t0)
_run_benchmark_lookup(tokens, fast_text)
# experimental FastText construction
print("FastText Experimental")
t0 = time.monotonic()
fast_text_experimental = FastTextExperimental(validate_file=False)
print("Construction time:", time.monotonic() - t0)
# not jit lookup
print("FastText Experimental - Not Jit Mode")
_run_benchmark_lookup(tokens, fast_text_experimental)
# jit lookup
print("FastText Experimental - Jit Mode")
jit_fast_text_experimental = torch.jit.script(fast_text_experimental)
_run_benchmark_lookup(tokens, jit_fast_text_experimental)
if __name__ == "__main__":
benchmark_experimental_vectors()
| [
{
"point_num": 1,
"id": "has_nested_function_def",
"question": "Does this file contain any function defined inside another function?",
"answer": true
},
{
"point_num": 2,
"id": "every_function_under_20_lines",
"question": "Is every function in this file shorter than 20 lines?",
"... | 3 | benchmark/experimental_vectors.py | guyang3532/text |
""" This is a test file used for testing the pytest plugin. """
def test_function_passed(snapshot):
""" The snapshot for this function is expected to exist. """
snapshot.assert_match(3 + 4j)
def test_function_new(snapshot):
""" The snapshot for this function is expected to exist, but only one assertion is expected. """
snapshot.assert_match(3 + 4j)
snapshot.assert_match(3 + 4j)
| [
{
"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 | tests/test_plugins/pytester_example_dir/test_file_1.py | MORSECorp/snappiershot |
import uuid
from django.contrib.auth import get_user_model
from django.db import models
# Create your models here.
from django.urls import reverse
class Book(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
title = models.CharField(max_length=250)
author = models.CharField(max_length=250)
price = models.DecimalField(max_digits=6, decimal_places=2)
cover = models.ImageField(upload_to='covers/', blank=True)
class Meta:
indexes = [
models.Index(fields=['id'], name='id_index'),
]
permissions = [
('special_status', 'Can read all books'),
]
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('book_detail', args=[str(self.id)])
class Review(models.Model):
book = models.ForeignKey(Book, on_delete=models.CASCADE, related_name='reviews', )
review = models.CharField(max_length=250)
author = models.ForeignKey(get_user_model(), on_delete=models.CASCADE)
def __str__(self):
return self.review
| [
{
"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 | books/models.py | Toluwalemi/django-bookstore-app |
def getDB(log, config):
'''Factory method for getting specific DB implementation'''
supported_dbms = {}
try:
from .aCTDBSqlite import aCTDBSqlite
supported_dbms['sqlite'] = aCTDBSqlite
except:
pass
try:
from .aCTDBMySQL import aCTDBMySQL
supported_dbms['mysql'] = aCTDBMySQL
except:
pass
try:
from .aCTDBOracle import aCTDBOracle
supported_dbms['oracle'] = aCTDBOracle
except:
pass
dbtype = config.get(('db', 'type')).lower()
if dbtype not in supported_dbms:
raise Exception("DB type %s is not implemented." % dbtype)
return supported_dbms[dbtype](log, config)
class aCTDBMS(object):
'''
Class for generic DB Mgmt System db operations. Specific subclasses
implement methods for their own database implementation.
'''
def __init__(self, log, config):
self.log = log
self.socket = str(config.get(('db', 'socket')))
self.dbname = str(config.get(('db', 'name')))
self.user = str(config.get(('db', 'user')))
self.passwd = str(config.get(('db', 'password')))
self.host = str(config.get(('db', 'host')))
self.port = str(config.get(('db', 'port')))
# Each subclass must implement the 6 methods below
def getCursor(self):
raise Exception("Method not implemented")
def timeStampLessThan(self,column,timediff):
raise Exception("Method not implemented")
def timeStampGreaterThan(self,column,timediff):
raise Exception("Method not implemented")
def addLock(self):
raise Exception("Method not implemented")
def getMutexLock(self, lock_name, timeout=2):
raise Exception("Method not implemented")
def releaseMutexLock(self, lock_name):
raise Exception("Method not implemented")
| [
{
"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 | src/act/db/aCTDBMS.py | bryngemark/aCT |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# This file is part of Karesansui.
#
# Copyright (C) 2009-2010 HDE, Inc.
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
import sqlalchemy
import sqlalchemy.orm
from pysilhouette.db.model import *
import sqlalchemy.pool
import sqlite
bind_name = 'sqlite:///:memory:'
def gs():
hoge = ':memory:'
return sqlite.connect('/tmp/hoge.db')
def main():
#qp = sqlalchemy.pool.QueuePool( gs , pool_size=5, max_overflow=100, echo=True)
#engine = sqlalchemy.create_engine(bind_name, encoding="utf8", echo=True, pool=qp)
#engine = sqlalchemy.create_engine(bind_name, encoding="utf8", echo=True, poolclass=sqlalchemy.pool.QueuePool)
engine = sqlalchemy.create_engine(bind_name, encoding="utf8", echo=True)
metadata = sqlalchemy.MetaData(bind=engine)
t_job_group = get_job_group_table(metadata)
t_job = get_job_table(metadata)
sqlalchemy.orm.mapper(JobGroup, t_job_group, properties={'jobs': sqlalchemy.orm.relation(Job)})
sqlalchemy.orm.mapper(Job, t_job)
metadata.drop_all()
metadata.create_all()
Session = sqlalchemy.orm.sessionmaker(engine)
session1 = Session()
session2 = Session()
session3 = Session()
hoge = session1.query(JobGroup).all()
jg1 = JobGroup(u'Test Success', '')
jg1.jobs.append(Job(u'日付取得','0','/bin/date', 'fdaf'))
session1.add(jg1)
session1.close()
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": false
},
{
"point_num": 2,
"id": "has_nested_function_def",
"question": "Does this file contain any function defined inside another function?",
... | 3 | tools/cleanlydb.py | GOMYWAY-NETWORKS-LLC/karesansui |
import datetime
from decimal import Decimal
from typing import Optional, NamedTuple
from enum import Enum, unique
@unique
class Signal(Enum):
UNKNOWN = 0
SELL = 1
UNDERPERFORM = 2
NEUTRAL = 3
HOLD = 4
OUTPERFORM = 5
BUY = 6
@classmethod
def from_text(cls, value: str) -> Enum:
return text_to_signal.get(value, Signal.UNKNOWN)
text_to_signal = {
'sälj': Signal.SELL,
'minska': Signal.SELL,
'neutral': Signal.NEUTRAL,
'jämvikt': Signal.HOLD,
'behåll': Signal.HOLD,
'köp': Signal.BUY,
'öka': Signal.BUY,
'underperform': Signal.UNDERPERFORM,
'outperform': Signal.OUTPERFORM,
'market perform': Signal.HOLD,
'sector perform': Signal.HOLD,
'övervikt': Signal.BUY,
'undervikt': Signal.SELL,
}
@unique
class Direction(Enum):
UNKNOWN = 0
LOWER = 1
NEW = 2
UNCHANGED = 3
RAISE = 4
@classmethod
def from_text(cls, value: str) -> Enum:
return text_to_direction.get(value, Direction.UNKNOWN)
text_to_direction = {
'sänker': Direction.LOWER,
'sänks': Direction.LOWER,
'höjer': Direction.RAISE,
'höjs': Direction.RAISE,
}
class Forecast(NamedTuple):
raw: str
extractor: Optional[str] = None
date: datetime.date = datetime.date.today()
analyst: Optional[str] = None
change_direction: Direction = Direction.UNKNOWN
company: Optional[str] = None
signal: Signal = Signal.UNKNOWN
prev_signal: Signal = Signal.UNKNOWN
forecast_price: Optional[Decimal] = None
prev_forecast_price: Optional[Decimal] = None
currency: Optional[str] = None
| [
{
"point_num": 1,
"id": "more_functions_than_classes",
"question": "Does this file define more functions than classes?",
"answer": false
},
{
"point_num": 2,
"id": "all_return_types_annotated",
"question": "Does every function in this file have a return type annotation?",
"answer... | 3 | stockrec/model.py | mrunesson/stockrec |
import json
from django import forms
from histonets.collections.models import Collection
class CollectionForm(forms.ModelForm):
images = forms.CharField(widget=forms.Textarea)
class Meta:
model = Collection
fields = ['label', 'description']
def clean_images(self):
try:
return json.loads(self.cleaned_data['images'])
except:
raise forms.ValidationError("Invalid data in images")
def save(self, commit=True):
super().save(commit=commit)
for image in self.cleaned_data['images']:
self.instance.images.create(label=image['label'], uri=image['uri'],
name=image.get('name'))
return self.instance
| [
{
"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 | histonets/collections/forms.py | sul-cidr/histonets-arch |
#!/usr/bin/python
"""
Turns on an LED on for one second, then off for one second, repeatedly.
Most Arduinos have an on-board LED you can control. On the Uno and
Leonardo, it is attached to digital pin 13. If you're unsure what
pin the on-board LED is connected to on your Arduino model, check
the documentation at http://www.arduino.cc
"""
from pymata_aio.pymata3 import PyMata3
from pymata_aio.constants import Constants
# Arduino LED is on pin 13
BOARD_LED = 13
# If you are having problems connecting, you may
# wish to add some time the arduino_wait parameter.
# replace:
# board = PyMata3()
# with:
# board = PyMata3(arduino_wait=5)
# adjust the arduino_wait value to meet the needs
# of your computer
# instantiate PyMata3
board = PyMata3()
def setup():
"""
Set the Arduino BOARD_LED pin as an output
:return:
"""
board.set_pin_mode(BOARD_LED, Constants.OUTPUT)
def loop():
"""
Toggle the LED by alternating the values written
to the LED pin. Wait 1 second between writes.
Also note the use of board.sleep and not
time.sleep.
:return:
"""
print("LED On")
board.digital_write(BOARD_LED, 1)
board.sleep(1.0)
print("LED Off")
board.digital_write(BOARD_LED, 0)
board.sleep(1.0)
if __name__ == "__main__":
setup()
while True:
loop() | [
{
"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 | pymata-aio/blink.py | hevangel/arduino_examples |
from src.harness.agentThread import AgentThread
class Task:
def __init__(self):
self.loc = None
self.assignId = None
self.taskId = None
class DefaultName(AgentThread):
def __init__(self, config, motion_config):
super(DefaultName, self).__init__(config, motion_config)
def initialize_vars(self):
self.locals = {}
self.locals['i'] = 0
self.locals['currentRoute'] = None
self.locals['newTask'] = None
self.locals['asgn'] = 0
self.locals['rchd'] = 1
self.locals['cmplt'] = 2
self.locals['stage'] = 0
self.create_aw_var('taskList', list, None)
self.create_ar_var('routes', list, None)
def loop_body(self):
if self.locals['stage'] == self.locals['asgn']:
self.locals['newTask'] = self.getAvailableNextTask(self.read_from_shared('taskList', None))
self.locals['currentRoute'] = self.getPathFromTask(self.locals['newTask'])
if not self.willCollide(self.locals['newTask']):
self.write_to_shared('routes', self.pid(), self.locals['currentRoute'])
self.write_to_actuator('Motion.route', self.locals['currentRoute'])
self.locals['stage'] = self.locals['rchd']
return
if self.locals['stage'] == self.locals['rchd'] and self.read_from_sensor('Motion.done'):
self.locals['stage'] = self.locals['asgn']
return
| [
{
"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 | GeneratedPython/tasks.py | cyphyhouse/KoordLanguage |
import discord
from discord.ext import commands
class List(commands.Cog):
def __init__(self, client):
self.client = client
@commands.command(name = 'listCommands', aliases = ['List', 'list'])
async def listCommands(self, ctx):
await ctx.send("List of Command:\n1. Ban: Can be used to ban a member ->\n\t Format: '.ban @username'. Can only be used by member with ban privileges.\n1. Kick: Can be used to kick a member ->\n\t Format: '.kick @username'. Can only be used by member with kick privileges.\n3. Ping: Can tell you the ping of the bot ->\n\t Format: '.ping'\n4. 8ball: Will help you take decisions, have fun with this one ->\n\t Format: '.8ball question?' ")
def setup(client):
client.add_cog(List(client))
| [
{
"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 | cogs/list.py | Shiv10/Kuwu |
"""
This is taken from "Simple Usage" page in the docs:
http://sanic-jwt.readthedocs.io/en/latest/pages/simpleusage.html
"""
from sanic import Sanic, response
from sanic_jwt import exceptions
from sanic_jwt import Initialize, protected
class User:
def __init__(self, id, username, password):
self.user_id = id
self.username = username
self.password = password
def __repr__(self):
return "User(id='{}')".format(self.user_id)
def to_dict(self):
return {"user_id": self.user_id, "username": self.username}
users = [User(1, "user1", "abcxyz"), User(2, "user2", "abcxyz")]
username_table = {u.username: u for u in users}
userid_table = {u.user_id: u for u in users}
async def authenticate(request, *args, **kwargs):
username = request.json.get("username", None)
password = request.json.get("password", None)
if not username or not password:
raise exceptions.AuthenticationFailed("Missing username or password.")
user = username_table.get(username, None)
if user is None:
raise exceptions.AuthenticationFailed("User not found.")
if password != user.password:
raise exceptions.AuthenticationFailed("Password is incorrect.")
return user
async def retrieve_user_secret(user_id):
print(f"{user_id=}")
return f"user_id|{user_id}"
app = Sanic(__name__)
Initialize(
app,
authenticate=authenticate,
user_secret_enabled=True,
retrieve_user_secret=retrieve_user_secret,
)
@app.route("/protected")
@protected()
async def protected(request):
return response.json({"protected": True})
if __name__ == "__main__":
app.run(host="127.0.0.1", port=8888, debug=True)
| [
{
"point_num": 1,
"id": "more_functions_than_classes",
"question": "Does this file define more functions than classes?",
"answer": true
},
{
"point_num": 2,
"id": "no_function_exceeds_5_params",
"question": "Does every function in this file take 5 or fewer parameters (excluding self/... | 3 | example/basic_with_user_secrets.py | jekel/sanic-jwt |
"""Test for the deprecation helper"""
# Authors: Guillaume Lemaitre <g.lemaitre58@gmail.com>
# License: MIT
import pytest
from imblearn.utils.deprecation import deprecate_parameter
class Sampler:
def __init__(self):
self.a = "something"
self.b = "something"
def test_deprecate_parameter():
with pytest.warns(FutureWarning, match="is deprecated from"):
deprecate_parameter(Sampler(), "0.2", "a")
with pytest.warns(FutureWarning, match="Use 'b' instead."):
deprecate_parameter(Sampler(), "0.2", "a", "b")
| [
{
"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 | imblearn/utils/tests/test_deprecation.py | cdchushig/imbalanced-learn |
#!/usr/bin/python3
import os
import json
class Config:
def __init__(self, filename):
self.filename = filename
self.data = dict()
# read config file, return true when success
def success(self):
try:
with open(self.filename) as f:
self.data = json.load(f)
except IOError:
print("Read Config failed")
return False
except ValueError:
print("Invalid Config JSON format")
return False
return True
# load config data
def load(self):
return self.data
| [
{
"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_function_names_snake_case",
"question": "Are all function names in this file written in snake_case?",
"answ... | 3 | 04_vnc_instance/config.py | Eudaemonal/AWS |
# Natural Language Toolkit: API for Language Models
#
# Copyright (C) 2001-2014 NLTK Project
# Author: Steven Bird <stevenbird1@gmail.com>
# URL: <http://nltk.org/>
# For license information, see LICENSE.TXT
# should this be a subclass of ConditionalProbDistI?
class ModelI(object):
"""
A processing interface for assigning a probability to the next word.
"""
def __init__(self):
'''Create a new language model.'''
raise NotImplementedError()
def prob(self, word, context):
'''Evaluate the probability of this word in this context.'''
raise NotImplementedError()
def logprob(self, word, context):
'''Evaluate the (negative) log probability of this word in this context.'''
raise NotImplementedError()
def choose_random_word(self, context):
'''Randomly select a word that is likely to appear in this context.'''
raise NotImplementedError()
def generate(self, n):
'''Generate n words of text from the language model.'''
raise NotImplementedError()
def entropy(self, text):
'''Evaluate the total entropy of a message with respect to the model.
This is the sum of the log probability of each word in the message.'''
raise NotImplementedError()
| [
{
"point_num": 1,
"id": "every_function_has_docstring",
"question": "Does every function in this file have a docstring?",
"answer": true
},
{
"point_num": 2,
"id": "all_params_annotated",
"question": "Does every function parameter in this file have a type annotation (excluding self/c... | 3 | api.py | curtislb/ReviewTranslation |
"""Support for local control of entities by emulating a Philips Hue bridge."""
import asyncio
import logging
from .config import Config
from .hass import HomeAssistant
from .hue_api import HueApi
from .upnp import UPNPResponderThread
_LOGGER = logging.getLogger(__name__)
class HueEmulator:
"""Support for local control of entitiesby emulating a Philips Hue bridge."""
def __init__(self, event_loop, data_path, hass_url, hass_token):
"""Create an instance of HueEmulator."""
self.event_loop = event_loop
self.config = Config(self, data_path, hass_url, hass_token)
self.hass = HomeAssistant(self)
self.hue_api = HueApi(self)
self.upnp_listener = UPNPResponderThread(self.config)
async def start(self):
"""Start running the Hue emulation."""
await self.hass.async_setup()
await self.hue_api.async_setup()
self.upnp_listener.start()
# wait for exit
try:
while True:
await asyncio.sleep(3600)
except asyncio.CancelledError:
_LOGGER.info("Application shutdown")
self.upnp_listener.stop()
await self.hue_api.stop()
| [
{
"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": "more_functions_than_classes",
"question": "Does this file define more functions than cla... | 3 | emulated_hue/__init__.py | amahlaka/hass_emulated_hue |
from pypy.interpreter.pyparser.asthelper import get_atoms
from pypy.interpreter.pyparser.grammar import Parser
from pypy.interpreter.pyparser import error
from fakes import FakeSpace
def test_symbols():
p = Parser()
x1 = p.add_symbol('sym')
x2 = p.add_token('tok')
x3 = p.add_anon_symbol(':sym')
x4 = p.add_anon_symbol(':sym1')
# test basic numbering assumption
# symbols and tokens are attributed sequentially
# using the same counter
assert x2 == x1 + 1
# anon symbols have negative value
assert x3 != x2 + 1
assert x4 == x3 - 1
assert x3 < 0
y1 = p.add_symbol('sym')
assert y1 == x1
y2 = p.add_token('tok')
assert y2 == x2
y3 = p.add_symbol(':sym')
assert y3 == x3
y4 = p.add_symbol(':sym1')
assert y4 == x4
def test_load():
d = { 5 : 'sym1',
6 : 'sym2',
9 : 'sym3',
}
p = Parser()
p.load_symbols( d )
v = p.add_symbol('sym4')
# check that we avoid numbering conflicts
assert v>9
v = p.add_symbol( 'sym1' )
assert v == 5
v = p.add_symbol( 'sym2' )
assert v == 6
v = p.add_symbol( 'sym3' )
assert v == 9
| [
{
"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 | pypy/interpreter/pyparser/test/test_parser.py | camillobruni/pygirl |
# -*- coding: utf-8 -*-
import pytest
from rest_framework.exceptions import ValidationError
@pytest.mark.django_db
def test_event_cannot_have_deprecated_keyword(event, keyword):
keyword.deprecated = True
keyword.save()
event.keywords.set([keyword])
with pytest.raises(ValidationError):
event.save()
event.keywords.set([])
event.audience.set([keyword])
with pytest.raises(ValidationError):
event.save()
@pytest.mark.django_db
def test_event_cannot_replace_itself(event):
event.replaced_by = event
event.deprecated = True
with pytest.raises(Exception):
event.save()
@pytest.mark.django_db
def test_prevent_circular_event_replacement(event, event2, event3):
event.replaced_by = event2
event.save()
event2.replaced_by = event3
event2.save()
event3.replaced_by = event
with pytest.raises(Exception):
event.save()
| [
{
"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_function_under_20_lines",
"question": "Is every function in this file shorter than 20 lines?",
"answ... | 3 | events/tests/test_event.py | ezkat/linkedevents |
class Pessoa:
def __init__(self, nome=None, idade=35):
self.idade = idade
self.nome = nome
def cumprimentar(self):
return f'Olá {id(self)}'
if __name__ == '__main__':
p = Pessoa('Luciano')
print(Pessoa.cumprimentar(p))
print(id(p))
print(p.cumprimentar())
print(p.nome)
p.nome = 'Flávio'
print(p.nome)
print(p.idade)
| [
{
"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": "more_functions_than_classes",
"question": "Does this file define more functions than classes?",
"answer... | 3 | oo/pessoa.py | Flavio123Fal/pythonbirds |
from __future__ import absolute_import, division, print_function, unicode_literals
import torch
import torch.nn.functional as F
from tests.utils import jitVsGlow
import unittest
class TestAdaptiveAvgPool2d(unittest.TestCase):
def test_adaptive_avg_pool2d_basic(self):
"""Basic test of PyTorch adaptive_avg_pool2d Node."""
def test_f(inputs):
return F.adaptive_avg_pool2d(inputs, (5, 5))
inputs = torch.randn(3, 6, 14, 14)
jitVsGlow(test_f, inputs, expected_fused_ops={
"aten::adaptive_avg_pool2d"})
def test_adaptive_avg_pool2d_nonsquare_inputs(self):
"""Test of PyTorch adaptive_avg_pool2d Node with non-square inputs."""
def test_f(inputs):
return F.adaptive_avg_pool2d(inputs, (3, 3))
inputs = torch.randn(3, 6, 13, 14)
jitVsGlow(test_f, inputs, expected_fused_ops={
"aten::adaptive_avg_pool2d"})
def test_adaptive_avg_pool2d_nonsquare_outputs(self):
"""Test of PyTorch adaptive_avg_pool2d Node with non-square outputs."""
def test_f(inputs):
return F.adaptive_avg_pool2d(inputs, (5, 3))
inputs = torch.randn(3, 6, 14, 14)
jitVsGlow(test_f, inputs, expected_fused_ops={
"aten::adaptive_avg_pool2d"})
| [
{
"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 | torch_glow/tests/nodes/adaptive_avg_pool2d_test.py | YonginKwon/glow |
def resolve():
'''
code here
'''
from functools import lru_cache
N = int(input())
@lru_cache(maxsize=10000000)
def fina(n):
if n == 0:
return 1
if n == 1:
return 1
return fina(n-1) + fina(n-2)
print(fina(N))
if __name__ == "__main__":
resolve()
| [
{
"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 | chapter_11/B/resolve_lru_cashe.py | staguchi0703/ALDS1 |
from django.conf import settings
from pipeline import manifest
class StaticManifest(manifest.PipelineManifest):
def cache(self):
if getattr(settings, "PIPELINE_ENABLED", None) or not settings.DEBUG:
for package in self.packages:
if self.pcs:
filename = self.pcs.hashed_name(package.output_filename)
else:
filename = package.output_filename
self.package_files.append(filename)
yield str(self.packager.individual_url(filename))
extra_resources = [
"//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js",
"//ajax.googleapis.com/ajax/libs/angularjs/1.0.6/angular.min.js",
"//code.angularjs.org/1.0.6/angular-resource.min.js",
"/static/img/favicon.ico",
]
for resource in extra_resources:
yield resource
def network(self):
return [
'*',
]
def fallback(self):
return [
# ('/', '/offline.html'),
]
| [
{
"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 | bilgisayfam/entry/manifest.py | tayfun/bilgisayfam |
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
from gaiatest import GaiaTestCase
from gaiatest.apps.clock.app import Clock
class TestClockSetAlarmRepeat(GaiaTestCase):
def setUp(self):
GaiaTestCase.setUp(self)
self.clock = Clock(self.marionette)
self.clock.launch()
def test_clock_set_alarm_repeat(self):
""" Modify the alarm repeat
https://moztrap.mozilla.org/manage/case/1786/
Test that [Clock][Alarm] Change the repeat state
"""
new_alarm = self.clock.tap_new_alarm()
# Set label
new_alarm.type_alarm_label("TestSetAlarmRepeat")
# loop the options and select the ones in match list
for option in ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday']:
new_alarm.select_repeat(option)
self.assertEqual('Weekdays', new_alarm.alarm_repeat)
# check select Sunday twice
new_alarm.select_repeat('Sunday')
self.assertEqual('Mon, Tue, Wed, Thu, Fri, Sun', new_alarm.alarm_repeat)
new_alarm.select_repeat('Sunday')
self.assertEqual('Weekdays', new_alarm.alarm_repeat)
# Save the alarm
new_alarm.tap_done()
self.clock.wait_for_banner_not_visible()
# Tap to Edit alarm
edit_alarm = self.clock.alarms[0].tap()
# To verify the select list.
self.assertEqual('Weekdays', edit_alarm.alarm_repeat)
# Close alarm
edit_alarm.tap_done()
self.clock.wait_for_banner_not_visible()
| [
{
"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/python/gaia-ui-tests/gaiatest/tests/functional/clock/test_clock_set_alarm_repeat.py | BReduardokramer/gaia |
import os, sys, inspect
import subprocess
from . import version
__version__ = version.get_current()
def get_current_dir_for_jupyter():
"""Get the current path for jupyter"""
return getCurrentDir(os.getcwd())
def get_current_dir(current_file):
"""Get the current path"""
current_dir = os.path.dirname(current_file)
return current_dir
def get_parent_dir(current_file):
"""Get the parth path"""
current_dir = os.path.dirname(current_file)
parent_dir = os.path.dirname(current_dir)
return parent_dir
def join(path, *paths):
"""Path join"""
return os.path.join(path, *paths)
def insert_parent_package_dir(current_file):
"""Insert parent package dir"""
current_dir = os.path.dirname(current_file)
parent_dir = os.path.dirname(current_dir)
sys.path.insert(0, parent_dir)
| [
{
"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 | my_happy_python_utils/path_utils.py | ggservice007/my-happy-python-utils |
# ----------------------------------------------------------------------------
# Copyright (c) 2016-2020, QIIME 2 development team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file LICENSE, distributed with this software.
# ----------------------------------------------------------------------------
from docutils import nodes
from sphinx.util.docutils import SphinxDirective
class QuestionAdmonition(nodes.Admonition, nodes.Element):
pass
class QuestionDirective(SphinxDirective):
has_content = True
def run(self):
target_id = 'question-%d' % self.env.new_serialno('question')
target_node = nodes.target('', '', ids=[target_id])
question_node = QuestionAdmonition(self.content)
question_node += nodes.title(text='Question')
question_node['classes'] += ['question']
self.state.nested_parse(self.content, self.content_offset,
question_node)
return [target_node, question_node]
def setup(app):
app.add_node(QuestionAdmonition,
html=(lambda s, n: s.visit_admonition(n),
lambda s, n: s.depart_admonition(n)))
app.add_directive('question', QuestionDirective)
return {'version': '0.0.2'}
| [
{
"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": false... | 3 | source/sphinx_extensions/question.py | HelenHip/docs |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.