source
string
points
list
n_points
int64
path
string
repo
string
from .base_trainer import BaseTrainer from .. import accuracy_evaluator class FineTuner(BaseTrainer): def __init__(self, *args, **kwargs): super(FineTuner, self).__init__(*args, **kwargs) def single_epoch_compute(self, model, x, y, mask): self.optimizer.zero_grad() output = model(x) loss = self.criterion(output, y) accs, _ = accuracy_evaluator.accuracy(output, y, topk=(1,)) acc = accs[0] loss.backward() self.optimizer.prune_step(mask) return acc, loss
[ { "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": "has_multiple_inheritance", "question": "Does any class in this file use multiple inherit...
3
nnutils/training_pipeline/trainers/finetuner.py
rexxy-sasori/nnutils
from PyQt5.QtWidgets import QLabel from Parents import Button, PathImage class OsrPath(PathImage): def __init__(self, parent): super(OsrPath, self).__init__(parent) self.default_x = 544 self.default_y = 165 self.default_size = 4.5 self.img = "res/OsrPath.png" self.img_shadow = "res/OsrPath_Shadow.png" super().setup() class MapSetPath(PathImage): def __init__(self, parent): super(MapSetPath, self).__init__(parent) self.default_x = 544 self.default_y = 200 self.default_size = 4.5 self.img = "res/MapsetPath.png" self.img_shadow = "res/MapsetPath_Shadow.png" super().setup()
[ { "point_num": 1, "id": "more_functions_than_classes", "question": "Does this file define more functions than classes?", "answer": false }, { "point_num": 2, "id": "every_function_under_20_lines", "question": "Is every function in this file shorter than 20 lines?", "answer": true...
3
HomeComponents/PathImage.py
Snake-GGJJWP/osr2mp4-app
import invoke from pathlib import Path PACKAGE = "src" REQUIRED_COVERAGE = 90 BASE_DIR = Path(__file__).resolve().parent @invoke.task(name="format") def format_(arg): autoflake = "autoflake -i --recursive --remove-all-unused-imports --remove-duplicate-keys --remove-unused-variables" arg.run(f"{autoflake} {PACKAGE}", echo=True) arg.run(f"isort {PACKAGE}", echo=True) arg.run(f"black {PACKAGE}", echo=True) @invoke.task( help={ "style": "Check style with flake8, isort, and black", "typing": "Check typing with mypy", } ) def check(arg, style=True, typing=True): if style: arg.run(f"flake8 {PACKAGE}", echo=True) arg.run(f"isort --diff {PACKAGE} --check-only", echo=True) arg.run(f"black --diff {PACKAGE} --check", echo=True) if typing: arg.run(f"mypy --no-incremental --cache-dir=/dev/null {PACKAGE}", echo=True) @invoke.task def test(arg): arg.run( f"pytest", pty=True, echo=True, ) @invoke.task def makemigrations(arg, message): arg.run(f"cd {BASE_DIR} && alembic revision --autogenerate -m '{message}'", echo=True, pty=True) @invoke.task def migrate(arg): arg.run(f"cd {BASE_DIR} && alembic upgrade head", echo=True) @invoke.task def hooks(arg): invoke_path = Path(arg.run("which invoke", hide=True).stdout[:-1]) for src_path in Path(".hooks").iterdir(): dst_path = Path(".git/hooks") / src_path.name print(f"Installing: {dst_path}") with open(str(src_path), "r") as f: src_data = f.read() with open(str(dst_path), "w") as f: f.write(src_data.format(invoke_path=invoke_path.parent)) arg.run(f"chmod +x {dst_path}")
[ { "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
tasks.py
brainfukk/fiuread
from django.contrib import admin from django.contrib.auth.admin import UserAdmin from markup.models import * class InlineProfile(admin.StackedInline): model = Profile verbose_name = 'Profile' verbose_name_plural = 'Profiles' can_delete = False class InlineFolders(admin.StackedInline): model = AllowedImagePack verbose_name = 'folder' verbose_name_plural = 'folders' can_delete = False @admin.register(MainUser) class MainUserAdmin(UserAdmin): inlines = [InlineProfile, InlineFolders] @admin.register(Profile) class ProfileAdmin(admin.ModelAdmin): list_display = ('id', 'bio', 'address', 'user', 'avatar') @admin.register(AllowedImagePack) class AllowedImagePackAdmin(admin.ModelAdmin): list_display = ('id', 'imagePack', 'user',) @admin.register(Image) class ImageAdmin(admin.ModelAdmin): list_display = ('id', 'name', 'file', 'imagePack_name', 'imagePack_id') def imagePack_name(self, obj): return obj.imagePack.name def imagePack_id(self, obj): return obj.imagePack.id imagePack_name.admin_order_field = 'Image Pack name' # Allows column order sorting imagePack_name.short_description = 'Image Pack Name' # Renames column head imagePack_id.admin_order_field = 'Image Pack id' # Allows column order sorting imagePack_id.short_description = 'Image Pack id' # Renames column head @admin.register(Polygon) class PolygonAdmin(admin.ModelAdmin): list_display = ('id', 'date_created', 'label', 'image', 'created_by', 'text') @admin.register(Label) class LabelAdmin(admin.ModelAdmin): list_display = ('id', 'name') @admin.register(Comment) class CommentAdmin(admin.ModelAdmin): list_display = ('id', 'date_created', 'created_by', 'text', 'image',) @admin.register(Folder) class FolderAdmin(admin.ModelAdmin): list_display = ('id', 'name', 'description', 'parent') @admin.register(ImagePack) class ImagePackAdmin(admin.ModelAdmin): list_display = ('id', 'name', 'description', 'parent')
[ { "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
markup/admin.py
vmun/SkyMed_Labeling
from python_framework import SchedulerType from python_framework import Scheduler, SchedulerMethod, WeekDay, WeekDayConstant @Scheduler(muteLogs=True) class EmissionScheduler: @SchedulerMethod(SchedulerType.INTERVAL, seconds=1, instancesUpTo=5) def updateAllModifiedFromMemory(self) : self.service.emission.updateAllModifiedFromMemory() @SchedulerMethod(SchedulerType.INTERVAL, seconds=0.1, instancesUpTo=100) def sendAllAcceptedFromOneQueue(self) : self.service.emission.sendAllAcceptedFromOneQueue()
[ { "point_num": 1, "id": "has_nested_function_def", "question": "Does this file contain any function defined inside another function?", "answer": false }, { "point_num": 2, "id": "more_functions_than_classes", "question": "Does this file define more functions than classes?", "answ...
3
api/src/scheduler/EmissionScheduler.py
SamuelJansen/queue-manager-api
from __future__ import absolute_import import ctypes from .._base import _LIB from .. import ndarray as _nd def max_pooling2d(in_arr, kernel_H, kernel_W, pooled_layer, padding=0, stride=1, stream=None): assert isinstance(in_arr, _nd.NDArray) assert isinstance(pooled_layer, _nd.NDArray) _LIB.DLGpuMax_Pooling2d(in_arr.handle, kernel_H, kernel_W, pooled_layer.handle, padding, stride, stream.handle if stream else None) def max_pooling2d_gradient(in_arr, in_grad_arr, kernel_H, kernel_W, out_grad_arr, padding=0, stride=1, stream=None): assert isinstance(in_arr, _nd.NDArray) assert isinstance(in_grad_arr, _nd.NDArray) assert isinstance(out_grad_arr, _nd.NDArray) _LIB.DLGpuMax_Pooling2d_gradient( in_arr.handle, in_grad_arr.handle, kernel_H, kernel_W, out_grad_arr.handle, padding, stride, stream.handle if stream else None)
[ { "point_num": 1, "id": "has_nested_function_def", "question": "Does this file contain any function defined inside another function?", "answer": false }, { "point_num": 2, "id": "all_params_annotated", "question": "Does every function parameter in this file have a type annotation (ex...
3
python/hetu/gpu_links/MaxPoolLink.py
initzhang/Hetu
from django.db import models class Event(models.Model): name = models.CharField(max_length=255) date = models.DateField() description = models.CharField(max_length=255) class EventRepo: @staticmethod def list(): return Event.objects.all() @staticmethod def get(id): return Event.objects.get(id) @staticmethod def save(event): event.save() @staticmethod def create(name, date, description): return Event.objects.create(name=name, date=date, description=description)
[ { "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_params_annotated", "question": "Does every function parameter in this file have a type annotation (excluding self/cls)?"...
3
event/models.py
SimonCockx/entity
import database def load_shard_from_db(conf): #TODO: load shard from cache if exists shards = database.load_shard(conf) return shards def get_shard(shards, url): """ Hash function for shading scheme returns a dict with hostname and table name Eg: s = { 'hostname': 'node1', 'table_name': 'url_s1'} """ if not shards: return {} else: return shards[hash(str(url['hostname'])+str(url['port'])+str(url['path'])) % len(shards)]
[ { "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
yama/shard.py
vitovitolo/yama
from abc import ABCMeta, abstractmethod import numpy as np from typing import Callable, Dict, List from ..core.position import Position from .route import Route class BaseRouter(metaclass=ABCMeta): @abstractmethod def map_match(self, position: Position) -> Position: return NotImplemented @abstractmethod def calculate_route(self, origin: Position, destination: Position) -> Route: """Calculate route between 2 points :param origin: Position :param destination: Position :return: Route :rtype: Route """ return NotImplemented @abstractmethod def estimate_duration(self, origin: Position, destination: Position) -> int: """Duration in clock units :param origin: Position :param destination: Position :return: Trip duration in clock units :rtype: int """ return NotImplemented @abstractmethod def calculate_distance_matrix( self, sources: List[Position], destinations: List[Position], travel_time: bool = True, ) -> List[List[float]]: """Calculate all-to-all travel time - all source to all destinations. Here distance means "distance in time" :param sources: List of Positions :param destinations: List of Positions :return: All-to-all trip durations (distance in time) in clock units (``distance_matrix``) :rtype: np.array """ return NotImplemented
[ { "point_num": 1, "id": "all_return_types_annotated", "question": "Does every function in this file have a return type annotation?", "answer": true }, { "point_num": 2, "id": "all_params_annotated", "question": "Does every function parameter in this file have a type annotation (exclu...
3
simobility/routers/base_router.py
yabirgb/simobility
# The code here is based on the code at # https://github.com/gpleiss/temperature_scaling/blob/master/temperature_scaling.py import torch from torch import nn, optim from torch.nn import functional as F from torch.autograd import Variable import numpy as np def logits_from_probs(prob_arr): return np.log(prob_arr) def optimal_temp_scale(probs_arr, labels_arr, lr=0.01, max_iter=50): probs = torch.from_numpy(probs_arr).float() labels = torch.from_numpy(labels_arr.astype(int)) logits = torch.log(probs + 1e-12) nll_criterion = nn.CrossEntropyLoss() before_temperature_nll = nll_criterion(logits, labels).item() print('Before temperature - NLL: %.3f' % (before_temperature_nll)) T = Variable(torch.ones(1,), requires_grad=True) optimizer = optim.LBFGS([T], lr=lr, max_iter=max_iter) def eval(): loss = nll_criterion(logits / T, labels) loss.backward(retain_graph=True) return loss optimizer.step(eval) after_temperature_nll = nll_criterion(logits / T, labels).item() print('After temperature - NLL: %.3f' % (after_temperature_nll), ", Temperature:", T) return T.item(), F.softmax(logits / T).data.numpy() def rescale_temp(probs_arr, temp): logits = np.log(probs_arr) logits /= temp probs = np.exp(logits) probs /= np.sum(probs, axis=1)[:, None] return probs
[ { "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": "all_function_names_snake_case", "question": "Are all function names in this file written in snake_case?", ...
3
experiments/uncertainty/temp_scaling.py
probabilisticdeeplearning/swa_gaussian
import cherrypy import datetime import logging from girder import auditLogger from girder.models.model_base import Model from girder.api.rest import getCurrentUser class Record(Model): def initialize(self): self.name = 'audit_log_record' def validate(self, doc): return doc class _AuditLogDatabaseHandler(logging.Handler): def handle(self, record): user = getCurrentUser() Record().save({ 'type': record.msg, 'details': record.details, 'ip': cherrypy.request.remote.ip, 'userId': user and user['_id'], 'when': datetime.datetime.utcnow() }, triggerEvents=False) def load(info): auditLogger.addHandler(_AuditLogDatabaseHandler())
[ { "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
plugins/audit_logs/server/__init__.py
data-exp-lab/girder
import asyncio import os from pstats import Stats from tempfile import NamedTemporaryFile from aiomisc.service.profiler import Profiler async def test_profiler_start_stop(): profiler = Profiler(interval=0.1, top_results=10) try: await profiler.start() await asyncio.sleep(0.5) finally: await profiler.stop() async def test_profiler_dump(): profiler = None fl = NamedTemporaryFile(delete=False) path = NamedTemporaryFile(delete=False).name fl.close() try: profiler = Profiler( interval=0.1, top_results=10, path=path ) await profiler.start() # Get first update await asyncio.sleep(0.01) stats1 = Stats(path) # Not enough sleep till next update await asyncio.sleep(0.01) stats2 = Stats(path) # Getting the same dump assert stats1.stats == stats2.stats # Enough sleep till next update await asyncio.sleep(0.2) stats3 = Stats(path) # Getting updated dump assert stats2.stats != stats3.stats finally: if profiler: await profiler.stop() os.remove(path)
[ { "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
tests/test_profiler.py
MrPainter/aiomisc
import numpy as np import itertools from panda3d.core import Point3, BoundingBox from citysim3d.envs import SimpleQuadPanda3dEnv from citysim3d.spaces import BoxSpace class Bbox3dSimpleQuadPanda3dEnv(SimpleQuadPanda3dEnv): def __init__(self, *args, **kwargs): super(Bbox3dSimpleQuadPanda3dEnv, self).__init__(*args, **kwargs) self._observation_space.spaces['points'] = BoxSpace(-np.inf, np.inf, shape=(8, 3)) # uncomment to visualize bounding box (makes rendering slow) # self.car_env._car_local_node.showTightBounds() def observe(self): obj_node = self.car_env._car_local_node cam_node = self.camera_node bounds = BoundingBox(*obj_node.getTightBounds()) corners_XYZ = np.array(list(itertools.product(*zip(bounds.getMin(), bounds.getMax())))) obj_to_cam_T = obj_node.getParent().getMat(cam_node) corners_XYZ = np.array([obj_to_cam_T.xform(Point3(*corner_XYZ)) for corner_XYZ in corners_XYZ])[:, :3] obs = super(Bbox3dSimpleQuadPanda3dEnv, self).observe() obs['points'] = corners_XYZ return obs
[ { "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
citysim3d/envs/bbox3d_quad_panda3d_env.py
alexlee-gk/citysim3d
"""circle module: contains the Circle class.""" class Circle: """circle class""" all_circles= [] pit= 3.14159 def __init__(self, r=1): """create a circle with the given radius""" self.radius=r self.__class__.all_circles.append(self) def area(self): """ determine the area of the cirle""" return self.__class__.pi * self.radius**2 @staticmethod def total_area(): total = 0 for c in Circle.all_circles: total += c.area() return total @classmethod def total_area(cls): total=0 for c in cls.all_circles: total +=c.area() return total
[ { "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
course2/session2/class.py
artopping/nyu-python
from django.db import models from datetime import datetime, timedelta from Client.models import Client class OffersHistory(models.Model): date_time_generated = models.DateTimeField(auto_now_add=True) date_time_expire = models.DateTimeField(null=False, blank=False) is_expired = models.BooleanField(default=False) client = models.ForeignKey(Client, related_name='client_offers', on_delete=models.PROTECT, null=True, blank=False) class Meta: db_table = 'offers_history' def save(self, *args, **kwargs): expire = datetime.now() + timedelta(minutes=10) self.date_time_expire = expire super(OffersHistory, self).save(*args, **kwargs) class Offers(models.Model): partner_id = models.IntegerField(blank=True, null=False) partner_name = models.CharField(max_length=200, null=False, blank=True) value = models.FloatField(blank=False, null=True) tax_rate_percent_montly = models.FloatField(blank=False, null=True) total_value = models.FloatField(blank=False, null=True) installments = models.IntegerField(blank=False, null=True) history = models.ForeignKey(OffersHistory, related_name="fk_offers_history", on_delete=models.CASCADE, null=True, blank=False) class Meta: db_table = "offers"
[ { "point_num": 1, "id": "more_functions_than_classes", "question": "Does this file define more functions than classes?", "answer": false }, { "point_num": 2, "id": "has_multiple_inheritance", "question": "Does any class in this file use multiple inheritance?", "answer": false }...
3
MarketPlace_api/Offers/models.py
giovani-dev/Marketplace-api
import pytest from chapter1 import zerofy as t def test_zerofy(): expected = [[1, 0, 1], [0, 0, 0], [1, 0, 1]] actual = t.zerofy([[1, 1, 1], [1, 0, 1], [1, 1, 1]]) for y in range(len(expected)): for x in range(len(expected[0])): assert expected[y][x] == actual[y][x] expected = [[0, 0, 0], [0, 1, 1], [0, 1, 1]] actual = t.zerofy([[0, 1, 1], [1, 1, 1], [1, 1, 1]]) for y in range(len(expected)): for x in range(len(expected[0])): assert expected[y][x] == actual[y][x] def test_zerofy_allzero(): expected = [[0, 0], [0, 0]] actual = t.zerofy([[0, 0], [0, 0]]) for y in range(len(expected)): for x in range(len(expected[0])): assert expected[y][x] == actual[y][x] def test_zerofy_empty(): assert t.zerofy([]) == []
[ { "point_num": 1, "id": "every_function_has_docstring", "question": "Does every function in this file have a docstring?", "answer": false }, { "point_num": 2, "id": "all_function_names_snake_case", "question": "Are all function names in this file written in snake_case?", "answer"...
3
cracking-the-coding-interview/tests/chapter1/test_zerofy.py
silphire/training-with-books
from django.shortcuts import render, get_object_or_404 from .models import Category, Product from cart.forms import CartAddProductForm from django.views.generic import ( ListView, DetailView ) ''' class ProductListView(ListView): template_name = 'shop/product/list.html' queryset = Product.objects.all() def get_context_data(self, **kwargs): context = super(ProductListView, self).get_context_data(**kwargs) context['category_list'] = Category.objects.all() return context ''' def product_list(request, category_slug=None): category = None categories = Category.objects.all() products = Product.objects.filter(available=True) if category_slug: category = get_object_or_404(Category, slug=category_slug) products = Product.objects.filter(category=category) context = { 'category': category, 'categories': categories, 'products': products } return render(request, 'shop/product/list.html', context) def product_detail(request, id, slug): product = get_object_or_404(Product, id=id, slug=slug, available=True) cart_product_form = CartAddProductForm() context = { 'product': product, 'cart_product_form': cart_product_form } return render(request, 'shop/product/detail.html', context)
[ { "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
shop/views.py
Honormmm/shop
import logging from .Container import Container class MqttBrokerContainer(Container): def __init__(self, name, vols, network, image_store, command=None): super().__init__(name, 'mqtt-broker', vols, network, image_store, command) def get_startup_finished_log_entry(self): return "mosquitto version [0-9\\.]+ running" def deploy(self): if not self.set_deployed(): return logging.info('Creating and running MQTT broker docker container...') self.client.containers.run( self.image_store.get_image(self.get_engine()), detach=True, name=self.name, network=self.network.name, ports={'1883/tcp': 1883}, entrypoint=self.command) logging.info('Added container \'%s\'', self.name)
[ { "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
docker/test/integration/minifi/core/MqttBrokerContainer.py
rustammendel/nifi-minifi-cpp
# -*- coding: utf-8 -*- # Copyright (c) 2018, masonarmani38@gmail.com and contributors # For license information, please see license.txt from __future__ import unicode_literals import frappe from frappe.model.document import Document from frappe.model.mapper import get_mapped_doc class WorkOrder(Document): pass @frappe.whitelist() def get_requested_by(ticket_number): ticket = frappe.get_doc("Equipment Support", ticket_number) employee = frappe.get_doc("Employee", ticket.raised_by) return employee.name @frappe.whitelist() def get_employee_name(ticket_number): ticket = frappe.get_doc("Equipment Support", ticket_number) employee = frappe.get_doc("Employee", ticket.raised_by) return employee.employee_name @frappe.whitelist() def make_purchase_order(source_name, target_doc=None): def set_missing_values(source, target): target.ignore_pricing_rule = 1 target.run_method("set_missing_values") target.run_method("get_schedule_dates") target.run_method("calculate_taxes_and_totals") target_doc = get_mapped_doc("Work Order", source_name, { "Job Card": { "doctype": "Purchase Order", "field_map": { "vendor": "supplier", "date": "transaction_date", "name": "work_order" } }, "Job Card Material Detail": { "doctype": "Purchase Order Item", "field_map": { "item_code": "item_code", "item_name": "item_name", "item_description": "description", "uom": "stock_uom", "no_of_units": "qty", "unit_cost": "rate", "conversion_factor": 1, "total": "amount" } } }, target_doc, set_missing_values) return target_doc
[ { "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
tools_box/tools_box/doctype/work_order/work_order.py
maisonarmani/Tools-Box
""" function for analyzing molecules """ from .measure import calculate_distance from .atom_data import atomic_weights def build_bond_list(coordinates, max_bond=1.5, min_bond=0): # Find the bonds in a molecule (set of coordinates) based on distance criteria. bonds = {} num_atoms = len(coordinates) for atom1 in range(num_atoms): for atom2 in range(atom1, num_atoms): distance = calculate_distance(coordinates[atom1], coordinates[atom2]) if distance > min_bond and distance < max_bond: bonds[(atom1, atom2)] = distance return bonds def calculate_molecular_mass(symbols): """Calculate the mass of a molecule. Parameters ---------- symbols : list A list of elements. Returns ------- mass : float The mass of the molecule """ mass = 0 for atom in symbols: mass+= atomic_weights[atom] return mass
[ { "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
molecool/molecule.py
mmim2904/molecool
# Copyright (c) 2019 Platform9 Systems Inc. # # 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. from sqlalchemy import Boolean from sqlalchemy import Column from sqlalchemy import DateTime from sqlalchemy import Integer from sqlalchemy import MetaData from sqlalchemy import String from sqlalchemy import Table meta = MetaData() cluster = Table( 'clusters', meta, Column('id', Integer, primary_key=True), Column('deleted', Integer, default=None), Column('name', String(255), default=None), Column('enabled', Boolean, default=False), Column('status', String(36), default=1), Column('updated_at', DateTime, default=None), Column('created_at', DateTime, default=None), Column('deleted_at', DateTime, default=None) ) def upgrade(migrate_engine): meta.bind = migrate_engine cluster.create() def downgrade(migrate_engine): meta.bind = migrate_engine cluster.drop()
[ { "point_num": 1, "id": "all_return_types_annotated", "question": "Does every function in this file have a return type annotation?", "answer": false }, { "point_num": 2, "id": "every_function_has_docstring", "question": "Does every function in this file have a docstring?", "answe...
3
hamgr/hamgr/db/versions/001_add_initial_tables.py
platform9/pf9-ha
# -*- coding: UTF-8 -*- from pp.store import redis from pp.search import search_url from flask import Flask, Response, render_template, request, redirect, abort from flask.ext.assets import Environment, Bundle from flask.ext.misaka import Misaka from flask.ext.cache import Cache from htmlmin.minify import html_minify from webassets_iife import IIFE app = Flask(__name__) # markdown Misaka(app) # caching app.config['CACHE_TYPE'] = 'simple' cache = Cache(app) # assets assets = Environment(app) # - JS js = Bundle('js/angular.min.js', 'js/mousetrap.js', 'js/wMousetrap.js', 'js/app.js', # closure_js is too aggressive for our angular app, it renames # every Angular identifier (e.g. .controller, .config, .module). We # fallback on the simpler yui_js filters=(IIFE, 'yui_js'), output='pp.js') assets.register('js_all', js) js = Bundle('js/text.js', filters=(IIFE, 'closure_js'), output='t.js') assets.register('js_articles', js) # - CSS css = Bundle('css/normalize.css', 'css/icons.css', 'css/app.css', filters=('cssmin',), output='pp.css') assets.register('css_all', css) @cache.cached(timeout=60) # 1 minute @app.route('/') def index(): html = render_template('main.html') return html_minify(html) @cache.cached(timeout=86400) # 24 hours @app.route('/about') def about(): html = render_template('about.html') return html_minify(html) @cache.cached(timeout=7200) # 2 hours @app.route('/json') def people_json(): resp = redis.get('people.json') or '[]' return Response(resp, 200, mimetype='application/json') @app.route('/search/url') def search(): """ server-side URL search """ url = search_url(request.args['q']) if url: return redirect(url, code=303) # 303 = See Other abort(404)
[ { "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.py
bfontaine/web-pp
import requests from time import sleep import random from multiprocessing import Process import boto3 import json import sqlalchemy random.seed(100) class AWSDBConnector: def __init__(self): self.HOST = "pinterestdbreadonly.cq2e8zno855e.eu-west-1.rds.amazonaws.com" self.USER = 'project_user' self.PASSWORD = ':t%;yCY3Yjg' self.DATABASE = 'pinterest_data' self.PORT = 3306 def create_db_connector(self): engine = sqlalchemy.create_engine(f"mysql+pymysql://{self.USER}:{self.PASSWORD}@{self.HOST}:{self.PORT}/{self.DATABASE}?charset=utf8mb4") return engine new_connector = AWSDBConnector() def run_infinite_post_data_loop(): while True: sleep(random.randrange(0, 2)) random_row = random.randint(0, 11000) engine = new_connector.create_db_connector() selected_row = engine.execute(f"SELECT * FROM pinterest_data LIMIT {random_row}, 1") for row in selected_row: result = dict(row) requests.post("http://localhost:8000/pin/", json=result) print(result) if __name__ == "__main__": run_infinite_post_data_loop() print('Working')
[ { "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
User_Emulation/user_posting_emulation.py
VBamgbaye/Pintrest_project
from .... pyaz_utils import _call_az def show(resource_group, server): ''' Gets a server's secure connection policy. Required Parameters: - resource_group -- Name of resource group. You can configure the default group using `az configure --defaults group=<name>` - server -- Name of the Azure SQL server. You can configure the default using `az configure --defaults sql-server=<name>` ''' return _call_az("az sql server conn-policy show", locals()) def update(connection_type, resource_group, server): ''' Updates a server's secure connection policy. Required Parameters: - connection_type -- The required parameters for updating a secure connection policy. The value is default - resource_group -- Name of resource group. You can configure the default group using `az configure --defaults group=<name>` - server -- Name of the Azure SQL server. You can configure the default using `az configure --defaults sql-server=<name>` ''' return _call_az("az sql server conn-policy update", locals())
[ { "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
pyaz/sql/server/conn_policy/__init__.py
py-az-cli/py-az-cli
import unittest from .testHelpers import get_cpp_function_list class TestCommentOptions(unittest.TestCase): def test_function_with_comment_option_should_be_forgiven(self): function_list = get_cpp_function_list("void foo(){/* #lizard forgives*/}") self.assertEqual(0, len(function_list)) def test_function_with_comment_option_before_it_should_be_forgiven(self): function_list = get_cpp_function_list("/* #lizard forgives*/void foo(){}") self.assertEqual(0, len(function_list)) def test_function_after_comment_option_should_not_be_forgiven(self): function_list = get_cpp_function_list("/* #lizard forgives*/void foo(){}void bar(){}") self.assertEqual(1, len(function_list)) def test_generated_code_should_be_ignored(self): function_list = get_cpp_function_list("/* GENERATED CODE */void foo(){}") self.assertEqual(0, len(function_list))
[ { "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
test/testCommentOptions.py
apiiro/lizard
# # Copyright (c) 2018 Stefan Seefeld # All rights reserved. # # This file is part of Faber. It is made available under the # Boost Software License, Version 1.0. # (Consult LICENSE or http://www.boost.org/LICENSE_1_0.txt) from ..action import action from ..feature import set from ..tool import tool from .xslt import process import os from os.path import join class quickbook(tool): process = action('quickbook --input-file=$(>) --output-file=$(<)') def __init__(self, name='quickbook', command=None, version='', features=()): tool.__init__(self, name=name, version=version) self.features |= features if command: self.process.subst('quickbook', command) class boostbook(tool): db = process() # bb -> db html = process() # db -> html def __init__(self, name='boostbook', command=None, version='', prefix='', features=()): tool.__init__(self, name=name, version=version) self.features |= set.instantiate(features) if command: self.db.subst('xsltproc', command) self.html.subst('xsltproc', command) if not prefix and 'BOOST_ROOT' in os.environ: prefix = join(os.environ['BOOST_ROOT'], 'tools/boostbook') if prefix: db_xsl = prefix + '/xsl/docbook.xsl' self.db.subst('$(stylesheet)', db_xsl) html_xsl = prefix + '/xsl/html.xsl' self.html.subst('$(stylesheet)', html_xsl) else: raise ValueError('no prefix set and $BOOST_ROOT undefined')
[ { "point_num": 1, "id": "has_multiple_inheritance", "question": "Does any class in this file use multiple inheritance?", "answer": false }, { "point_num": 2, "id": "every_class_has_docstring", "question": "Does every class in this file have a docstring?", "answer": false }, {...
3
src/faber/tools/boost.py
drmoose/faber
#!/usr/bin/env python # Copied from fftpack.helper by Pearu Peterson, October 2005 """ Test functions for fftpack.helper module """ from numpy.testing import * from numpy.fft import fftshift,ifftshift,fftfreq from numpy import pi def random(size): return rand(*size) class TestFFTShift(TestCase): def test_definition(self): x = [0,1,2,3,4,-4,-3,-2,-1] y = [-4,-3,-2,-1,0,1,2,3,4] assert_array_almost_equal(fftshift(x),y) assert_array_almost_equal(ifftshift(y),x) x = [0,1,2,3,4,-5,-4,-3,-2,-1] y = [-5,-4,-3,-2,-1,0,1,2,3,4] assert_array_almost_equal(fftshift(x),y) assert_array_almost_equal(ifftshift(y),x) def test_inverse(self): for n in [1,4,9,100,211]: x = random((n,)) assert_array_almost_equal(ifftshift(fftshift(x)),x) class TestFFTFreq(TestCase): def test_definition(self): x = [0,1,2,3,4,-4,-3,-2,-1] assert_array_almost_equal(9*fftfreq(9),x) assert_array_almost_equal(9*pi*fftfreq(9,pi),x) x = [0,1,2,3,4,-5,-4,-3,-2,-1] assert_array_almost_equal(10*fftfreq(10),x) assert_array_almost_equal(10*pi*fftfreq(10,pi),x) if __name__ == "__main__": run_module_suite()
[ { "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
numpy/fft/tests/test_helper.py
enthought/numpy-refactor
class CustomArgs(object): pass _args = CustomArgs() def get_global_args(): global _args return _args def set_global_arg(arg, value): global _args setattr(_args, arg,value) def set_global_args(args): for k,v in args.items(): set_global_arg(k, v) def set_dry_run(): set_global_arg('dry_run', True) def is_dry_run(): global _args return hasattr(_args, 'dry_run') and _args.dry_run def set_trace(): set_global_arg('trace', True) def is_trace(): global _args return hasattr(_args, 'trace') and _args.trace def set_production(): set_global_arg('production', True) def is_production(): global _args return hasattr(_args, 'production') and _args.production def set_minikube(): set_global_arg('minikube', True) def is_minikube(): global _args return hasattr(_args, 'minikube') and _args.minikube
[ { "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
lib/args_helper.py
wxw-matt/rails_on_docker
from __future__ import annotations from typing import Callable, Dict, TYPE_CHECKING if TYPE_CHECKING: # pylint: disable=cyclic-import from tarkov.trader.models import TraderType from tarkov.trader.trader import Trader class TraderManager: def __init__(self, trader_factory: Callable[..., Trader]) -> None: self.__trader_factory = trader_factory self.__traders: Dict[TraderType, Trader] = {} def get_trader(self, trader_type: TraderType) -> Trader: if trader_type not in self.__traders: self.__traders[trader_type] = self.__trader_factory(trader_type) return self.__traders[trader_type]
[ { "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
tarkov/trader/manager.py
JustEmuTarkov/jet_py
import pytest from uzi.markers import ProSlice as Predicate xfail = pytest.mark.xfail parametrize = pytest.mark.parametrize @pytest.fixture def cls(): return Predicate from .cases import * _T_New = T_New[Predicate] def test_pro_entries(new_predicate: _T_New, MockProPredicate: _T_New, MockContainer): pred1, pred2 = MockProPredicate(), MockProPredicate() n = 16 containers = tuple(MockContainer() for _ in range(n)) pred1.pro_entries.return_value = containers[n // 4 :] pred2.pro_entries.return_value = containers[-n // 4 :] sub = new_predicate(pred1, pred2) assert sub.pro_entries(containers, None, None) == containers[n // 4 : -n // 4] sub = new_predicate(pred1) assert sub.pro_entries(containers, None, None) == containers[n // 4 :] sub = new_predicate(pred1, pred2, 2) assert sub.pro_entries(containers, None, None) == containers[n // 4 : -n // 4 : 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": "all_params_annotated", "question": "Does every function parameter in this file have a type annotation (excluding se...
3
tests/predicates/slice_predicate_tests.py
laza-toolkit/di
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you 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. """Creates a simple TVM modules.""" import argparse import os import logging from PIL import Image import numpy as np def preprocess_image(image_file): resized_image = Image.open(image_file).resize((224, 224)) image_data = np.asarray(resized_image).astype("float32") # after expand_dims, we have format NCHW image_data = np.expand_dims(image_data, axis=0) image_data[:, :, :, 0] = 2.0 / 255.0 * image_data[:, :, :, 0] - 1 image_data[:, :, :, 1] = 2.0 / 255.0 * image_data[:, :, :, 1] - 1 image_data[:, :, :, 2] = 2.0 / 255.0 * image_data[:, :, :, 2] - 1 return image_data def build_inputs(): x = preprocess_image("lib/cat.png") print("x", x.shape) with open("lib/input.bin", "wb") as fp: fp.write(x.astype(np.float32).tobytes()) if __name__ == "__main__": build_inputs()
[ { "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
apps/deploy_tflite_cpp/build_input.py
DzAvril/tvm
from django.core.paginator import Paginator from django.shortcuts import render from django.http import HttpResponse from .models import Branch, Category from songs.models import Song from artists.models import Artist # Create your views here. def category_index(request): categories = Category.objects.all() return render(request,"categories/index.html",{'categories':categories}) def category_show(request, slug): category = Category.objects.filter(slug=slug)[0] return render(request,"categories/show.html",{'category':category}) def branch_index(request): branches = Branch.objects.all() return render(request,"branches/index.html",{'branches':branches}) def branch_show(request, acronym): branch = Branch.objects.filter(acronym=acronym)[0] songs = Song.objects.filter(branch=branch) paginator = Paginator(songs, 100) page_number = request.GET.get('page',1) page_obj = paginator.get_page(page_number) return render(request,"branches/show.html",{'branch':branch,'page_obj':page_obj})
[ { "point_num": 1, "id": "all_function_names_snake_case", "question": "Are all function names in this file written in snake_case?", "answer": true }, { "point_num": 2, "id": "no_function_exceeds_5_params", "question": "Does every function in this file take 5 or fewer parameters (exclu...
3
categories/views.py
Damillora/Altessimo
import os import cherrypy from girder.exceptions import ValidationException from girder.models.assetstore import Assetstore from girder.models.setting import Setting from girder.models.user import User cherrypy.config["database"]["uri"] = os.getenv("GIRDER_MONGO_URI") ADMIN_USER = os.getenv("GIRDER_ADMIN_USER", "admin") ADMIN_PASS = os.getenv("GIRDER_ADMIN_PASS", "letmein") def createInitialUser(): try: User().createUser( ADMIN_USER, ADMIN_PASS, ADMIN_USER, ADMIN_USER, "admin@admin.com", admin=True, public=True, ) except ValidationException: print("Admin user already exists, skipping...") def createAssetstore(): try: Assetstore().createFilesystemAssetstore("assetstore", "/home/assetstore") except ValidationException: print("Assetstore already exists, skipping...") def configure(): Setting().set( "core.cors.allow_origin", os.environ.get( "CORS_ALLOWED_ORIGINS", "http://localhost:8080, http://localhost:8010" ), ) if __name__ == '__main__': createInitialUser() createAssetstore() configure()
[ { "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_under_20_lines", "question": "Is every function in this file shorter than 20 lines?", "ans...
3
docker/server_setup.py
maxpark/dive
import unittest from facial_recog.app import * from .test_config import test_run_count, seed, success_perc from .test_util import * class TestFR(unittest.TestCase): subject_names = dict() subject_classes = dict() def setUp(self): random.seed(seed) create_app_dirs() setup_logger() logging.debug('Seed is %s', seed) # only for super strict testing # clear_fdb() prepare_fdb() self.subject_names, self.subject_classes = create_sample() logging.info('Subject names: %s', self.subject_names) logging.info('Subject classes are: %s', self.subject_classes) recreate_db() populate_db(self.subject_classes) logging.info('New db created') clear_dataset() copy_dataset(subject_names=self.subject_names) logging.info('Training Dataset created') clear_recognizers() for class_id in get_all_classes(): train(class_id=class_id) logging.info('Classifiers trained') def test_fr(self): success = 0 for _ in range(test_run_count): random_class = random.choice(get_all_classes()) random_subject = random.choice(get_class_subjects(random_class)) random_image = random.choice( get_images_for_subject(subject_name=self.subject_names[random_subject])) logging.info('Testing subject %s in class %s with image %s', random_subject, random_class, random_image) if predict(img=path_to_img(random_image), class_id=random_class) == random_subject: success += 1 logging.info('Test success') else: logging.warning('Test failed') self.assertGreaterEqual(success, int(success_perc * test_run_count))
[ { "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
facial_recog/tests/test_app.py
MePsyDuck/amfr
import pickle from src.probabilistic_models.grammar_utils import score, update from math import log from decimal import Decimal def probabilistic_model_guesses(password): scores = pickle.load(open("scores.p", "rb")) (cb_counter, Q) = pickle.load(open("cb_dictionary.p", "rb")) (sb_counter, B) = pickle.load(open("sb_dictionary.p", "rb")) score_password = score(password, cb_counter, sb_counter, Q, B) len_score = len(scores) rank_password = 0 for i in range(len_score) : if scores[i] > score_password : rank_password += 1/ (scores[i]*len_score) return int(rank_password) def probabilistic_model_result(password): guesses = probabilistic_model_guesses(password) update(password) return { "guesses_log10" : log(guesses, 10), "guesses" : Decimal(guesses), "sequence" : [], "password" : password, "pattern" : "probabilistic_model" }
[ { "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
src/probabilistic_models/probabilistic_model.py
pfreifer/zxcvbn
""" Ory APIs Documentation for all public and administrative Ory APIs. Administrative APIs can only be accessed with a valid Personal Access Token. Public APIs are mostly used in browsers. # noqa: E501 The version of the OpenAPI document: v0.0.1-alpha.71 Contact: support@ory.sh Generated by: https://openapi-generator.tech """ import sys import unittest import ory_client from ory_client.model.submit_self_service_settings_flow_with_lookup_method_body import SubmitSelfServiceSettingsFlowWithLookupMethodBody class TestSubmitSelfServiceSettingsFlowWithLookupMethodBody(unittest.TestCase): """SubmitSelfServiceSettingsFlowWithLookupMethodBody unit test stubs""" def setUp(self): pass def tearDown(self): pass def testSubmitSelfServiceSettingsFlowWithLookupMethodBody(self): """Test SubmitSelfServiceSettingsFlowWithLookupMethodBody""" # FIXME: construct object with mandatory attributes with example values # model = SubmitSelfServiceSettingsFlowWithLookupMethodBody() # noqa: E501 pass if __name__ == '__main__': unittest.main()
[ { "point_num": 1, "id": "every_function_under_20_lines", "question": "Is every function in this file shorter than 20 lines?", "answer": true }, { "point_num": 2, "id": "has_multiple_inheritance", "question": "Does any class in this file use multiple inheritance?", "answer": false...
3
clients/client/python/test/test_submit_self_service_settings_flow_with_lookup_method_body.py
sproutfi/sdk
# !/usr/bin/env python # -- coding: utf-8 -- # @Author zengxiaohui # Datatime:8/31/2021 2:50 PM # @File:SpaceToDepthModuleConv import torch import torch.nn as nn class SpaceToDepth(nn.Module): def __init__(self, block_size=4): super().__init__() assert block_size == 4 self.bs = block_size def forward(self, x): N, C, H, W = x.size() x = x.view(N, C, H // self.bs, self.bs, W // self.bs, self.bs) # (N, C, H//bs, bs, W//bs, bs) x = x.permute(0, 3, 5, 1, 2, 4).contiguous() # (N, bs, bs, C, H//bs, W//bs) x = x.view(N, C * (self.bs ** 2), H // self.bs, W // self.bs) # (N, C*bs^2, H//bs, W//bs) return x @torch.jit.script class SpaceToDepthJit(object): def __call__(self, x: torch.Tensor): # assuming hard-coded that block_size==4 for acceleration N, C, H, W = x.size() x = x.view(N, C, H // 4, 4, W // 4, 4) # (N, C, H//bs, bs, W//bs, bs) x = x.permute(0, 3, 5, 1, 2, 4).contiguous() # (N, bs, bs, C, H//bs, W//bs) x = x.view(N, C * 16, H // 4, W // 4) # (N, C*bs^2, H//bs, W//bs) return x class SpaceToDepthModule(nn.Module): def __init__(self, remove_model_jit=False): super().__init__() if not remove_model_jit: self.op = SpaceToDepthJit() else: self.op = SpaceToDepth() def forward(self, x): return self.op(x) class DepthToSpace(nn.Module): def __init__(self, block_size): super().__init__() self.bs = block_size def forward(self, x): N, C, H, W = x.size() x = x.view(N, self.bs, self.bs, C // (self.bs ** 2), H, W) # (N, bs, bs, C//bs^2, H, W) x = x.permute(0, 3, 4, 1, 5, 2).contiguous() # (N, C//bs^2, H, bs, W, bs) x = x.view(N, C // (self.bs ** 2), H * self.bs, W * self.bs) # (N, C//bs^2, H * bs, W * bs) return x
[ { "point_num": 1, "id": "every_class_has_docstring", "question": "Does every class 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": true },...
3
python_developer_tools/cv/bases/input_conv/space_to_depth.py
carlsummer/python_developer_tools
# -*- coding: utf-8 -*- import click from jira import JIRA, JIRAError from jirainfo.helpers import printJiraErrorAndExit, printErrorMsg class JiraHelper(object): def __init__(self, host, user="", password=""): self.host = host self.user = user self.password = password try: if user != "" and password != "": self.jira = JIRA(host, basic_auth=(user, password)) else: self.jira = JIRA(host) except JIRAError as e: printErrorMsg('Error connecting to %s. Check if username and password are correct.' % (self.host)) printJiraErrorAndExit(e) def getSummary(self, issue): """ Gets the summary for the given ticket. """ issueData = self.jira.issue(issue) return issueData.fields.summary def getIssues(self, issues): """ Gets the issues from Jira with the given issue numbers. """ result = [] for issue in issues: result.append(self.jira.issue(issue)) return result
[ { "point_num": 1, "id": "has_multiple_inheritance", "question": "Does any class in this file use multiple inheritance?", "answer": false }, { "point_num": 2, "id": "every_function_under_20_lines", "question": "Is every function in this file shorter than 20 lines?", "answer": true...
3
jirainfo/jirahelper.py
hypebeast/jira-info
from os import path from blazeutils import prependsitedir from blazeweb.application import WSGIApp from blazeweb.middleware import full_wsgi_stack from minimal2.config import settings as settingsmod from blazeweb.scripting import application_entry # make sure our base module gets put on the path try: import minimal2 # noqa except ImportError: prependsitedir(path.dirname(settingsmod.basedir), 'apps') def make_wsgi(profile='Default', use_session=True): app = WSGIApp(settingsmod, profile) if not use_session: app.settings.beaker.enabled = False return full_wsgi_stack(app) def script_entry(): application_entry(make_wsgi) if __name__ == '__main__': script_entry()
[ { "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
tests/apps/minimal2/application.py
blazelibs/blazeweb
from graphql.schema import GraphQlFuncDescriptor class GraphQlRootMutationObject(object): """The root mutation object for GraphQL. This is the object whose fields we "query" at the root level of a GraphQL mutation operation. """ # The singleton instance of GraphQlRootMutationObject, or None if we have # not created this yet. _instance = None def __init__(self): """Provate constructor.""" pass @staticmethod def instance(): """Return the singleton instance of GraphQlRootMutationObject.""" if GraphQlRootMutationObject._instance is None: GraphQlRootMutationObject._instance = GraphQlRootMutationObject() return GraphQlRootMutationObject._instance def execute_mutation(self, module_name, class_name, func_name, **kwargs): """Execute a mutation and return its value. basestring module_name - The name of the Python module containing the method or function that executes the mutation basestring class_name - The name of the class containing the method that executes the mutation, or None if it is not implemented using a static method. basestring func_name - The name of the method or function that executes the mutation. dict<basestring, mixed> **kwargs - The keyword arguments to pass to the function. """ return GraphQlFuncDescriptor( module_name, class_name, func_name).load_func()(**kwargs)
[ { "point_num": 1, "id": "all_params_annotated", "question": "Does every function parameter in this file have a type annotation (excluding self/cls)?", "answer": false }, { "point_num": 2, "id": "every_function_has_docstring", "question": "Does every function in this file have a docst...
3
src/graphql/executor/root_mutation_object.py
btrekkie/graphql
import builtins from functools import lru_cache from types import ModuleType, FunctionType, BuiltinFunctionType from typing import Iterable import torch from .funcs import * from .funcs import __all__ as _funcs_all from .funcs.base import get_func_from_torch from .size import * from .size import __all__ as _size_all from .tensor import * from .tensor import __all__ as _tensor_all from ..config.meta import __VERSION__ __all__ = [ *_funcs_all, *_size_all, *_tensor_all, ] _basic_types = ( builtins.bool, builtins.bytearray, builtins.bytes, builtins.complex, builtins.dict, builtins.float, builtins.frozenset, builtins.int, builtins.list, builtins.range, builtins.set, builtins.slice, builtins.str, builtins.tuple, ) _torch_all = set(torch.__all__) class _Module(ModuleType): def __init__(self, module): ModuleType.__init__(self, module.__name__) for name in filter(lambda x: x.startswith('__') and x.endswith('__'), dir(module)): setattr(self, name, getattr(module, name)) self.__origin__ = module self.__torch_version__ = torch.__version__ self.__version__ = __VERSION__ @lru_cache() def __getattr__(self, name): if (name in self.__all__) or \ (hasattr(self.__origin__, name) and isinstance(getattr(self.__origin__, name), ModuleType)): return getattr(self.__origin__, name) else: item = getattr(torch, name) if isinstance(item, (FunctionType, BuiltinFunctionType)) and not name.startswith('_'): return get_func_from_torch(name) elif (isinstance(item, torch.dtype)) or \ isinstance(item, _basic_types) and name in _torch_all: return item else: raise AttributeError(f'Attribute {repr(name)} not found in {repr(__name__)}.') def __dir__(self) -> Iterable[str]: return self.__all__ import sys sys.modules[__name__] = _Module(sys.modules[__name__])
[ { "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
treetensor/torch/__init__.py
opendilab/DI-treetensor
import os import shutil import tempfile from unittest import TestCase, mock from collectors import brew DEPS = b''' a: b: c c: d d: f: g: ''' PACKAGE_INFO = b''' ffmpeg: stable 3.4.2 (bottled), HEAD Play, record, convert, and stream audio and video https://ffmpeg.org/ /usr/local/Cellar/ffmpeg/3.4.2 (248 files, 51.1MB) * Built from source on 2018-03-06 at 18:35:40 with: --with-x265 --with-fdk-aac From: https://github.com/Homebrew/homebrew-core/blob/master/Formula/ffmpeg.rb ==> Dependencies Build: nasm, pkg-config, texi2html Recommended: lame, x264, xvid Optional: chromaprint, fdk-aac ==> Options --with-chromaprint Enable the Chromaprint audio fingerprinting library --with-fdk-aac''' class TestProject(TestCase): @mock.patch('subprocess.check_output') def test_installed_packages(self, mock_check_output): mock_check_output.return_value = DEPS packages = [package for package in brew._installed_packages()] self.assertEquals(packages, ['a', 'b', 'f', 'g']) @mock.patch('subprocess.check_output') def test_get_install_options(self, mock_check_output): mock_check_output.return_value = PACKAGE_INFO self.assertEquals(brew._get_install_options('ffmpeg'), ['--with-x265', '--with-fdk-aac'])
[ { "point_num": 1, "id": "has_multiple_inheritance", "question": "Does any class in this file use multiple inheritance?", "answer": false }, { "point_num": 2, "id": "every_function_has_docstring", "question": "Does every function in this file have a docstring?", "answer": false ...
3
tests/collectors/brew_test.py
ecleya/autodot
import info class subinfo(info.infoclass): def setDependencies(self): self.runtimeDependencies["virtual/base"] = None self.runtimeDependencies["libs/qt5/qtbase"] = None self.runtimeDependencies["libs/openssl"] = None self.runtimeDependencies["libs/cyrus-sasl"] = None def setTargets(self): self.description = "Qt Cryptographic Architecture (QCA)" self.svnTargets["master"] = "https://anongit.kde.org/qca.git" # latest stable version self.defaultTarget = "2.3.3" self.targets[self.defaultTarget] = f"https://download.kde.org/stable/qca/{self.defaultTarget}/qca-{self.defaultTarget}.tar.xz" self.targetDigestUrls[self.defaultTarget] = f"https://download.kde.org/stable/qca/{self.defaultTarget}/qca-{self.defaultTarget}.tar.xz.sha256" self.targetInstSrc[self.defaultTarget] = f"qca-{self.defaultTarget}" self.patchToApply[self.defaultTarget] = [("msvc.diff", 1)] self.patchLevel[self.defaultTarget] = 1 from Package.CMakePackageBase import * class Package(CMakePackageBase): def __init__(self, **args): CMakePackageBase.__init__(self) # the cmake config is not relocatable self.subinfo.options.package.disableBinaryCache = True # tests fail to build with missing openssl header self.subinfo.options.configure.args = "-DBUILD_TESTS=OFF "
[ { "point_num": 1, "id": "has_multiple_inheritance", "question": "Does any class in this file use multiple inheritance?", "answer": false }, { "point_num": 2, "id": "every_function_has_docstring", "question": "Does every function in this file have a docstring?", "answer": false ...
3
kdesupport/qca/qca.py
KDE/craft-blueprints-kde
import base64 import json import falcon import numpy as np from io import BytesIO from PIL import Image, ImageOps def convert_image(image): img = Image.open(image).convert('L') inverted_img = ImageOps.invert(img) data = np.asarray(inverted_img, dtype='int32') rescaled_data = (data / 255).reshape(1, 28, 28, 1) return rescaled_data class GetResource(object): def __init__(self, model): self.model = model def on_get(self, req, resp): resp.status = falcon.HTTP_200 resp.body = 'Hello World!' def on_post(self, req, resp): """ (echo -n '{"image": "'; four_test.png; echo '"}') | curl -H "Content-Type: application/json" -d @- http://0.0.0.0:8080/predict """ image = json.loads(req.stream.read()) decoded_image = base64.b64decode(image.get('image')) data = convert_image(BytesIO(decoded_image)) predicted_data = self.model.predict_classes(data)[0] output = {'prediction': str(predicted_data)} resp.status = falcon.HTTP_200 resp.body = json.dumps(output, ensure_ascii=False)
[ { "point_num": 1, "id": "no_function_exceeds_5_params", "question": "Does every function in this file take 5 or fewer parameters (excluding self/cls)?", "answer": true }, { "point_num": 2, "id": "every_function_under_20_lines", "question": "Is every function in this file shorter than...
3
src/prediction_app/predict.py
datitran/falcon-prediction-app
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2012 Nebula, Inc. # # 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. from django.core.urlresolvers import reverse from django.utils.translation import ugettext_lazy as _ from horizon import exceptions from horizon import tabs from openstack_dashboard.api import cinder class OverviewTab(tabs.Tab): name = _("Overview") slug = "overview" template_name = ("project/images_and_snapshots/snapshots/" "_detail_overview.html") def get_context_data(self, request): snapshot_id = self.tab_group.kwargs['snapshot_id'] try: snapshot = cinder.volume_snapshot_get(request, snapshot_id) volume = cinder.volume_get(request, snapshot.volume_id) volume.display_name = None except: redirect = reverse('horizon:project:images_and_snapshots:index') exceptions.handle(self.request, _('Unable to retrieve snapshot details.'), redirect=redirect) return {'snapshot': snapshot, 'volume': volume} class SnapshotDetailTabs(tabs.TabGroup): slug = "snapshot_details" tabs = (OverviewTab,)
[ { "point_num": 1, "id": "every_class_has_docstring", "question": "Does every class 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
openstack_dashboard/dashboards/project/images_and_snapshots/volume_snapshots/tabs.py
dreamhost/horizon
#!/usr/bin/env python import torch import torch.nn as nn from colossalai.nn import CheckpointModule from .utils.dummy_data_generator import DummyDataGenerator from .registry import non_distributed_component_funcs class NetWithRepeatedlyComputedLayers(CheckpointModule): """ This model is to test with layers which go through forward pass multiple times. In this model, the fc1 and fc2 call forward twice """ def __init__(self, checkpoint=False) -> None: super().__init__(checkpoint=checkpoint) self.fc1 = nn.Linear(5, 5) self.fc2 = nn.Linear(5, 5) self.fc3 = nn.Linear(5, 2) self.layers = [self.fc1, self.fc2, self.fc1, self.fc2, self.fc3] def forward(self, x): for layer in self.layers: x = layer(x) return x class DummyDataLoader(DummyDataGenerator): def generate(self): data = torch.rand(16, 5) label = torch.randint(low=0, high=2, size=(16,)) return data, label @non_distributed_component_funcs.register(name='repeated_computed_layers') def get_training_components(): def model_builder(checkpoint=True): return NetWithRepeatedlyComputedLayers(checkpoint) trainloader = DummyDataLoader() testloader = DummyDataLoader() criterion = torch.nn.CrossEntropyLoss() return model_builder, trainloader, testloader, torch.optim.Adam, criterion
[ { "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_class_has_docstring", "question": "Does every class in this file have a docstring?", "answer": f...
3
tests/components_to_test/repeated_computed_layer.py
RichardoLuo/ColossalAI
from algorithms.graphs import prepare_undirect_graph, prepare_direct_graph from algorithms.graphs.dfs import dfs_iterative class TestDFSIterative: def test_direct_graph(self): edges = [(0, 1), (0, 2), (1, 2), (2, 0), (2, 3), (3, 3)] graph = prepare_direct_graph(edges) assert [2, 3, 0, 1] == dfs_iterative(graph, 2), "Order of vertex visiting is wrong" def test_direct_graph_3(self): edges = [(1, 0), (0, 2), (2, 1), (0, 3), (1, 4)] graph = prepare_direct_graph(edges) assert [0, 3, 2, 1, 4] == dfs_iterative(graph, 0), "Order of vertex visiting is wrong" def test_undirect_graph(self): edges = [(0, 1), (0, 2), (1, 2), (2, 0), (2, 3), (3, 3)] graph = prepare_undirect_graph(edges) assert [2, 3, 1, 0] == dfs_iterative(graph, 2), "Order of vertex visiting is wrong" def test_direct_graph_2(self): edges = [(1, 2), (2, 5), (2, 4), (4, 6), (4, 5), (5, 3), (3, 1)] graph = prepare_direct_graph(edges) assert [1, 2, 5, 3, 4, 6] == dfs_iterative(graph, 1), "Order of vertex visiting is wrong" def test_undirect_graph_2(self): edges = [(1, 2), (2, 5), (2, 4), (4, 6), (4, 5), (5, 3), (3, 1)] graph = prepare_undirect_graph(edges) assert [1, 3, 5, 4, 6, 2] == dfs_iterative(graph, 1), "Order of vertex visiting is wrong" def test_direct_graph_4(self): edges = [(1, 2), (2, 3), (1, 4), (4, 5), (1, 6), (6, 7), (1, 8), (7, 9)] graph = prepare_undirect_graph(edges) assert [1, 8, 6, 7, 9, 4, 5, 2, 3] == dfs_iterative(graph, 1), "Order of vertex visiting is wrong"
[ { "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
tests/graph/test_dfs.py
mchao409/python-algorithms
from chainerui.models.log import Log def get_test_json(): return [ { "loss": 100, "epoch": 1, }, { "loss": 90, "epoch": 2, } ] def test_log_serialize_numbers(): json_data = get_test_json() logs = [Log(data) for data in json_data] serialized_data = [log.serialize for log in logs] assert serialized_data[0]['logDict']['epoch'] == 1 assert serialized_data[1]['logDict']['epoch'] == 2 def test_log_serialize_arbitrary_data(): json_data = get_test_json() json_data.insert( 0, { "loss": 110, "epoch": 0, "model_files": ["Model", "model.py"] } ) logs = [Log(data) for data in json_data] serialized_data = [log.serialize for log in logs] assert serialized_data[0]['logDict']['epoch'] == 0 assert serialized_data[0]['logDict']['model_files'] is None assert serialized_data[1]['logDict']['epoch'] == 1 assert serialized_data[2]['logDict']['epoch'] == 2 def test_log_serialize_nan_and_inf(): json_data = get_test_json() json_data.insert( 0, { "loss": float('nan'), "epoch": float('inf'), "iteration": 0, } ) logs = [Log(data) for data in json_data] serialized_data = [log.serialize for log in logs] assert serialized_data[0]['logDict']['iteration'] == 0 assert serialized_data[0]['logDict']['epoch'] is None assert serialized_data[0]['logDict']['loss'] is None assert serialized_data[1]['logDict']['epoch'] == 1 assert serialized_data[2]['logDict']['epoch'] == 2
[ { "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
tests/models_tests/test_log.py
chainer/chainerui
"""test utilities (part of web.py) """ import unittest import sys, os import web TestCase = unittest.TestCase TestSuite = unittest.TestSuite def load_modules(names): return [__import__(name, None, None, "x") for name in names] def module_suite(module, classnames=None): """Makes a suite from a module.""" if classnames: return unittest.TestLoader().loadTestsFromNames(classnames, module) elif hasattr(module, 'suite'): return module.suite() else: return unittest.TestLoader().loadTestsFromModule(module) def doctest_suite(module_names): """Makes a test suite from doctests.""" import doctest suite = TestSuite() for mod in load_modules(module_names): suite.addTest(doctest.DocTestSuite(mod)) return suite def suite(module_names): """Creates a suite from multiple modules.""" suite = TestSuite() for mod in load_modules(module_names): suite.addTest(module_suite(mod)) return suite def runTests(suite): runner = unittest.TextTestRunner() return runner.run(suite) def main(suite=None): if not suite: main_module = __import__('__main__') # allow command line switches args = [a for a in sys.argv[1:] if not a.startswith('-')] suite = module_suite(main_module, args or None) result = runTests(suite) sys.exit(not result.wasSuccessful())
[ { "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
webpy/src/web/test.py
minixalpha/SourceLearning
#!/usr/bin/env python """ _LoadFromFilesetWorkflow_ MySQL implementation of Subscription.LoadFromFilesetWorkflow """ __all__ = [] from WMCore.Database.DBFormatter import DBFormatter class LoadFromFilesetWorkflow(DBFormatter): sql = """SELECT wmbs_subscription.id, fileset, workflow, split_algo, wmbs_sub_types.name, last_update FROM wmbs_subscription INNER JOIN wmbs_sub_types ON wmbs_subscription.subtype = wmbs_sub_types.id WHERE fileset = :fileset AND workflow = :workflow""" def formatDict(self, result): """ _formatDict_ Cast the id, fileset, workflow and last_update columns to integers since formatDict() turns everything into strings. """ formattedResult = DBFormatter.formatDict(self, result)[0] formattedResult["id"] = int(formattedResult["id"]) formattedResult["fileset"] = int(formattedResult["fileset"]) formattedResult["workflow"] = int(formattedResult["workflow"]) formattedResult["last_update"] = int(formattedResult["last_update"]) formattedResult["type"] = formattedResult["name"] del formattedResult["name"] return formattedResult def execute(self, fileset = None, workflow = None, conn = None, transaction = False): result = self.dbi.processData(self.sql, {"fileset": fileset, "workflow": workflow}, conn = conn, transaction = transaction) return self.formatDict(result)
[ { "point_num": 1, "id": "all_params_annotated", "question": "Does every function parameter in this file have a type annotation (excluding self/cls)?", "answer": false }, { "point_num": 2, "id": "every_function_has_docstring", "question": "Does every function in this file have a docst...
3
src/python/WMCore/WMBS/MySQL/Subscriptions/LoadFromFilesetWorkflow.py
khurtado/WMCore
def concat_multiples(num, multiples): return int("".join([str(num*multiple) for multiple in range(1,multiples+1)])) def is_pandigital(num): return sorted([int(digit) for digit in str(num)]) == list(range(1,10)) def solve_p038(): # retrieve only 9 digit concatinations of multiples where n = (1,2,..n) n6 = [concat_multiples(num, 6) for num in [3]] n5 = [concat_multiples(num, 5) for num in range(5,10)] n4 = [concat_multiples(num, 4) for num in range(25,33)] n3 = [concat_multiples(num, 3) for num in range(100,333)] n2 = [concat_multiples(num, 2) for num in range(5000,9999)] all_concats = set(n2 + n3 + n4 + n5 + n6) return max([num for num in all_concats if is_pandigital(num)]) if __name__ == '__main__': print((solve_p038()))
[ { "point_num": 1, "id": "has_nested_function_def", "question": "Does this file contain any function defined inside another function?", "answer": false }, { "point_num": 2, "id": "no_function_exceeds_5_params", "question": "Does every function in this file take 5 or fewer parameters (...
3
p038.py
piohhmy/euler
from http import HTTPStatus from typing import List from apifairy import body, other_responses, response from flask import Blueprint, jsonify from flask import request from src.config import DefaultConfig from src.dtos.user import UserDto from src.requests.user import CreateUserRequestSchema, CreateUserRequest, CreateManyUsersRequestSchema, \ CreateManyUsersRequest from src.responses.user import UserResponseSchema from src.services import queue_client from src.services.pascal_to_snake_serializer import JSONSerializer as ToSnakeJson from src.services.snake_to_pascal_serializer import JSONSerializer as ToPascalJson users_api = Blueprint('users', __name__) @users_api.route('users', methods=['POST']) @other_responses({ 200: 'User Created', 400: 'Request Body is Invalid' }) @body(CreateUserRequestSchema()) def post(user_request: CreateUserRequest): """Create a User.""" if request.method == 'POST': user_snake_case = ToSnakeJson.deserialize(UserDto, ToSnakeJson.serialize(user_request)) add_msg = queue_client.add_create_user_job(user_snake_case) return jsonify(add_msg), 200 @users_api.route('users/many', methods=['POST']) @other_responses({ 200: 'Users Created', 400: 'Request Body is Invalid' }) @body(CreateManyUsersRequestSchema()) def post_many(user_request: CreateManyUsersRequest): """Create a User.""" if request.method == 'POST': users_snake_case = ToSnakeJson.deserialize(List[UserDto], ToSnakeJson.serialize(user_request.Users)) users_added = [] for user in users_snake_case: add_msg = queue_client.add_create_user_job(user) users_added.append(add_msg) return jsonify(users_added), 200 @users_api.route('users/<int:id>', methods=['GET']) @response(UserResponseSchema, HTTPStatus.OK.value, "Get Users") def get_all_users(id: int): if request.method == 'GET': user = UserDto(user_name=DefaultConfig.DEFAULT_USERNAME) return ToPascalJson.serialize(user), 200
[ { "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
src/routes/users.py
tombrereton/flask-api-starter-kit
import random from string import Template import tinydb from flask import Flask, redirect, url_for, abort app = Flask(__name__) db = tinydb.TinyDB('./db.json') HTML = """<!DOCTYPE html> <html> <head> <title>Dulux Swatch</title> <link rel="StyleSheet" href="/static/main.css" type="text/css"> </head> <body style="background-color: #${rgb}"> <div> ${name} <br/> (id: <a href="https://www.dulux.co.uk/en/products/colour-tester#?selectedColor=${colorId}">${colorId}</a>) </div> </body> </html> """ @app.route('/id/<colour_id>') def get_colour_by_id(colour_id): obj = db.get(tinydb.Query().colorId == colour_id) if not obj: abort(404) return Template(HTML).substitute(obj) @app.route('/name/<colur_name>') def get_colour_by_name(colur_name): obj = db.get(tinydb.Query().uriFriendlyName == colur_name) if not obj: abort(404) return Template(HTML).substitute(obj) @app.route('/') @app.route('/random') def get_random_colour(): return redirect(url_for('get_colour_by_id', colour_id=random.choice(db.all())['colorId']))
[ { "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
duluxswatch/app.py
leohemsted/duluxswatch
# coding=utf-8 from jotdx.parser.base import BaseParser from jotdx.helper import get_datetime, get_volume, get_price from collections import OrderedDict import struct import six class GetMinuteTimeData(BaseParser): def setParams(self, market, code): if type(code) is six.text_type: code = code.encode("utf-8") pkg = bytearray.fromhex(u'0c 1b 08 00 01 01 0e 00 0e 00 1d 05') pkg.extend(struct.pack("<H6sI", market, code, 0)) self.send_pkg = pkg """ b1cb74000c1b080001b61d05be03be03f0000000a208ce038d2c028302972f4124b11a00219821011183180014891c0009be0b4207b11000429c2041.... In [26]: get_price(b, 0) Out[26]: (0, 1) In [27]: get_price(b, 1) Out[27]: (0, 2) In [28]: get_price(b, 2) Out[28]: (546, 4) In [29]: get_price(b, 4) Out[29]: (-206, 6) In [30]: get_price(b, 6) Out[30]: (2829, 8) In [31]: get_price(b, 8) Out[31]: (2, 9) In [32]: get_price(b, 9) Out[32]: (131, 11) In [36]: get_price(b, 11) Out[36]: (3031, 13) In [37]: get_price(b, 13) Out[37]: (-1, 14) In [38]: get_price(b, 14) Out[38]: (36, 15) In [39]: get_price(b, 15) Out[39]: (1713, 17) In [40]: get_price(b, 17) Out[40]: (0, 18) """ def parseResponse(self, body_buf): pos = 0 (num, ) = struct.unpack("<H", body_buf[:2]) last_price = 0 pos += 4 prices = [] for i in range(num): price_raw, pos = get_price(body_buf, pos) reversed1, pos = get_price(body_buf, pos) vol, pos = get_price(body_buf, pos) last_price = last_price + price_raw price = OrderedDict( [ ("price", float(last_price)/100), ("vol", vol) ] ) prices.append(price) return prices
[ { "point_num": 1, "id": "every_function_has_docstring", "question": "Does every function in this file have a docstring?", "answer": false }, { "point_num": 2, "id": "all_params_annotated", "question": "Does every function parameter in this file have a type annotation (excluding self/...
3
jotdx/parser/get_minute_time_data.py
jojoquant/jotdx
from copy import deepcopy class Movel: """ Super class para móveis interativos """ def __init__(self, name, message): self.name = name self.message = message self.itens = [] self.nomes = [] def olhar(self): """ Método que retorna uma breve descrição do item/móvel """ print(self.message) def pegar_todos(self): """ Método que retorna todos os itens disponíveis em um móvel para o jogador """ if len(self.itens): all_itens = [i for i in self.itens] self.itens = [] self.nomes = [] print('Você pegou todos os itens') return all_itens else: return [] def pegar(self, item): """ Método que retorna ao jogador o item requerido """ # try: if item in self.nomes: for i in range(len(self.nomes)): if item == self.nomes[i]: r = self.itens.pop(i) self.nomes.pop(i) print(f'Você pegou o item {item}!') return r else: print("%s é um item inválido" % item) # except Exception as e: # ## In case the player inputs nonsense # print("%s é um item inválido" % item) # return None def store_item(self, item): self.itens.append(item) self.nomes.append(item.name)
[ { "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
superclasses/movel.py
augusnunes/titanic-escape
import pytest from django.urls import resolve, reverse from notificationsservice.users.models import User pytestmark = pytest.mark.django_db def test_user_detail(user: User): assert ( reverse("api:user-detail", kwargs={"username": user.username}) == f"/api/users/{user.username}/" ) assert resolve(f"/api/users/{user.username}/").view_name == "api:user-detail" def test_user_list(): assert reverse("api:user-list") == "/api/users/" assert resolve("/api/users/").view_name == "api:user-list" def test_user_me(): assert reverse("api:user-me") == "/api/users/me/" assert resolve("/api/users/me/").view_name == "api:user-me"
[ { "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
notificationsservice/users/tests/test_drf_urls.py
saippuakauppias/test-task-django
# coding: utf-8 """ Kubernetes No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) OpenAPI spec version: v1.8.2 Generated by: https://github.com/swagger-api/swagger-codegen.git """ from __future__ import absolute_import import os import sys import unittest import kubernetes.client from kubernetes.client.rest import ApiException from kubernetes.client.models.v2beta1_horizontal_pod_autoscaler import V2beta1HorizontalPodAutoscaler class TestV2beta1HorizontalPodAutoscaler(unittest.TestCase): """ V2beta1HorizontalPodAutoscaler unit test stubs """ def setUp(self): pass def tearDown(self): pass def testV2beta1HorizontalPodAutoscaler(self): """ Test V2beta1HorizontalPodAutoscaler """ # FIXME: construct object with mandatory attributes with example values #model = kubernetes.client.models.v2beta1_horizontal_pod_autoscaler.V2beta1HorizontalPodAutoscaler() pass if __name__ == '__main__': unittest.main()
[ { "point_num": 1, "id": "more_functions_than_classes", "question": "Does this file define more functions than classes?", "answer": true }, { "point_num": 2, "id": "has_multiple_inheritance", "question": "Does any class in this file use multiple inheritance?", "answer": false },...
3
kubernetes/test/test_v2beta1_horizontal_pod_autoscaler.py
scele/kubernetes-client-python
from ..messenger import Messenger from . import pytest def test_send_message_should_fail(): messenger = Messenger() with pytest.raises(Exception) as exception_info: messenger.send("user", "message") assert "implemented" in str(exception_info) def test_mark_writing_on_should_do_nothing(): messenger = Messenger() messenger.mark_writing("user", True) def test_mark_writing_off_should_do_nothing(): messenger = Messenger() messenger.mark_writing("user", False) def test_mark_seen_should_do_nothing(): messenger = Messenger() messenger.mark_seen("user")
[ { "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
chatbotmaker/tests/messenger_test.py
Dominique57/ChatBotMaker
""" Good morning! Here's your coding interview problem for today. This problem was asked by Coursera. Given a 2D board of characters and a word, find if the word exists in the grid. The word can be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once. For example, given the following board: [ ['A','B','C','E'], ['S','F','C','S'], ['A','D','E','E'] ] exists(board, "ABCCED") returns true, exists(board, "SEE") returns true, exists(board, "ABCB") returns false. """ def is_word_present(board, word): if type(board) != list or type(board[0]) != list or type(word) != str: return None isFound = False root_x = 0 root_y = 0 def find_word(x, y, current_word=""): nonlocal isFound new_current_word = current_word + board[x][y] if new_current_word == word: isFound = True else: if new_current_word == word[:len(new_current_word)]: if (x + 1) < len(board): find_word(x + 1, y, new_current_word) if (y + 1) < len(board[0]): find_word(x, y + 1, new_current_word) if (x - 1) >= 0: find_word(x - 1, y, new_current_word) if (y - 1) >= 0: find_word(x, y - 1, new_current_word) else: return for _ in range(len(board) * len(board[0])): find_word(root_x, root_y) if isFound: break else: if root_y >= len(board[0]) - 1: root_y = 0 root_x += 1 else: root_y += 1 return isFound
[ { "point_num": 1, "id": "every_function_has_docstring", "question": "Does every function in this file have a docstring?", "answer": false }, { "point_num": 2, "id": "all_params_annotated", "question": "Does every function parameter in this file have a type annotation (excluding self/...
3
src/daily-coding-problem/easy/word-board/word_board.py
nwthomas/code-challenges
import PIL import PIL.Image from functional import compose import numpy as np import argparse lmap = compose(list, map) def str2bool(v): if v.lower() in ('yes', 'true', 't', 'y', '1'): return True elif v.lower() in ('no', 'false', 'f', 'n', '0'): return False else: raise argparse.ArgumentTypeError('Boolean value expected.') def split(a, n): """ Splits a list into n parts of approx. equal length from https://stackoverflow.com/questions/2130016/splitting-a-list-into-n-parts-of-approximately-equal-length """ k, m = divmod(len(a), n) return (a[i * k + min(i, m):(i + 1) * k + min(i + 1, m)] for i in range(n)) def str2FloatOrNone(v): if v.lower() == 'none': return None try: return float(v) except ValueError: raise argparse.ArgumentTypeError('Float or none value expected.') def torch_image_to_PIL(img): img = img.cpu().numpy() if len(img.shape) == 4: img = img[0, ...] elif len(img.shape) == 3: pass else: assert False img = 255 * np.transpose(img, (1, 2, 0)) img = np.clip(np.round(img), 0, 255).astype(np.uint8) return PIL.Image.fromarray(img) class Logger(object): def __init__(self, filename, stdout): self.terminal = stdout if filename is not None: self.log = open(filename, "a") else: self.log = None def write(self, message): self.terminal.write(message) if self.log is not None: self.log.write(message) def flush(self): self.terminal.flush() if self.log is not None: self.log.flush() def get_interpolation(i): return getattr(PIL.Image, i.upper())
[ { "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
util.py
eth-sri/transformation-smoothing
from os import listdir import os.path as osp class AudiofileProcessor(object): SECONDS = 60 POMADORO_LENGTH_IN_SECONDS = 25 * SECONDS def __init__(self, directory, filter_by_ext, length_calculator): self.directory = directory self.filter_by_ext = filter_by_ext self.length_calculator = length_calculator def _get_files(self): files = [] if osp.isdir(self.directory): for f in listdir(self.directory): if osp.isfile(osp.join(self.directory, f)) and self.filter_by_ext(f): files.append(osp.join(self.directory, f)) return files def pomodoro(self): files = self._get_files() length = 0 for f in files: length += self.length_calculator(f) l = round(length) print("Pomodoros listened: #{}. Time remained: {}:{}" .format(l // self.POMADORO_LENGTH_IN_SECONDS, (l % self.POMADORO_LENGTH_IN_SECONDS) // self.SECONDS, (l % self.POMADORO_LENGTH_IN_SECONDS) % self.SECONDS))
[ { "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
audiofile_processor.py
ChameleonTartu/audio-files-to-pomodoro-counts
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you 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. from aliyunsdkcore.request import RpcRequest from aliyunsdkhbr.endpoint import endpoint_data class RenewClientTokenRequest(RpcRequest): def __init__(self): RpcRequest.__init__(self, 'hbr', '2017-09-08', 'RenewClientToken','hbr') self.set_protocol_type('https') self.set_method('POST') if hasattr(self, "endpoint_map"): setattr(self, "endpoint_map", endpoint_data.getEndpointMap()) if hasattr(self, "endpoint_regional"): setattr(self, "endpoint_regional", endpoint_data.getEndpointRegional()) def get_ClientId(self): return self.get_query_params().get('ClientId') def set_ClientId(self,ClientId): self.add_query_param('ClientId',ClientId) def get_VaultId(self): return self.get_query_params().get('VaultId') def set_VaultId(self,VaultId): self.add_query_param('VaultId',VaultId) def get_Token(self): return self.get_query_params().get('Token') def set_Token(self,Token): self.add_query_param('Token',Token) def get_ExpireInSeconds(self): return self.get_query_params().get('ExpireInSeconds') def set_ExpireInSeconds(self,ExpireInSeconds): self.add_query_param('ExpireInSeconds',ExpireInSeconds)
[ { "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
aliyun-python-sdk-hbr/aliyunsdkhbr/request/v20170908/RenewClientTokenRequest.py
yndu13/aliyun-openapi-python-sdk
from airflow.hooks.base_hook import BaseHook class AzureBlobStorageCredentials(BaseHook): def __init__(self, conn_id="azure_blob_storage_default"): self.conn_id = conn_id def get_credentials(self): connection_object = self.get_connection(self.conn_id) extras = connection_object.extra_dejson credentials = dict() if connection_object.login: credentials["account_name"] = connection_object.login if connection_object.password: credentials["account_key"] = connection_object.password credentials.update(extras) return credentials
[ { "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
modules/dbnd-airflow/src/dbnd_airflow_contrib/credentials_helper_azure.py
ipattarapong/dbnd
from builtins import range from builtins import object import os import json from collections import OrderedDict import scipy.sparse as sp from .inferencer import IForest, LeafComputer, Blender, IForestBlender class Inferencer(object): """ Loads up a model for inferencing """ def __init__(self, dname, gamma=30, blend=0.8, leaf_probs=False): with open(os.path.join(dname, 'settings'), 'rt') as f: self.__dict__.update(json.load(f)) self.gamma = gamma self.blend = blend self.leaf_probs = leaf_probs forest = IForest(dname, self.n_trees, self.n_labels) if self.leaf_classifiers: lc = LeafComputer(dname) predictor = Blender(forest, lc) else: predictor = IForestBlender(forest) self.predictor = predictor def predict(self, X, fmt='sparse'): assert fmt in ('sparse', 'dict') s = [] num = X.shape[0] if isinstance(X, sp.csr_matrix) else len(X) for i in range(num): Xi = X[i] mean = self.predictor.predict(Xi.data, Xi.indices, self.blend, self.gamma, self.leaf_probs) if fmt == 'sparse': s.append(mean) else: od = OrderedDict() for idx in reversed(mean.data.argsort()): od[mean.indices[idx]] = mean.data[idx] s.append(od) if fmt == 'sparse': return sp.vstack(s) return s
[ { "point_num": 1, "id": "has_multiple_inheritance", "question": "Does any class in this file use multiple inheritance?", "answer": false }, { "point_num": 2, "id": "no_function_exceeds_5_params", "question": "Does every function in this file take 5 or fewer parameters (excluding self...
3
FastXML/fastxml/fastxml/fastxml.py
anonymouslorem/library_identification_vulnerability_report
import numpy as np from sklearn.base import TransformerMixin def format_runs(runs): # Time invariant parameters X = np.stack([entry['parameters'] for entry in runs]) # Outputs y = np.stack([entry['outputs'] for entry in runs]) # Time varying parameters period = y.shape[1] X = np.repeat(X[:, None, :], period, axis=1) X = np.concatenate( [ X, [entry['timed_parameters'] for entry in runs] ], axis = 2 ) return (X, y) class GlobalScaler(TransformerMixin): def __init__(self, **kwargs): self._mean = None self._std = None def fit(self, X, **kwargs): self._mean = np.mean(X) self._std = np.std(X) if self._std == 0.: self._std = 1. return self def transform(self, X, **kwargs): return (X - self._mean) / self._std def inverse_transform(self, X, **kwargs): return X * self._std + self._mean class SequenceScaler(TransformerMixin): def __init__(self, **kwargs): self._mean = None self._std = None def fit(self, X, **kwargs): self._mean = np.mean(X, axis=(0, 1)) self._std = np.std(X, axis=(0, 1)) self._std[self._std == 0.] = 1. return self def transform(self, X, **kwargs): return (X - self._mean) / self._std def inverse_transform(self, X, **kwargs): return X * self._std + self._mean
[ { "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
src/fastms/preprocessing.py
giovannic/fastms
from django import template from ..rocketchat import get_rc_id, get_rc_url, get_rc_ws_url register = template.Library() @register.inclusion_tag("rocketchat/chat.html", takes_context=True) def chat(context): user = getattr(context.get("request"), "user") return { "rocketchat_url": get_rc_url(), "websocket_url": get_rc_ws_url(), "user": user, "user_id": user and user.is_authenticated and get_rc_id(user), } @register.inclusion_tag("rocketchat/livechat.html", takes_context=True) def livechat(context): return { "rocketchat_url": get_rc_url(), "user": getattr(context.get("request"), "user"), }
[ { "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
leprikon/templatetags/rocketchat.py
leprikon-cz/leprikon
"""Create book model Revision ID: dc9d9a0ac820 Revises: bbb00b216d89 Create Date: 2021-12-23 05:05:26.276613 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = 'dc9d9a0ac820' down_revision = 'bbb00b216d89' branch_labels = None depends_on = None def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.create_table('book', sa.Column('id', sa.Integer(), nullable=False), sa.Column('title', sa.String(), nullable=True), sa.Column('description', sa.String(), nullable=True), sa.Column('time_created', sa.DateTime(timezone=True), server_default=sa.text('now()'), nullable=True), sa.Column('time_updated', sa.DateTime(timezone=True), nullable=True), sa.Column('author_id', sa.Integer(), nullable=True), sa.ForeignKeyConstraint(['author_id'], ['author.id'], ), sa.PrimaryKeyConstraint('id') ) op.create_index(op.f('ix_book_id'), 'book', ['id'], unique=False) # ### end Alembic commands ### def downgrade(): # ### commands auto generated by Alembic - please adjust! ### op.drop_index(op.f('ix_book_id'), table_name='book') op.drop_table('book') # ### end Alembic commands ###
[ { "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
api/app/alembic/versions/dc9d9a0ac820_create_book_model.py
CHSevero/ZipBank-book-api
from gettext import find import torch from ezflow.utils import ( AverageMeter, coords_grid, endpointerror, find_free_port, forward_interpolate, is_port_available, upflow, ) def test_endpointerror(): pred = torch.rand(4, 2, 256, 256) target = torch.rand(4, 2, 256, 256) _ = endpointerror(pred, target) multi_magnitude_epe = endpointerror(pred, target, multi_magnitude=True) assert isinstance(multi_magnitude_epe, dict) target = torch.rand( 4, 3, 256, 256 ) # Ignore valid mask for EPE calculation if target contains it _ = endpointerror(pred, target) def test_forward_interpolate(): flow = torch.rand(2, 256, 256) _ = forward_interpolate(flow) def test_upflow(): flow = torch.rand(2, 2, 256, 256) _ = upflow(flow) def test_coords_grid(): _ = coords_grid(2, 256, 256) def test_AverageMeter(): meter = AverageMeter() meter.update(1) assert meter.avg == 1 meter.reset() assert meter.avg == 0 def test_find_free_port(): assert len(find_free_port()) == 5 def test_is_port_available(): port = find_free_port() assert is_port_available(int(port)) is True
[ { "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_under_20_lines", "question": "Is every function in this file shorter than 20 lines?", "ans...
3
tests/test_utils.py
neu-vig/ezflow
""" Author: Shreck Ye Date: June 16, 2019 Time complexity: O(log(N)) Let's think in the mathematical way. Obviously, the recursion formula represents a linear relationship. By viewing it as a recursion formula of a single vector F_n = (f_n, f_{n + 1})' with a transition matrix M = (0, 1; 1, 1), which is (f_{n + 1}, f_{n + 2})' = (0, 1; 1, 1) (f_n, f_{n + 1})' namely F_{n + 1} = M F_n, we can get the result using matrix exponentiation and reduce the number of recursions. """ import copy F_0 = [[0], [1]] M = [[0, 1], [1, 1]] def zero_matrix(m: int, n: int): rows = [None] * m row = [0] * n for i in range(m): rows[i] = copy.deepcopy(row) return rows def matmul(A, B): # More checks of matrix shapes may be performed m = len(A) n = len(B) l = len(B[0]) C = zero_matrix(m, l) for i in range(m): for j in range(l): sum = 0 A_i = A[i] for k in range(n): sum += A_i[k] * B[k][j] C[i][j] = sum return C def eye(size: int): E = zero_matrix(size, size) for i in range(size): E[i][i] = 1 return E def matrix_power(A, n: int): size = len(A) if n == 0: return eye(size) elif n == 1: return copy.deepcopy(A) else: A_pow_half_n = matrix_power(A, n // 2) A_pow_n = matmul(A_pow_half_n, A_pow_half_n) if n % 2: A_pow_n = matmul(A_pow_n, A) return A_pow_n class Solution: def fib(self, N: int) -> int: return matmul(matrix_power(M, N), F_0)[0][0] # Test cases s = Solution() print(s.fib(0), s.fib(1), s.fib(2), s.fib(3), s.fib(4), s.fib(5))
[ { "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
leetcode/solutions/fibonacci_number/matrix_exponentiation_solution_full_implementation.py
ShreckYe/Python-learning-Chinese
from unittest.mock import patch import os from chapter10 import C10 import pytest TESTDIR = os.path.join(os.path.dirname(__file__), 'tests') def pytest_configure(): pytest.SAMPLE = os.path.join(TESTDIR, '1.c10') pytest.EVENTS = os.path.join(TESTDIR, 'event.c10') pytest.ETHERNET = os.path.join(TESTDIR, 'ethernet.c10') pytest.ERR = os.path.join(TESTDIR, 'err.c10') pytest.BAD = os.path.join(TESTDIR, 'bad.c10') pytest.PCAP = os.path.join(TESTDIR, 'test.pcap') pytest.TMATS = os.path.join(TESTDIR, 'test.tmt') class MockC10(C10): def __init__(self, packets): self.packets = packets def __iter__(self): return iter(self.packets) @pytest.fixture def c10(): return MockC10 @pytest.fixture(scope='session') def fake_progress(): with patch('c10_tools.common.FileProgress'): yield
[ { "point_num": 1, "id": "all_function_names_snake_case", "question": "Are all function names in this file written in snake_case?", "answer": true }, { "point_num": 2, "id": "has_multiple_inheritance", "question": "Does any class in this file use multiple inheritance?", "answer": ...
3
conftest.py
atac-bham/c10-tools
# coding=utf-8 from sqlalchemy import Column, String from .base import Base class NsfHerdFederalAgency(Base): """ map to a table name in db """ __tablename__ = "nsf_herd_federal_agencies" """ create columns """ agency_key = Column(String(3), primary_key = True) agency_name = Column(String(64), nullable = False) agency_short_name = Column(String(32), nullable = False) agency_type = Column(String(16), nullable = False) def __init__(self, agency_key, agency_name, agency_short_name, agency_type): """ method for instantiating object """ self.agency_key = agency_key self.agency_name = agency_name self.agency_short_name = agency_short_name self.agency_type = agency_type def __repr__(self): """ produces human-readable object call """ return ( f'{self.__class__.__name__}(' f'agency_key={self.agency_key!r}, ' f'agency_name={self.agency_name!r}, ' f'agency_short_name={self.agency_short_name!r}, ' f'agency_type={self.agency_type!r})' )
[ { "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
database/nsf_herd_federal_agencies.py
jasonpcasey/public_comparative_data
import logging import os import time import pytest from tests.test_helpers.docker_helpers import docker_compose_runner # noqa: F401 # Enable debug logging. logging.getLogger().setLevel(logging.DEBUG) os.putenv("DATAHUB_DEBUG", "1") @pytest.fixture def mock_time(monkeypatch): def fake_time(): return 1615443388.0975091 monkeypatch.setattr(time, "time", fake_time) yield def pytest_addoption(parser): parser.addoption( "--update-golden-files", action="store_true", default=False, )
[ { "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
metadata-ingestion/tests/conftest.py
chinmay-bhat/datahub
#!/usr/bin/env python3 # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you 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. from http.server import SimpleHTTPRequestHandler, HTTPServer from socketserver import ThreadingMixIn import threading import socketserver import sys class HTTPRequestHandler(SimpleHTTPRequestHandler): def do_PUT(self): length = int(self.headers["Content-Length"]) path = self.translate_path(self.path) with open(path, "wb") as dst: dst.write(self.rfile.read(length)) self.send_response(200) self.end_headers() class ThreadingSimpleServer(ThreadingMixIn, HTTPServer): pass if __name__ == '__main__': if len(sys.argv) > 1: port = int(sys.argv[1]) else: port = 6789 socketserver.TCPServer.allow_reuse_address = True with ThreadingSimpleServer(('0.0.0.0', port), HTTPRequestHandler) as httpd: print("serving at port", port) httpd.serve_forever()
[ { "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/scripts/simple_http_server.py
whileskies/incubator-teaclave
import os,shutil from SCons.Script import DefaultEnvironment from platformio import util try: # PIO < 4.4 from platformio.managers.package import PackageManager except ImportError: # PIO >= 4.4 from platformio.package.meta import PackageSpec as PackageManager def parse_pkg_uri(spec): if PackageManager.__name__ == 'PackageSpec': return PackageManager(spec).name else: name, _, _ = PackageManager.parse_pkg_uri(spec) return name def copytree(src, dst, symlinks=False, ignore=None): for item in os.listdir(src): s = os.path.join(src, item) d = os.path.join(dst, item) if os.path.isdir(s): shutil.copytree(s, d, symlinks, ignore) else: shutil.copy2(s, d) env = DefaultEnvironment() platform = env.PioPlatform() board = env.BoardConfig() variant = board.get("build.variant") platform_packages = env.GetProjectOption('platform_packages') # if there's no framework defined, take it from the class name of platform framewords = { "Ststm32Platform": "framework-arduinoststm32", "AtmelavrPlatform": "framework-arduino-avr" } if len(platform_packages) == 0: platform_name = framewords[platform.__class__.__name__] else: platform_name = parse_pkg_uri(platform_packages[0]) FRAMEWORK_DIR = platform.get_package_dir(platform_name) assert os.path.isdir(FRAMEWORK_DIR) assert os.path.isdir("buildroot/share/PlatformIO/variants") variant_dir = os.path.join(FRAMEWORK_DIR, "variants", variant) source_dir = os.path.join("buildroot/share/PlatformIO/variants", variant) assert os.path.isdir(source_dir) if os.path.isdir(variant_dir): shutil.rmtree(variant_dir) if not os.path.isdir(variant_dir): os.mkdir(variant_dir) copytree(source_dir, variant_dir)
[ { "point_num": 1, "id": "every_function_has_docstring", "question": "Does every function in this file have a docstring?", "answer": false }, { "point_num": 2, "id": "all_params_annotated", "question": "Does every function parameter in this file have a type annotation (excluding self/...
3
marlin-firmware/buildroot/share/PlatformIO/scripts/copy_marlin_variant_to_framework.py
voicevon/gogame_bot
from flask import Blueprint, jsonify, request from flask_login import current_user from dawdle.components.board.models import BoardPermission from dawdle.components.board.utils import board_permissions_required from dawdle.components.column.forms import (CreateColumnForm, DeleteColumnForm, UpdateColumnForm) from dawdle.components.column.models import Column from dawdle.components.column.utils import (board_id_from_column, column_from_column_id) column_bp = Blueprint('column', __name__, url_prefix='/column') @column_bp.route('/', methods=['POST']) @board_permissions_required(BoardPermission.WRITE) def index_POST(board, **_): form = CreateColumnForm(request.form) if not form.validate_on_submit(): return jsonify(form.errors), 400 column = Column() form.populate_obj(column) column.board_id = board.id column.created_by = current_user.id column.save() board.columns.append(column) board.save() return jsonify({ 'column': column, }), 201 @column_bp.route('/<column_id>', methods=['POST']) @column_from_column_id @board_id_from_column @board_permissions_required(BoardPermission.WRITE) def column_update_POST(column, **_): form = UpdateColumnForm(request.form) if not form.validate_on_submit(): return jsonify(form.errors), 400 form.populate_obj(column) column.save() return jsonify({ 'column': column, }), 200 @column_bp.route('/<column_id>/delete', methods=['POST']) @column_from_column_id @board_id_from_column @board_permissions_required(BoardPermission.WRITE) def column_delete_POST(column, column_id, **_): form = DeleteColumnForm(request.form) if not form.validate_on_submit(): return jsonify(form.errors), 400 column.delete() return jsonify({ 'id': column_id, }), 200
[ { "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
legacy/dawdle/components/column/blueprints.py
vanillaSlice/dawdle
import datetime import json from flask import url_for from flask import redirect from flask import render_template from flask_login import login_user from flask_login import logout_user from . import blueprint_auth from .forms import RegisterForm from .forms import LoginForm from .utils_cms import generate_code from .utils_cms import send_sms_code from ..models import db from ..models import User @blueprint_auth.route('/login', methods=['GET', 'POST']) def login(): form = LoginForm() if form.validate_on_submit(): user = User.query.filter_by(phone=form.phone.data).first() login_user(user) return redirect(url_for('blueprint_time.index')) return render_template('auth/login.html', form=form) @blueprint_auth.route('/logout', methods=['GET', 'POST']) def logout(): logout_user() return redirect(url_for('blueprint_auth.login')) @blueprint_auth.route('/register', methods=['GET', 'POST']) def register(): form = RegisterForm() if form.validate_on_submit(): new_user = User.query.filter_by(phone=form.phone.data).first() new_user.set_password(form.password.data) db.session.commit() return redirect(url_for('blueprint_auth.login')) return render_template('auth/register.html', form=form) @blueprint_auth.route('/sms_code/<string:phone>', methods=['GET', 'POST']) def sms_code(phone): user = User.query.filter_by(phone=phone).first() if not user: ret = {'result': 'error'} return json.dumps(ret) code = generate_code() ret = send_sms_code(phone, code) if not ret: ret = {'result': 'error'} return json.dumps(ret) user.sms_code = code user.updated_at = datetime.datetime.now() db.session.commit() ret = {'result': 'success'} return json.dumps(ret)
[ { "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
app/blueprint_auth/views.py
medsci-tech/mime_analysis_flask_2017
""" Project Euler Problem 7: https://projecteuler.net/problem=7 10001st prime By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13. What is the 10001st prime number? References: - https://en.wikipedia.org/wiki/Prime_number """ import itertools import math def prime_check(number: int) -> bool: """ Determines whether a given number is prime or not >>> prime_check(2) True >>> prime_check(15) False >>> prime_check(29) True """ if number % 2 == 0 and number > 2: return False return all(number % i for i in range(3, int(math.sqrt(number)) + 1, 2)) def prime_generator(): """ Generate a sequence of prime numbers """ num = 2 while True: if prime_check(num): yield num num += 1 def solution(nth: int = 10001) -> int: """ Returns the n-th prime number. >>> solution(6) 13 >>> solution(1) 2 >>> solution(3) 5 >>> solution(20) 71 >>> solution(50) 229 >>> solution(100) 541 """ return next(itertools.islice(prime_generator(), nth - 1, nth)) if __name__ == "__main__": print(f"{solution() = }")
[ { "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
project_euler/problem_007/sol3.py
NavpreetDevpuri/Python
from django.contrib.admin.views.decorators import staff_member_required from django.contrib.auth.decorators import login_required from django.utils.decorators import method_decorator from django.http import Http404 class StaffRequiredMixin(object): @classmethod def as_view(self, *args, **kwargs): view = super(StaffRequiredMixin, self).as_view(*args, **kwargs) return login_required(view) @method_decorator(login_required) def dispatch(self, request, *args, **kwargs): if request.user.is_staff: return super(StaffRequiredMixin, self).dispatch(request, *args, **kwargs) else: raise Http404 class LoginRequiredMixin(object): @classmethod def as_view(self, *args, **kwargs): view = super(LoginRequiredMixin, self).as_view(*args, **kwargs) return staff_member_required(view) @method_decorator(login_required) def dispatch(self, request, *args, **kwargs): return super(LoginRequiredMixin, self).dispatch(request, *args, **kwargs)
[ { "point_num": 1, "id": "has_multiple_inheritance", "question": "Does any class in this file use multiple inheritance?", "answer": false }, { "point_num": 2, "id": "every_class_has_docstring", "question": "Does every class in this file have a docstring?", "answer": false }, {...
3
src/products/mixins.py
jayesh96/ecommerce2
#!/usr/bin/env python3 # coding=utf8 from soco import SoCo import socket # http://docs.python-soco.com/en/latest/getting_started.html class SpeakerSonos: def __init__(self): print("SpeakerSonos initialized!") def do(self, params): speaker = SoCo(socket.gethostbyname(params['host'])) print(speaker.groups) if 'volume' in params: speaker.volume = params['volume'] if 'clear_queue' in params: speaker.clear_queue() if 'add_playlist_id_to_queue' in params: playlist = speaker.get_sonos_playlists()[params['add_playlist_id_to_queue']] speaker.add_uri_to_queue(playlist.resources[0].uri) if 'switch_to_tv' in params: speaker.switch_to_tv() if 'next' in params: speaker.next() elif 'previous' in params: speaker.previous() if 'play' in params: speaker.play() elif 'pause' in params: speaker.pause() if 'set_sleep_timer' in params: speaker.set_sleep_timer(params['set_sleep_timer'] * 60)
[ { "point_num": 1, "id": "has_multiple_inheritance", "question": "Does any class in this file use multiple inheritance?", "answer": false }, { "point_num": 2, "id": "has_nested_function_def", "question": "Does this file contain any function defined inside another function?", "answ...
3
plugins/speaker_sonos.py
mrusme/melon
#coding:utf-8 import flask_login from flask import render_template from sigda.models import db, User from sigda.config.common import ErrorCode import logging login_manager = flask_login.LoginManager() class UserDbService(object): @staticmethod def add(email, name, passwd): u = UserDbService.get_user_by_email(email) if u: return u, ErrorCode.EXIST u = User(email=email, name=name, passwd=passwd) db.session.add(u) try: db.session.flush() db.session.commit() except Exception as e: db.session.rollback() logging.error('add user') return None, ErrorCode.FAILURE return u, ErrorCode.SUCCESS @staticmethod def get_user_by_name(name): u = User.query.filter(User.name == name).first() return u @staticmethod def get_user_by_id(uid): u = User.query.filter(User.id == uid).first() return u @staticmethod def get_user_by_email(email): u = User.query.filter(User.email == email).first() return u @staticmethod def auth(email, passwd): real_user = UserDbService.get_user_by_email(email) if not real_user: return False return real_user.passwd == passwd class UserAuth(flask_login.UserMixin): pass @login_manager.user_loader def user_loader(email): u = UserDbService.get_user_by_email(email) if not u : return ua = UserAuth() ua.id = u.email ua.name = u.name return ua ''' @login_manager.request_loader def request_loader(request): email = request.form.get('email') u = UserDbService.get_user_by_email(email) if not u: return ua = UserAuth() ua.id = email ua.is_authenticated = request.form.get('passwd') == u.passwd ua.is_authenticated return ua ''' @login_manager.unauthorized_handler def unauthorized_handler(): return render_template('login.html', notifier='')
[ { "point_num": 1, "id": "every_class_has_docstring", "question": "Does every class 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
sigda/user/services.py
yangluoshen/sigda
''' Created on Nov 9, 2017 @author: khoi.ngo ''' def generate_random_string(prefix="", suffix="", size=20): """ Generate random string . :param prefix: (optional) Prefix of a string. :param suffix: (optional) Suffix of a string. :param length: (optional) Max length of a string (include prefix and suffix) :return: The random string. """ import random import string left_size = size - len(prefix) - len(suffix) random_str = "" if left_size > 0: random_str = ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(left_size)) else: print("Warning: Length of prefix and suffix more than %s chars" % str(size)) result = str(prefix) + random_str + str(suffix) return result def create_step(size): from utils.step import Step lst_step = [] for i in range(0, size): step = Step(i, "") lst_step.append(step) return lst_step def handle_exception(code): if isinstance(code, IndexError or Exception): raise code else: return code async def perform(step, func, *agrs): from indy.error import IndyError from utils.report import Status result = None try: result = await func(*agrs) step.set_status(Status.PASSED) except IndyError as E: print("Indy error" + str(E)) step.set_message(str(E)) return E except Exception as Ex: print("Exception" + str(Ex)) step.set_message(str(E)) return Ex return result async def perform_with_expected_code(step, func, *agrs, expected_code=0): from indy.error import IndyError from utils.report import Status try: await func(*agrs) except IndyError as E: if E == expected_code: step.set_status(Status.PASSED) else: print("Indy error" + str(E)) step.set_message(str(E)) return E except Exception as Ex: print("Exception" + str(Ex)) return Ex
[ { "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
indy-tests/utils/utils.py
NgoAnhKhoi/indy-testcase
from conans import ConanFile, CMake import os class HelloConan(ConanFile): name = "hello" license = "MIT" author = "Jay Zhang <wangyoucao577@gmail.com>" url = "https://github.com/wangyoucao577/hello-sdk-sample" description = "<Description of Hello here>" topics = ("<Put some tag here>", "<here>", "<and here>") settings = "os", "compiler", "build_type", "arch" options = {"shared": [True, False], "fPIC": [True, False]} default_options = {"shared": False, "fPIC": True} generators = "cmake" exports_sources = "src/*" requires = "poco/1.9.4" def set_version(self): self.version = os.getenv('PACKAGE_SEMVER', '0.1') def config_options(self): if self.settings.os == "Windows": del self.options.fPIC def build(self): cmake = CMake(self) cmake.definitions["CMAKE_HELLO_SDK_VERSION"] = self.version cmake.configure(source_folder="src") cmake.build() # Explicit way: # self.run('cmake %s/hello %s' # % (self.source_folder, cmake.command_line)) # self.run("cmake --build . %s" % cmake.build_config) def package(self): self.copy("*.h", dst="include", src="src") self.copy("*.lib", dst="lib", keep_path=False) self.copy("*.dll", dst="bin", keep_path=False) self.copy("*.dylib*", dst="lib", keep_path=False) self.copy("*.so", dst="lib", keep_path=False) self.copy("*.a", dst="lib", keep_path=False) def package_info(self): self.cpp_info.libs = ["hello"]
[ { "point_num": 1, "id": "every_function_has_docstring", "question": "Does every function in this file have a docstring?", "answer": false }, { "point_num": 2, "id": "all_function_names_snake_case", "question": "Are all function names in this file written in snake_case?", "answer"...
3
conanfile.py
wangyoucao577/hello-sdk-sample
import msgpack def dump(obj, fp, default=None): msgpack.pack(obj, fp, use_bin_type=True, default=default) def dumps(obj, default=None): return msgpack.packb(obj, use_bin_type=True, default=default) def load(fp, object_hook=None): return msgpack.unpack(fp, object_hook=object_hook, encoding='utf8') def loads(b, object_hook=None): return msgpack.unpackb(b, object_hook=object_hook, encoding='utf8') def stream_unpacker(fp, object_hook=None): return msgpack.Unpacker(fp, object_hook=object_hook, encoding='utf8') __all__ = [ "dump", "dumps", "load", "loads", "stream_unpacker", ]
[ { "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
p2p_python/serializer.py
namuyan/p2p-python
from typing import List from fastapi import APIRouter from samey.table_crud import * from .models import * router = APIRouter() @router.get("/", response_model=List[Stack]) def list_stacks(): return query(tables.Stack) @router.post("/", response_model=Stack, status_code=201) def create_stack(stack_in: Stack): return create(tables.Stack, stack_in) @router.put("/{id}", response_model=Stack) def update_stack(id: str, stack_in: Stack): return update(tables.Stack, id, stack_in) @router.get("/{id}", response_model=Stack) def get_stack(id: str): return get_or_error(tables.Stack, id, "Stack not found") @router.delete("/{id}", status_code=204) def delete_stack(id: str): delete(tables.Stack, id)
[ { "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
sites/stacks/api.py
bluebirdio/improbable-sites
""" Module: 'ds18x20' on esp8266 v1.11 """ # MCU: (sysname='esp8266', nodename='esp8266', release='2.2.0-dev(9422289)', version='v1.11-8-g48dcbbe60 on 2019-05-29', machine='ESP module with ESP8266') # Stubber: 1.2.0 class DS18X20: '' def convert_temp(): pass def read_scratch(): pass def read_temp(): pass def scan(): pass def write_scratch(): pass def const(): pass
[ { "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
packages/micropython-official/v1.11/esp8266/stubs/ds18x20.py
TheVinhLuong102/micropy-stubs
#!/usr/bin/env python # Copyright 2016 Google Inc. 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 sys import struct import json def sendraw(buf): sys.stdout.write(struct.pack("<q", len(buf))) sys.stdout.write(buf) sys.stdout.flush() def send(obj): sendraw(json.dumps(obj)) def mainloop(): text = '' while True: sizebuf = sys.stdin.read(8) if len(sizebuf) == 0: return (size,) = struct.unpack("<q", sizebuf) cmd, arg = json.loads(sys.stdin.read(size)) print >> sys.stderr, cmd, arg if cmd == 'key': chars = arg['chars'] if chars == u'\x7f': if len(text): text = text[:-1] else: text += chars send(['settext', text]) mainloop()
[ { "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/xicore.py
regexident/xi-editor
"""Assorted utilities shared between parts of apitools.""" import collections import httplib import os import types import urllib2 from apitools.base.py import exceptions __all__ = [ 'DetectGae', 'DetectGce', ] def DetectGae(): """Determine whether or not we're running on GAE. This is based on: https://developers.google.com/appengine/docs/python/#The_Environment Returns: True iff we're running on GAE. """ server_software = os.environ.get('SERVER_SOFTWARE', '') return (server_software.startswith('Development/') or server_software.startswith('Google App Engine/')) def DetectGce(): """Determine whether or not we're running on GCE. This is based on: https://developers.google.com/compute/docs/instances#dmi Returns: True iff we're running on a GCE instance. """ try: o = urllib2.urlopen('http://metadata.google.internal') except urllib2.URLError: return False return o.getcode() == httplib.OK def NormalizeScopes(scope_spec): """Normalize scope_spec to a set of strings.""" if isinstance(scope_spec, types.StringTypes): return set(scope_spec.split(' ')) elif isinstance(scope_spec, collections.Iterable): return set(scope_spec) raise exceptions.TypecheckError( 'NormalizeScopes expected string or iterable, found %s' % ( type(scope_spec),)) def Typecheck(arg, arg_type, msg=None): if not isinstance(arg, arg_type): if msg is None: if isinstance(arg_type, tuple): msg = 'Type of arg is "%s", not one of %r' % (type(arg), arg_type) else: msg = 'Type of arg is "%s", not "%s"' % (type(arg), arg_type) raise exceptions.TypecheckError(msg) return arg
[ { "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
.install/.backup/lib/apitools/base/py/util.py
bopopescu/google-cloud-sdk
"""Support for the Abode Security System locks.""" import abodepy.helpers.constants as CONST from homeassistant.components.lock import LockEntity from homeassistant.config_entries import ConfigEntry from homeassistant.core import HomeAssistant from homeassistant.helpers.entity_platform import AddEntitiesCallback from . import AbodeDevice from .const import DOMAIN async def async_setup_entry( hass: HomeAssistant, config_entry: ConfigEntry, async_add_entities: AddEntitiesCallback, ) -> None: """Set up Abode lock devices.""" data = hass.data[DOMAIN] entities = [] for device in data.abode.get_devices(generic_type=CONST.TYPE_LOCK): entities.append(AbodeLock(data, device)) async_add_entities(entities) class AbodeLock(AbodeDevice, LockEntity): """Representation of an Abode lock.""" def lock(self, **kwargs): """Lock the device.""" self._device.lock() def unlock(self, **kwargs): """Unlock the device.""" self._device.unlock() @property def is_locked(self): """Return true if device is on.""" return self._device.is_locked
[ { "point_num": 1, "id": "has_multiple_inheritance", "question": "Does any class in this file use multiple inheritance?", "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
homeassistant/components/abode/lock.py
andersop91/core
import string from Bio import Alphabet, Seq from Bio.Alphabet import IUPAC class Transcribe: def __init__(self, dna_alphabet, rna_alphabet): self.dna_alphabet = dna_alphabet self.rna_alphabet = rna_alphabet def transcribe(self, dna): assert dna.alphabet == self.dna_alphabet, \ "transcribe has the wrong DNA alphabet" s = dna.data return Seq.Seq(string.replace(s, "T", "U"), self.rna_alphabet) def back_transcribe(self, rna): assert rna.alphabet == self.rna_alphabet, \ "back transcribe has the wrong RNA alphabet" s = rna.data return Seq.Seq(string.replace(s, "U", "T"), self.dna_alphabet) generic_transcriber = Transcribe(Alphabet.generic_dna, Alphabet.generic_rna) ambiguous_transcriber = Transcribe(IUPAC.ambiguous_dna, IUPAC.ambiguous_rna) unambiguous_transcriber = Transcribe(IUPAC.unambiguous_dna, IUPAC.unambiguous_rna)
[ { "point_num": 1, "id": "all_function_names_snake_case", "question": "Are all function names in this file written in snake_case?", "answer": true }, { "point_num": 2, "id": "no_function_exceeds_5_params", "question": "Does every function in this file take 5 or fewer parameters (exclu...
3
ddi_search_engine/Bio/Transcribe.py
dbmi-pitt/DIKB-Evidence-analytics
# Copyright (c) 2013, igrekus and contributors # For license information, please see license.txt from __future__ import unicode_literals import frappe from frappe import _ from dc_plc.custom.utils import add_completeness, add_query_relevance from dc_plc.controllers.stats_query import get_procmap_stats def execute(filters=None): columns = get_columns() data = get_data(filters) return columns, data def get_columns(): return [ "ID:Link/DC_PLC_Product_Summary", _("Relevance"), _("Progress"), _("RnD Title"), _("Function"), _("External number"), _("Process map"), _("Internal number") ] def get_data(filters): res = get_procmap_stats(filters) has_perms = 'DC_PLC_Process_Map_Specialist' in frappe.get_roles(frappe.session.user) res = [add_completeness(row, [4]) for row in res] res = [add_query_relevance(row, has_perms) for row in res] return res
[ { "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
dc_plc/dc_plc/report/dc_product_procmap_stats/dc_product_procmap_stats.py
igrekus/dc_plc
from awssg.Client_Interface import Client_Interface from awssg.VPC_Client import VPC_Client import boto3 class Client(Client_Interface): def __init__(self): self.ec2_client = boto3.client('ec2') def describe_security_groups(self) -> dict: return self.ec2_client.describe_security_groups() def describe_regions(self) -> dict: return self.ec2_client.describe_regions() def describe_db_instances(self) -> dict: self.aws_client = boto3.client('rds') return self.aws_client.describe_db_instances() def describe_specific_security_group(self, security_group: str): return self.ec2_client.describe_security_groups(GroupNames=[security_group]) def create_security_group(self, group_name: str, vpc_id: str): return self.ec2_client.create_security_group( GroupName=group_name, Description=group_name, VpcId=vpc_id ) def get_region_name(self) -> str: return self.ec2_client.meta.region_name def delete_security_group_by_name(self, group_name: str): self.ec2_client.delete_security_group( GroupName=group_name ) def delete_security_group_by_id(self, group_id: str): self.ec2_client.delete_security_group( GroupId=group_id ) def set_rule(self, group_id: str, protocol: str, ip: str, port: str): ec2 = boto3.resource('ec2') security_group = ec2.SecurityGroup(group_id) security_group.authorize_ingress( IpProtocol=protocol, CidrIp=ip + "/32", FromPort=int(port), ToPort=int(port) ) def describe_vpcs(self): return VPC_Client().describe_vpcs() def describe_specific_security_group_by_id(self, sg_id: str): return self.ec2_client.describe_security_groups(GroupIds=[sg_id])
[ { "point_num": 1, "id": "more_functions_than_classes", "question": "Does this file define more functions than classes?", "answer": true }, { "point_num": 2, "id": "every_function_under_20_lines", "question": "Is every function in this file shorter than 20 lines?", "answer": true ...
3
awssg/Client.py
danilocgsilva/aws-sg
from os.path import exists from typing import Optional from yaml import safe_load, safe_dump from .model import GameSettings, GameConfig from .typing import ISettingManager, IPathProvider from .events import publish_game_event, SETTINGS_CHANGED class YamlSettingsManager(ISettingManager): def get_settings(self) -> GameSettings: if not self._settings: self._load_from_disk_or_default() return self._settings def set_settings(self, settings: GameSettings) -> None: self._settings = settings self._write_to_disk() publish_game_event(SETTINGS_CHANGED, settings=settings) def _load_from_disk_or_default(self): if not exists(self._path): self._settings = self._defaults self._write_to_disk() else: with open(self._path, "r") as fd: dat = safe_load(fd) self._settings = GameSettings.load(dat) def _write_to_disk(self): self._path_provider.ensure_config_dir_exists() with open(self._path, "w") as fd: safe_dump(self._settings.todict(), fd) def __init__(self, game_config: GameConfig, path_provider: IPathProvider): self._path_provider = path_provider self._path = path_provider.get_config_path("game-settings.yaml") self._settings: Optional[GameSettings] = None self._defaults: GameSettings = game_config.default_settings
[ { "point_num": 1, "id": "all_params_annotated", "question": "Does every function parameter in this file have a type annotation (excluding self/cls)?", "answer": true }, { "point_num": 2, "id": "more_functions_than_classes", "question": "Does this file define more functions than class...
3
malibu_lib/setting_manager.py
en0/codename-malibu
from __future__ import absolute_import, division, print_function, unicode_literals import unittest import torch from tests import utils class SimpleFloorModule(torch.nn.Module): def forward(self, a, b): c = a + b return torch.floor(c) class TestFloor(unittest.TestCase): def test_floor(self): """Basic test of the PyTorch floor Node on Glow.""" x = torch.randn(3, 4, 5) y = torch.randn(3, 4, 5) utils.compare_tracing_methods( SimpleFloorModule(), x, y, fusible_ops={"aten::floor"} )
[ { "point_num": 1, "id": "every_class_has_docstring", "question": "Does every class in this file have a docstring?", "answer": false }, { "point_num": 2, "id": "every_function_has_docstring", "question": "Does every function in this file have a docstring?", "answer": false }, ...
3
torch_glow/tests/nodes/floor_test.py
aksingh-fb/glow
from flask import Flask, jsonify, request from cashman.model.expense import Expense, ExpenseSchema from cashman.model.income import Income, IncomeSchema from cashman.model.transaction_type import TransactionType app = Flask(__name__) transactions = [ Income('Salary', 5000), Income('Dividends', 200), Expense('pizza', 50), Expense('Rock Concert', 100) ] @app.route('/incomes') def get_incomes(): schema = IncomeSchema(many=True) incomes = schema.dump( filter(lambda t: t.type == TransactionType.INCOME, transactions) ) return jsonify(incomes) @app.route('/incomes', methods=['POST']) def add_income(): income = IncomeSchema().load(request.get_json()) transactions.append(income) return "", 204 @app.route('/expenses') def get_expenses(): schema = ExpenseSchema(many=True) expenses = schema.dump( filter(lambda t: t.type == TransactionType.EXPENSE, transactions) ) return jsonify(expenses) @app.route('/expenses', methods=['POST']) def add_expense(): expense = ExpenseSchema().load(request.get_json()) transactions.append(expense) return "", 204 @app.route('/all') def get_all(): schema = IncomeSchema(many=True) all = schema.dump(transactions) return jsonify(all) if __name__ == "__main__": app.run()
[ { "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
cashman/index.py
horahh/flask-restful-apis
from direct.distributed import DistributedObjectAI from . import Entity from direct.directnotify import DirectNotifyGlobal class DistributedEntityAI(DistributedObjectAI.DistributedObjectAI, Entity.Entity): notify = DirectNotifyGlobal.directNotify.newCategory('DistributedEntityAI') def __init__(self, level, entId): if hasattr(level, 'air'): air = level.air self.levelDoId = level.doId else: air = level level = None self.levelDoId = 0 DistributedObjectAI.DistributedObjectAI.__init__(self, air) Entity.Entity.__init__(self, level, entId) return def generate(self): self.notify.debug('generate') DistributedObjectAI.DistributedObjectAI.generate(self) def destroy(self): self.notify.debug('destroy') Entity.Entity.destroy(self) self.requestDelete() def delete(self): self.notify.debug('delete') DistributedObjectAI.DistributedObjectAI.delete(self) def getLevelDoId(self): return self.levelDoId def getEntId(self): return self.entId if __dev__: def setParentEntId(self, parentEntId): self.parentEntId = parentEntId newZoneId = self.getZoneEntity().getZoneId() if newZoneId != self.zoneId: self.sendSetZone(newZoneId)
[ { "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
otp/level/DistributedEntityAI.py
TheFamiliarScoot/open-toontown
# This file is part of Moksha. # Copyright (C) 2008-2010 Red Hat, Inc. # # 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. # # Authors: Luke Macken <lmacken@redhat.com> from moksha.hub.messaging import MessagingHubExtension class BaseAMQPHubExtension(MessagingHubExtension): """ A skeleton class for what we expect from an AMQP implementation. This allows us to bounce between different AMQP modules without too much pain and suffering. """ conn = None def __init__(self): """ Initialize a connection to a specified broker. This method must set self.channel to an active channel. """ pass def send_message(self, topic, message, **headers): pass def subscribe(self, topic, callback): pass def create_queue(self, queue, exchange, durable, exclusive, auto_delete): raise NotImplementedError def bind_queue(self, queue, exchange): raise NotImplementedError def wait(self): """ Block for new messages """ raise NotImplementedError def close(self): raise NotImplementedError
[ { "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
moksha.hub/moksha/hub/amqp/base.py
hroncok/moksha
# Debug helper functions # Author: Matej Kastak from colors import Color from context import Context def debug_print(s): if Context().debug_enabled: Color.print(Color.GREEN, str(s)) def debug_enabled(): return Context().debug_enabled
[ { "point_num": 1, "id": "all_return_types_annotated", "question": "Does every function in this file have a return type annotation?", "answer": false }, { "point_num": 2, "id": "every_function_has_docstring", "question": "Does every function in this file have a docstring?", "answe...
3
insrunner/debug.py
MatejKastak/insrunner
import pytest import graphviz from graphviz import parameters VERIFY_FUNCS = [parameters.verify_engine, parameters.verify_format, parameters.verify_renderer, parameters.verify_formatter] @pytest.mark.parametrize( 'cls', [graphviz.Graph, graphviz.Digraph, graphviz.Source]) def test_parameters(cls, engine='patchwork', format='tiff', renderer='map', formatter='core'): args = [''] if cls is graphviz.Source else [] dot = cls(*args, engine=engine, format=format, renderer=renderer, formatter=formatter) assert isinstance(dot, cls) assert type(dot) is cls assert dot.engine == engine assert dot.format == format assert dot.renderer == renderer assert dot.formatter == formatter dot_copy = dot.copy() assert dot_copy is not dot assert isinstance(dot_copy, cls) assert type(dot_copy) is cls assert dot.engine == engine assert dot.format == format assert dot_copy.renderer == renderer assert dot_copy.formatter == formatter @pytest.mark.parametrize( 'verify_func', VERIFY_FUNCS) def test_verify_parameter_raises_unknown(verify_func): with pytest.raises(ValueError, match=r'unknown .*\(must be .*one of'): verify_func('Brian!') @pytest.mark.parametrize( 'verify_func', VERIFY_FUNCS) def test_verify_parameter_none_required_false_passes(verify_func): assert verify_func(None, required=False) is None @pytest.mark.parametrize( 'verify_func', VERIFY_FUNCS) def test_verify_parameter_none_required_raises_missing(verify_func): with pytest.raises(ValueError, match=r'missing'): verify_func(None, required=True)
[ { "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
tests/test_parameters.py
iycheng/graphviz
def distribute_guests(n, end_command): guests = set() for _ in range(n): guest = input() guests.add(guest) while True: guest_arrived = input() if guest_arrived == end_command: break guests.remove(guest_arrived) return guests def print_guests(guests): guests = sorted(guests) print(len(guests)) [print(g) for g in guests] print_guests(distribute_guests(int(input()), 'END'))
[ { "point_num": 1, "id": "every_function_has_docstring", "question": "Does every function in this file have a docstring?", "answer": false }, { "point_num": 2, "id": "all_params_annotated", "question": "Does every function parameter in this file have a type annotation (excluding self/...
3
Old/Python-Advanced-Preliminary-Homeworks/Tuples and Sets/05. SoftUni Party.py
MNikov/Python-Advanced-September-2020
from django.conf import settings from yubico_client import Yubico def yubikey_authenticate(yubikey_otp): """ Checks a YubiKey OTP :param yubikey_otp: Yubikey OTP :type yubikey_otp: :return: True or False or None :rtype: bool """ if settings.YUBIKEY_CLIENT_ID is None or settings.YUBIKEY_SECRET_KEY is None: return None client = Yubico(settings.YUBIKEY_CLIENT_ID, settings.YUBIKEY_SECRET_KEY) try: yubikey_is_valid = client.verify(yubikey_otp) except: yubikey_is_valid = False return yubikey_is_valid def yubikey_get_yubikey_id(yubikey_otp): """ Returns the yubikey id based :param yubikey_otp: Yubikey OTP :type yubikey_otp: str :return: Yubikey ID :rtype: str """ yubikey_otp = str(yubikey_otp).strip() return yubikey_otp[:12]
[ { "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
psono/restapi/utils/yubikey.py
dirigeant/psono-server