source
string
points
list
n_points
int64
path
string
repo
string
from contextlib import closing import json import logging import boto3 from lambda_logs import JSONFormatter, custom_lambda_logs logger = logging.getLogger() logger.setLevel(logging.INFO) logger.handlers[0].setFormatter(JSONFormatter()) class QCFailed(Exception): def __init__(self, message: str): self.message = message def lambda_handler(event: dict, context: object): with custom_lambda_logs(**event["logging"]): logger.info(f"event: {str(event)}") s3_path = f"{event['repo']}/{event['qc_result_file']}" bucket, key = s3_path.split("/", 3)[2:] s3 = boto3.client("s3") response = s3.get_object(Bucket=bucket, Key=key) with closing(response["Body"]) as fp: qc_object = json.load(fp) logger.info(f"input: {str(qc_object)}") result = eval(event["qc_expression"], globals(), qc_object) if result: logger.warning("failed QC check") sfn = boto3.client("stepfunctions") sfn.stop_execution( executionArn=event["execution_id"], error=f"Job {event['logging']['job_file_key']} failed QC check at step {event['logging']['step_name']}", cause=f"failed condition: {event['qc_expression']}" ) raise QCFailed(f"QC check failed ({event['qc_expression']})") else: logger.info("passed QC check")
[ { "point_num": 1, "id": "every_function_has_docstring", "question": "Does every function in this file have a docstring?", "answer": false }, { "point_num": 2, "id": "every_function_under_20_lines", "question": "Is every function in this file shorter than 20 lines?", "answer": fal...
3
lambda/src/qc_checker/qc_checker.py
jack-e-tabaska/BayerCLAW
import sys import json import numpy as np import pylab def plot(X,Y,theory,data,err): #print "theory",theory[1:6,1:6] #print "data",data[1:6,1:6] #print "delta",(data-theory)[1:6,1:6] pylab.subplot(3,1,1) pylab.pcolormesh(X,Y, data) pylab.subplot(3,1,2) pylab.pcolormesh(X,Y, theory) pylab.subplot(3,1,3) pylab.pcolormesh(X,Y, (data-theory)/(err+1)) def load_results(filename): """ Reload results from the json file created by Peaks.save """ data = json.load(open(filename)) # Convert array info back into numpy arrays data.update( (k,np.array(data[k])) for k in ('X', 'Y', 'data', 'err', 'theory') ) return data def main(): data = load_results(sys.argv[1]) plot(data['X'],data['Y'],data['theory'],data['data'],data['err']) pylab.show() if __name__ == "__main__": main()
[ { "point_num": 1, "id": "every_function_under_20_lines", "question": "Is every function in this file shorter than 20 lines?", "answer": true }, { "point_num": 2, "id": "no_function_exceeds_5_params", "question": "Does every function in this file take 5 or fewer parameters (excluding ...
3
doc/examples/peaks/plot.py
cyankaet/bumps
import unittest from unittest import TestCase import mechanize def first_form(text, base_uri="http://example.com/"): return mechanize.ParseString(text, base_uri)[0] class MutationTests(TestCase): def test_add_textfield(self): form = first_form('<input type="text" name="foo" value="bar" />') more = first_form('<input type="text" name="spam" value="eggs" />') combined = form.controls + more.controls for control in more.controls: control.add_to_form(form) self.assertEquals(form.controls, combined) if __name__ == "__main__": unittest.main()
[ { "point_num": 1, "id": "more_functions_than_classes", "question": "Does this file define more functions than classes?", "answer": true }, { "point_num": 2, "id": "every_function_has_docstring", "question": "Does every function in this file have a docstring?", "answer": false }...
3
test/test_form_mutation.py
smalllark/mechanize
# coding=utf-8 # Copyright 2017-2019 The THUMT Authors from __future__ import absolute_import from __future__ import division from __future__ import print_function import sys _ENGINE = None def enable_distributed_training(): global _ENGINE try: import horovod.tensorflow as hvd _ENGINE = hvd hvd.init() except ImportError: sys.stderr.write("Error: You must install horovod first in order to" " enable distributed training.\n") exit() def is_distributed_training_mode(): return _ENGINE is not None def rank(): return _ENGINE.rank() def local_rank(): return _ENGINE.local_rank() def size(): return _ENGINE.size() def all_reduce(tensor): return _ENGINE.allreduce(tensor, compression=_ENGINE.Compression.fp16) def get_broadcast_hook(): return _ENGINE.BroadcastGlobalVariablesHook(0)
[ { "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
thumt/utils/distribute.py
THUNLP-MT/Copy4APE
# -*- coding: utf-8 -*- from __future__ import unicode_literals from __future__ import division from __future__ import absolute_import from __future__ import print_function from . import Attribute class Item(object): """ """ ID = 0 def __init__(self): """ """ self.id = Item.ID Item.ID += 1 self.attr = {} def __str__(self): """ """ s = "" s += "ID: %i" % self.id s += "\n" for a in self.attr: s += "%s : %s" % (self.attr[a].name, str(self.attr[a].value)) s += "\n" return s def __setitem__(self, name, value): """ """ self.attr[name] = Attribute(name, value) def __getitem__(self, name): """ """ try: re = self.attr[name].value except: re = None return re def attributes(self): """ """ return self.attr
[ { "point_num": 1, "id": "every_function_has_docstring", "question": "Does every function in this file have a docstring?", "answer": true }, { "point_num": 2, "id": "every_function_under_20_lines", "question": "Is every function in this file shorter than 20 lines?", "answer": true...
3
item.py
stavsta/tpzgraphml
''' Some utility functions ''' import os.path def cm2inch(value): ''' convert from cm to inches ''' return value / 2.54 def read_pdb_distribution(residue): ''' read the pdb distributions ''' if residue.lower() == 'ile': path = os.path.join( os.path.split(__file__)[0], "resources/ile_top8000_distribution.dat") file_ = open(path) data = file_.readlines() file_.close() pops = {a.split()[0]: float(a.split()[1]) for a in data} return pops
[ { "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
pyroshift/util.py
L-Siemons/PyRoShift
import pytest from contoso import get_company_name, get_company_address def test_get_company_name(): assert get_company_name() == "Contoso" def test_get_company_address(): assert get_company_address() == "Contosostrasse 1, Zurich, Switzerland"
[ { "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_return_types_annotated", "question": "Does every function in this file have a return type annotation?...
3
src/packages/tests/test_company_details.py
fbeltrao/az-func-gh-deployment
import tkinter as tk class Application(tk.Frame): def __init__(self, master=None): super().__init__(master) self.master = master self.pack() self.create_widgets() def create_widgets(self): self.hi_there = tk.Button(self) self.hi_there["text"] = "Hello World\n(click me)" self.hi_there["command"] = self.say_hi self.hi_there.pack(side="top") self.button2 = tk.Button(self) self.button2["text"] = "This is a button" self.button2["command"] = self.say_by self.button2.pack(side="left") self.quit = tk.Button(self, text="QUIT", fg="red", command=self.master.destroy) self.quit.pack(side="bottom") def say_hi(self): print("hi there, everyone!") def say_by(self): print("good by") root = tk.Tk() app = Application(master=root) app.mainloop()
[ { "point_num": 1, "id": "has_nested_function_def", "question": "Does this file contain any function defined inside another function?", "answer": false }, { "point_num": 2, "id": "has_multiple_inheritance", "question": "Does any class in this file use multiple inheritance?", "answ...
3
test gui.py
shogan50/paint_bot_ml
# coding: utf-8 import chainer import chainer.links as L # Network definition class A(chainer.Chain): def __init__(self, n_vocab, n_out): super(A, self).__init__() with self.init_scope(): self.l1 = L.EmbedID(n_vocab, n_out) def forward(self, x): return self.l1(x) # ====================================== from chainer_compiler import ch2o if __name__ == '__main__': import numpy as np np.random.seed(314) n_vocab = 7 n_out = 3 n_batch = 5 model = A(n_vocab, n_out) v = np.random.randint(n_vocab, size=n_batch) ch2o.generate_testcase(model, [v], backprop=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": "more_functions_than_classes", "question": "Does this file define more functions than clas...
3
testcases/ch2o_tests/node/EmbedID.py
vermashresth/chainer-compiler
from rest_framework import serializers from profiles_api import models class HelloSerializer(serializers.Serializer): """Serializes a name field for testing our APIView""" name = serializers.CharField(max_length=10) class UserProfileSerializer(serializers.ModelSerializer): """Serializes a user profile object""" class Meta: model = models.UserProfile fields = ('id', 'email', 'name', 'password') extra_kwargs = { 'password' : { 'write_only': True, 'style': {'input_type': 'password'} } } def create(self, validated_data): """Creste and return a new user""" user = models.UserProfile.objects.create_user( email=validated_data['email'], name=validated_data['name'], password=validated_data['password'] ) return user
[ { "point_num": 1, "id": "every_class_has_docstring", "question": "Does every class in this file have a docstring?", "answer": false }, { "point_num": 2, "id": "more_functions_than_classes", "question": "Does this file define more functions than classes?", "answer": false }, {...
3
profiles_api/serializers.py
SrijitPal/profiles-rest-api
""" test for the module `remove_salts` """ import pytest import sys import rdkit from rdkit import Chem from opencadd.compounds.standardization.remove_salts import remove_salts def _evaluation_mol_generator(test_smiles=None, test_inchi=None): """Creates mol files directly with rdkits functions for evaluation.""" if test_smiles is not None: return Chem.MolFromSmiles(test_smiles) if test_inchi is not None: return Chem.MolFromInchi(test_inchi) def _molecule_test(test_inchi=None, test_smiles=None): return Chem.MolToInchi( remove_salts( _evaluation_mol_generator(test_inchi=test_inchi, test_smiles=test_smiles) ) ) def test_structure(): """Only C(C(=O)[O-])(Cc1n[n-]nn1)(C[NH3+])(C[N+](=O)[O-] should be left after stripping salts. """ assert ( _molecule_test( test_smiles="C(C(=O)[O-])(Cc1n[n-]nn1)(C[NH3+])(C[N+](=O)[O-].CCCCCCCCCCCCCCCCCC(=O)O.OCC(O)C1OC(=O)C(=C1O)O)" ) == "InChI=1S/C6H10N6O4/c7-2-6(5(13)14,3-12(15)16)1-4-8-10-11-9-4/h1-3,7H2,(H2,8,9,10,11,13,14)/p-1" ) def test_single_salts(): """All salt fragments should be detected and stripped.""" assert ( _molecule_test( test_smiles="[Al].N.[Ba].[Bi].Br.[Ca].Cl.F.I.[K].[Li].[Mg].[Na].[Ag].[Sr].S.O.[Zn]" ) == "" ) def test_complex_salts(): """Complex salts, contained in salts.tsv should be detected.""" assert ( _molecule_test(test_smiles="OC(C(O)C(=O)O)C(=O)O.O=C1NS(=O)(=O)c2ccccc12") == "" ) def test_custom_dictionary(): """Configuration of a custom dictionary, by defining one, should work. """ assert ( Chem.MolToInchi( remove_salts( _evaluation_mol_generator(test_smiles="[Al].N.[Ba].[Bi]"), dictionary=False, defnData="[Al]", ) ) == "InChI=1S/Ba.Bi.H3N.2H/h;;1H3;;" )
[ { "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
opencadd/tests/compounds/standardization/test_remove_salts.py
Allend95/opencadd
def do(action, value, acc, i): if action == 'acc': acc += value elif action == 'jmp': i += value - 1 elif action == 'nop': pass return acc, i def run(instrs): visited, acc, i = set(), 0, 0 while i < len(instrs): if i in visited: break else: visited.add(i) action, value = instrs[i] acc, i = do(action, int(value), acc, i) i += 1 else: return acc, True return acc, False if __name__ == '__main__': with open('input.txt') as input_file: instructions = [tuple(line.split()) for line in input_file] changeble = [i for i, (action, _) in enumerate(instructions) if action in ('nop', 'jmp')] for i in changeble: old_action, value = instructions[i] new_action = 'jmp' if old_action == 'nop' else 'nop' instructions[i] = new_action, value res, terminated = run(instructions) if terminated: print(res) break else: instructions[i] = old_action, value
[ { "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
day_08/day_08.py
niccolomarcon/AoC_2020
import socket import time class TestIO: def __init__(self): # self.ipAddress = "10.20.8.136" self.ipAddress = "10.20.0.194" self.port = 63350 def queryServer(self, query): """ Private method that sends a command and returns the server's response in a readable fashion 1- Creates a TCP socket with the robot on the port 63 350. 2- Encode and execute the given query. 3- Store the result 4- Close the socket 5- Return the server's answer. Args: query (String): Query to send to the server. Returns: """ # Create the socket tcpSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # Connect to the server tcpSocket.connect((self.ipAddress, self.port)) # Run the query tcpSocket.sendall(query.encode()) try: # Receive the result data = tcpSocket.recv(1024) except Exception as e: print(str(e)) finally: tcpSocket.close() # Return the formatted value return data if __name__ == '__main__': """ GET SNU returns the serial number as string formatted int8 array GET FWV returns the firmware version as string formatted int8 array GET PYE returns the production year as string formatted int8 array SET ZRO This calibrates the sensor's current readings to zero then returns "Done" """ test = TestIO() # cmd = "READ UR DATA" + "\n" cmd = "READ DATA" + "\n" cmd.encode('utf-8') # cmd = "CURRENT STATE" print(str(test.queryServer(cmd))) # # while True: # print(str(test.queryServer(cmd))) # time.sleep(1)
[ { "point_num": 1, "id": "every_function_under_20_lines", "question": "Is every function in this file shorter than 20 lines?", "answer": false }, { "point_num": 2, "id": "more_functions_than_classes", "question": "Does this file define more functions than classes?", "answer": true...
3
forcecopilot/forcecopilot_reading.py
roymart1/RQBasicDevTest
#!/usr/bin/env python import numpy as np import cv2 as cv from umucv.stream import Camera from umucv.util import ROI, putText from skimage.feature import hog cv.namedWindow('cam') roi = ROI('cam') PPC = 16 CPB = 2 SHOW = False cam = Camera() def feat(region): r = cv.cvtColor(region, cv.COLOR_BGR2GRAY) return hog( r, visualise = SHOW, transform_sqrt=True, feature_vector=False, orientations = 8, pixels_per_cell = (PPC,PPC), cells_per_block = (CPB,CPB), block_norm = 'L1' ) def dist(u,v): return sum(abs(u-v))/len(u) MODEL = None while True: key = cv.waitKey(1) & 0xFF if key == 27: break if key == ord('x'): MODEL = None x = cam.frame.copy() if SHOW: h, sh = feat(x) cv.imshow('hog', sh) else: h = feat(x) if MODEL is not None: h1,w1 = h.shape[:2] h2,w2 = MODEL.shape[:2] detected = [] for j in range(h1-h2): for k in range(w1-w2): vr = h[j:j+h2 , k: k+w2].flatten() v = MODEL.flatten() detected.append( (dist(vr,v), j, k) ) d,j,k = min(detected) x1 = k*PPC y1 = j*PPC x2 = x1+(w2+CPB-1)*PPC y2 = y1+(h2+CPB-1)*PPC if d < 0.04: cv.rectangle(x, (x1,y1), (x2,y2), color=(255,255,0), thickness=2) putText(x,'{:.3f}'.format(d),(6,18),(0,128,255)) if roi.roi: [x1,y1,x2,y2] = roi.roi reg = x[y1:y2, x1:x2].copy() if key == ord('c'): if SHOW: MODEL, sh = feat(reg) cv.imshow('model', sh) else: MODEL = feat(reg) roi.roi = [] cv.rectangle(x, (x1,y1), (x2,y2), color=(0,255,255), thickness=2) cv.imshow('cam', x) cam.stop()
[ { "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
code/hog/hog0.py
josemac95/umucv
from flask import Flask, flash, redirect, render_template, request, session, abort app = Flask(__name__) @app.route("/") def index(): return "Flask App!" @app.route("/plants") def plants(): return render_template('plants.html') @app.route("/animals") def animals(): return render_template('animals.html') @app.route("/humans") def humans(): return render_template('humans.html') if __name__ == "__main__": app.run(host ='0.0.0.0', port = 5001, debug = True)
[ { "point_num": 1, "id": "all_function_names_snake_case", "question": "Are all function names in this file written in snake_case?", "answer": true }, { "point_num": 2, "id": "all_return_types_annotated", "question": "Does every function in this file have a return type annotation?", ...
3
webapp.py
sheldon-cooper26/PythonFlask-Docker
from hangul_romanize import Transliter from hangul_romanize.rule import academic class Word: """ Object representation of a word record that can update the success_rating of that record. """ _romanize = Transliter(academic).translit def __init__(self, _id: int, english: str, korean: str, score: int): self._id = _id self._english = english self._korean = korean self._romanized = self._romanize(korean) self._score = score def __repr__(self) -> str: return f"<Word(English: '{self._english}', Korean:'{self._korean}')>" def get_id(self): return self._id def get_english(self): return self._english def get_korean(self): return self._korean def get_romanized(self): return self._romanized def get_score(self): return self._score def update_eng_to_kor(self, correct: bool) -> None: self._score += -2 if correct else 1 if self._score < 10: self._score = 0 def update_kor_to_eng(self, correct: bool) -> None: if not correct: self._score += 2 elif 10 < self._score: self._score -= 1 if self._score < 10: self._score = 0 def update_record(self): from database.access import Access Access.update_word_record(self)
[ { "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
database/word.py
YeetmeisterII/KoreanVocabularyLearner
# from typing_extensions import Required from django.shortcuts import redirect, render from django.contrib.auth import authenticate, login, logout from django.contrib.auth.decorators import login_required from django.contrib import messages from .decorators import allowed_users, unauthenticated_user from .models import SiteWide def logoutUser(request): if request.user.is_authenticated: logout(request) messages.success(request, "You've been logged out!") else: messages.error(request, "You are NOT logged in!") return redirect('index') @unauthenticated_user def loginPage(request): if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') user = authenticate(request, username=username, password=password) if user is not None: login(request, user) messages.success(request, "Welcome! You are now logged in!") return redirect('home') else: messages.error(request, 'The Username or Password is incorrect') context = {} return render(request, 'app1/login.html', context) @login_required(login_url='login') @allowed_users(allowed_roles=['adminGroup']) def adminpanel(request): sitewide = SiteWide.objects.all().first() return render(request, 'app1/adminpanel.html', { 'sitewide':sitewide }) @login_required(login_url='login') @allowed_users(allowed_roles=['userGroup', 'adminGroup']) def home(request): sitewide = SiteWide.objects.all().first() return render(request, 'app1/home.html', { 'sitewide':sitewide }) def index(request): sitewide = SiteWide.objects.all().first() return render(request, 'app1/index.html', { 'sitewide':sitewide })
[ { "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
Project-Directory/app1/views.py
RonBulaon/DockeredDjangoNginx
from collections import OrderedDict from typing import Dict, List from models.base import ServerBase class Server(ServerBase): """服务端只做模型参数的融合 """ def __init__(self) -> None: super().__init__() self._params = None @property def params(self): return self._params @params.setter def params(self, params): self._params = params def __repr__(self) -> str: return "Server()"
[ { "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
models/FedGMF/server.py
TD21forever/QoS-Predcition-Algorithm-library
import numpy as np from grove.alpha.jordan_gradient.gradient_utils import binary_to_real, \ measurements_to_bf def test_binary_to_real(): for sign in [1, -1]: decimal_rep = sign * 0.345703125 binary_rep = str(sign * 0.010110001) decimal_convert = binary_to_real(binary_rep) assert(np.isclose(decimal_rep, decimal_convert)) def test_measurements_to_bf(): measurements = [[1, 0, 0], [1, 0, 0], [1, 1, 0], [1, 0, 0]] true_bf = 0.01 bf_from_measurements = measurements_to_bf(measurements) assert(np.isclose(true_bf, bf_from_measurements))
[ { "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
grove/tests/jordan_gradient/test_gradient_utils.py
msohaibalam/grove
""" Group all tests cases for layers""" import pytest import torch from polaris.network.layers import SqueezeExcitation, ResidualBlock2D def test_squeeze_excitation(): X = torch.tensor([[[[1.0, 2.0, 3.0], [4.0, 5.0, 6.0], [7.0, 8.0, 9.0]]]]) se = SqueezeExcitation(channels=1, ratio=1) se.dense_linear_1.weight.data = torch.tensor([[4.0]]) se.dense_linear_1.bias.data = torch.tensor([[2.0]]) se.dense_linear_2.weight.data = torch.tensor([[-0.1], [2.0]]) se.dense_linear_2.bias.data = torch.tensor([0.1, -3]) output = se(X) expected = torch.tensor([[[[41.109, 41.218, 41.327], [41.436, 41.545, 41.655], [41.764, 41.873, 41.982]]]]) assert pytest.approx(expected.detach().numpy(), abs=1e-3) == output.detach().numpy() def test_residual_block(): X = torch.tensor([[[[1.0, 2.0, 3.0], [4.0, 5.0, 6.0], [7.0, 8.0, 9.0]]]]) rb = ResidualBlock2D(channels=1, kernel_size=3, se_ratio=1) rb.conv_layer_1.weight.data = torch.tensor([[[[0.0, 1, 0.0], [1, 2, 1], [0.0, 1, 0.0]]]]) rb.conv_layer_2.weight.data = torch.tensor([[[[0.0, 1, 0.0], [1, 1, 1], [0.0, 1, 0.0]]]]) rb.batch_norm_1.weight.data = torch.tensor([0.1]) rb.batch_norm_2.weight.data = torch.tensor([1.0]) rb.squeeze_ex.dense_linear_1.weight.data = torch.tensor([[0.0]]) rb.squeeze_ex.dense_linear_1.bias.data = torch.tensor([[0.0]]) rb.squeeze_ex.dense_linear_2.weight.data = torch.tensor([[1.0], [1.0]]) rb.squeeze_ex.dense_linear_2.bias.data = torch.tensor([1.0, 0.0]) output = rb(X) expected = torch.tensor([[[[0.000, 1.351, 2.282], [3.535, 5.685, 6.340], [7.018, 9.076, 9.823]]]]) assert pytest.approx(expected.detach().numpy(), abs=1e-3) == output.detach().numpy()
[ { "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
polaris/tests/test_layers.py
leelastar/leelastar-training
from abc import ABC from datetime import datetime from pyramid.response import Response class BaseView(ABC): @staticmethod def json_response(json): """" :param dict | list json: :rtype: dict | list """ if isinstance(json, dict): result = BaseView._dict_response(json) elif isinstance(json, list): result = BaseView._list_response(json) else: result = json return result @staticmethod def empty_response(): """ :rtype: Response """ return Response(status=204) @staticmethod def options(): """ :rtype: Response """ return BaseView.empty_response() @staticmethod def _dict_response(_dict): """" :param dict _dict: :rtype: dict """ result = {} for key, value in _dict.items(): if isinstance(value, dict): result[key] = BaseView._dict_response(value) elif isinstance(value, list): result[key] = BaseView._list_response(value) elif isinstance(value, datetime): result[key] = value.strftime('%Y-%m-%d %H:%M:%S') else: result[key] = value return result @staticmethod def _list_response(_list): """" :param list _list: :rtype: list """ result = [] for value in _list: if isinstance(value, dict): result.append(BaseView._dict_response(value)) elif isinstance(value, list): result.append(BaseView._list_response(value)) elif isinstance(value, datetime): result.append(value.strftime('%Y-%m-%d %H:%M:%S')) else: result.append(value) return result def __init__(self, request): """ :param pyramid.request.Request request: """ self._request = request
[ { "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
backend/app/views/_base.py
scottsbergeron/pyramid-react-template
#!/usr/bin/env python import os try: from http.server import HTTPServer #python3 from socketserver import ThreadingMixIn except ImportError: from BaseHTTPServer import HTTPServer,BaseHTTPRequestHandler #python2 from SocketServer import ThreadingMixIn class MyHTTPServer(ThreadingMixIn,HTTPServer): def __init__(self,addr,handler,subnet): HTTPServer.__init__(self,addr,handler) self.subnet = subnet def verify_request(self,request,client_address): host, port = client_address #auto fill?? if not host.startswith(self.subnet): return False return HTTPServer.verify_request(self,request,client_address) class MyHandler(BaseHTTPRequestHandler): def do_GET(self): filename = os.path.basename(self.path[1:]) f = open(filename,'r') self.wfile.write(f.read()) f.close() serv = MyHTTPServer(('',8080),MyHandler,'127.0.0.') serv.serve_forever()
[ { "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
lang/py/rfc/22/myhttp.py
ch1huizong/learning
## # Copyright (c) 2007-2016 Apple 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. ## from caldavclientlibrary.protocol.http.session import Session from caldavclientlibrary.protocol.webdav.report import Report import unittest class TestRequest(unittest.TestCase): def test_Method(self): server = Session("www.example.com") request = Report(server, "/") self.assertEqual(request.getMethod(), "REPORT") class TestRequestHeaders(unittest.TestCase): pass class TestRequestBody(unittest.TestCase): pass class TestResponse(unittest.TestCase): pass class TestResponseHeaders(unittest.TestCase): pass class TestResponseBody(unittest.TestCase): pass
[ { "point_num": 1, "id": "every_class_has_docstring", "question": "Does every class in this file have a docstring?", "answer": false }, { "point_num": 2, "id": "more_functions_than_classes", "question": "Does this file define more functions than classes?", "answer": false }, {...
3
caldavclientlibrary/protocol/webdav/tests/test_report.py
LaudateCorpus1/ccs-caldavclientlibrary
from django.conf import settings import requests import socket BASE_HOST = '127.0.0.1' PORT = 4040 class Ngrok(object): def __init__(self, port=PORT, *args, **kwargs): super(Ngrok, self).__init__(*args, **kwargs) self.port = port self._check_launch_ngrok() def _check_launch_ngrok(self): s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((BASE_HOST, self.port)) # error handling: socket.error s.close() def get_public_url(self): if not settings.USE_NGROK: return None response = requests.get(f'http://{BASE_HOST}:{self.port}/api/tunnels').json() tunnels = response['tunnels'] tunnel = tunnels[1] public_url = tunnel['public_url'] return public_url
[ { "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/ngrok.py
nnsnodnb/line-bot-django-handle
import unittest from discrete_probability.concept.random_variable import RandomVariable, SetOfRandomVariable, Assignment, Conditional from discrete_probability.concept.event import Event class RandomVariableTestCase(unittest.TestCase): def test_name(self): name = 'A' self.assertEqual(RandomVariable(name).name, name) def test_assigned(self): self.assertFalse(RandomVariable('A').assigned) def test_assign(self): event = Event({1, 2, 3}) expected = Assignment('A', event) self.assertEqual(RandomVariable('A').assign(event), expected) def test___eq__(self): self.assertEqual(RandomVariable('A'), RandomVariable('A')) self.assertNotEqual(RandomVariable('A'), RandomVariable('B')) def test___eq__ellipsis(self): self.assertFalse(RandomVariable('A') == ...) def test___eq__assign(self): event = Event({1, 2, 3}) expected = Assignment('A', event) self.assertEqual(RandomVariable('A') == event, expected) def test___repr__(self): name = 'A' self.assertEqual(RandomVariable(name).__repr__(), name) def test_given(self): X, Y = RandomVariable('X'), RandomVariable('Y') X_barrado = SetOfRandomVariable((X, )) Y_barrado = SetOfRandomVariable((Y, )) expected = Conditional(X_barrado, Y_barrado) self.assertEqual(expected, X.given(Y)) def test___or___given(self): X, Y = RandomVariable('X'), RandomVariable('Y') X_barrado = SetOfRandomVariable((X, )) Y_barrado = SetOfRandomVariable((Y, )) expected = Conditional(X_barrado, Y_barrado) self.assertEqual(expected, X | Y)
[ { "point_num": 1, "id": "every_function_has_docstring", "question": "Does every function in this file have a docstring?", "answer": false }, { "point_num": 2, "id": "has_multiple_inheritance", "question": "Does any class in this file use multiple inheritance?", "answer": false ...
3
test/concept/test_random_variable.py
DiscreteProbability/DiscreteProbability
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. from typing import Tuple, Dict from augly.video.augmenters.ffmpeg import BaseFFMPEGAugmenter from ffmpeg.nodes import FilterableStream class VideoAugmenterByBrightness(BaseFFMPEGAugmenter): def __init__(self, level: float): assert -1.0 <= level <= 1.0, "Level must be a value in the range [-1.0, 1.0]" self.level = level def add_augmenter( self, in_stream: FilterableStream, **kwargs ) -> Tuple[FilterableStream, Dict]: """ Changes the brightness level of the video @param in_stream: the FFMPEG object of the video @returns: a tuple containing the FFMPEG object with the augmentation applied and a dictionary with any output arguments as necessary """ return in_stream.video.filter("eq", **{"brightness": self.level}), {}
[ { "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
augly/video/augmenters/ffmpeg/brightness.py
Ierezell/AugLy
# Copyright (c) Alex Ellis 2017. All rights reserved. # Licensed under the MIT license. See LICENSE file in the project root for full license information. from flask import Flask, request, jsonify from function import handler #from gevent.wsgi import WSGIServer from gevent.pywsgi import WSGIServer app = Flask(__name__) @app.before_request def fix_transfer_encoding(): """ Sets the "wsgi.input_terminated" environment flag, thus enabling Werkzeug to pass chunked requests as streams. The gunicorn server should set this, but it's not yet been implemented. """ transfer_encoding = request.headers.get("Transfer-Encoding", None) if transfer_encoding == u"chunked": request.environ["wsgi.input_terminated"] = True @app.route("/", defaults={"path": ""}, methods=["POST", "GET"]) @app.route("/<path:path>", methods=["POST", "GET"]) def main_route(path): ret = handler.handle(request) return jsonify(ret) if __name__ == '__main__': #app.run(host='0.0.0.0', port=5000, debug=False) http_server = WSGIServer(('', 5000), app) http_server.serve_forever()
[ { "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
template/python3-flask/index.py
AFCYBER-DREAM/piperci-noop-faas
import urllib from io import BytesIO import requests from flask import (Blueprint, current_app, jsonify, make_response, render_template, request) from .helpers import prepare_image_for_json bp = Blueprint('routes', __name__, url_prefix='') @bp.route('/', methods=['GET']) def home(): return render_template('home.html') @bp.route('/inpaint', methods=['GET', 'POST']) def inpaint(): if request.method == 'POST': prepared_image = prepare_image_for_json(request.files['image']) json = {'image': prepared_image} url = current_app.config.get('INPAINT_API_URL') + 'api/inpaint' api_response = requests.post( url, json=json, timeout=60) return make_response(jsonify(api_response.json()), 200) elif request.method == 'GET': return render_template('inpaint.html') @bp.route('/cut', methods=['GET', 'POST']) def cut(): if request.method == 'POST': prepared_image = prepare_image_for_json(request.files['image']) json = {'image': prepared_image} url = current_app.config.get('INPAINT_API_URL') + 'api/cut' api_response = requests.post( url, json=json, timeout=60) return make_response(jsonify(api_response.json()), 200) elif request.method == 'GET': return render_template('cut.html') @bp.route('/mask', methods=['GET', 'POST']) def mask(): if request.method == 'POST': prepared_image = prepare_image_for_json(request.files['image']) json = {'image': prepared_image} url = current_app.config.get('INPAINT_API_URL') + 'api/mask' api_response = requests.post( url, json=json, timeout=60) return make_response(jsonify(api_response.json()), 200) elif request.method == 'GET': return render_template('mask.html')
[ { "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
demo_site/routes.py
ArtemiiH/ppl_eraser_demo_site
from django.contrib.auth.backends import ModelBackend from ratelimitbackend.backends import RateLimitMixin from .profiles.models import User from .utils import is_email class CaseInsensitiveModelBackend(ModelBackend): def authenticate(self, username, password, request): try: user = User.objects.get(username__iexact=username) except User.DoesNotExist: return None else: if user.check_password(password): return user class RateLimitMultiBackend(RateLimitMixin, CaseInsensitiveModelBackend): """A backend that allows login via username or email, rate-limited.""" def authenticate(self, username=None, password=None, request=None): if is_email(username): try: username = User.objects.get(email__iexact=username).username except User.DoesNotExist: pass return super().authenticate( username=username, password=password, request=request, )
[ { "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": true }, { ...
3
feedhq/backends.py
feedhq/feedhq
# encoding: utf-8 """ config_file_backing_store.py Created by Scott on 2014-08-12. Copyright (c) 2014 Scott Rice. All rights reserved. """ import ConfigParser import backing_store class ConfigFileBackingStore(backing_store.BackingStore): def __init__(self, path): super(ConfigFileBackingStore, self).__init__(path) self.configParser = ConfigParser.RawConfigParser() self.configParser.read(self.path) def identifiers(self): return self.configParser.sections() def add_identifier(self, ident): try: self.configParser.add_section(ident) except ConfigParser.DuplicateSectionError: raise ValueError("The identifier `%s` already exists" % str(ident)) def remove_identifier(self, ident): self.configParser.remove_section(ident) def keys(self, ident): try: return self.configParser.options(ident) except ConfigParser.NoSectionError: raise ValueError("No identifier named `%s` exists" % str(ident)) def get(self, ident, key, default=None): try: val = self.configParser.get(ident, key.lower()) return val if val != "" else default except ConfigParser.NoOptionError: return default def set(self, ident, key, value): self.configParser.set(ident, key.lower(), value) def save(self): try: with open(self.path, "w") as configFile: self.configParser.write(configFile) except IOError: raise IOError("Cannot save data to `%s`. Permission Denied")
[ { "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
src/ice/persistence/config_file_backing_store.py
geraldhumphries/Ice
import tensorflow as tf from tensorflow.keras.models import Sequential from tensorflow.keras.layers import Dense, Dropout, Activation, Flatten, Conv2D, MaxPooling2D from tensorflow.keras.callbacks import TensorBoard import pickle, os, time DATADIR="data/" NAME="cachorros-gatos-cnn-128-128-128-{}".format(int(time.time())) tensorboard = TensorBoard(log_dir="logs/{}".format(NAME)) gpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=0.4) sess = tf.Session(config=tf.ConfigProto(gpu_options=gpu_options)) def getData(): X = pickle.load(open(DATADIR + "X.pickle", "rb")) y = pickle.load(open(DATADIR + "y.pickle", "rb")) return X, y def normalizeData(X): return X/255.0 # já que numa imagem o valor máximo é 255 para cada pixels, é só dividir por 255. def saveModel(model): model.save("128-128-128-CNN-noDense.model") def trainModel(model, training_set): X, y = training_set model.compile(loss="binary_crossentropy", optimizer="adam", metrics=["accuracy"]) model.fit(X, y, batch_size=32, validation_split=0.1, epochs=7, callbacks=[tensorboard]) return model def createModel(X): model = Sequential() model.add(Conv2D(128, (3,3), input_shape=X.shape[1:])) model.add(Activation("relu")) model.add(MaxPooling2D(pool_size=(2, 2))) model.add(Conv2D(128, (4,4))) model.add(Activation("relu")) model.add(MaxPooling2D(pool_size=(2, 2))) model.add(Conv2D(128, (3,3))) model.add(Activation("relu")) model.add(MaxPooling2D(pool_size=(2, 2))) model.add(Flatten()) model.add(Dense(1)) model.add(Activation("sigmoid")) return model def main(): X, y = getData() X = normalizeData(X) model = createModel(X) model = trainModel(model, (X, y)) #saveModel(model) main()
[ { "point_num": 1, "id": "every_function_has_docstring", "question": "Does every function in this file have a docstring?", "answer": false }, { "point_num": 2, "id": "every_function_under_20_lines", "question": "Is every function in this file shorter than 20 lines?", "answer": fal...
3
src/backend/model.py
inacioMattos/DeepLearning-Cachorros-e-Gatos
from django.db import models from django.contrib.auth.models import User # Create your models here. class GoalStatus(models.Model): status_name = models.CharField(max_length=200) def __str__(self): return self.status_name class ScrumyGoals(models.Model): #goal_name, goal_id, created_by, moved_by, owner goal_id = models.BigIntegerField() goal_name = models.CharField(max_length=200) created_by = models.CharField(max_length=200) moved_by = models.CharField(max_length=200) owner = models.CharField(max_length=200) goal_status = models.ForeignKey( GoalStatus, on_delete=models.PROTECT, related_name='goalstatus') user = models.ForeignKey( User, on_delete=models.PROTECT, related_name='scrumygoals') def __str__(self): return self.goal_name class ScrumyHistory(models.Model): #moved_by, created_by, moved_from, moved_to, time_of_action created_by = models.CharField(max_length=200) moved_by = models.CharField(max_length=200) moved_from = models.CharField(max_length=200) moved_to = models.CharField(max_length=200) time_of_action = models.CharField(max_length=200) goal = models.ForeignKey(ScrumyGoals, on_delete=models.PROTECT) def __str__(self): return self.created_by
[ { "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_class_has_docstring", "question": "Does every class in this file have a docstring?", "answer": false }, ...
3
django-semiuscrumy1/semiuscrumy/models.py
trustidkid/myscrumy
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # License: GNU General Public License v3. See license.txt import json import frappe def execute(): frappe.reload_doc('crm', 'doctype', 'lead') frappe.reload_doc('crm', 'doctype', 'opportunity') add_crm_to_user_desktop_items() def add_crm_to_user_desktop_items(): key = "_user_desktop_items" for user in frappe.get_all("User", filters={"enabled": 1, "user_type": "System User"}): user = user.name user_desktop_items = frappe.db.get_defaults(key, parent=user) if user_desktop_items: user_desktop_items = json.loads(user_desktop_items) if "CRM" not in user_desktop_items: user_desktop_items.append("CRM") frappe.db.set_default(key, json.dumps(user_desktop_items), parent=user)
[ { "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
frappe-bench/apps/erpnext/erpnext/patches/v5_0/new_crm_module.py
Semicheche/foa_frappe_docker
""" cfg_loader.fields ~~~~~~~~~~~~~~~~~ Implement marshmallow fields to validate against specific input data :copyright: Copyright 2017 by ConsenSys France. :license: BSD, see :ref:`license` for more details. """ import os from marshmallow import validate, fields class PathValidator(validate.Validator): """Validate a path. :param error: Error message to raise in case of a validation error. Can be interpolated with `{input}`. :type error: str """ default_message = 'Path "{input}" does not exist' def __init__(self, error=None): self.error = error or self.default_message def _format_error(self, value): return self.error.format(input=value) def __call__(self, value): message = self._format_error(value) if not os.path.exists(value): raise validate.ValidationError(message) return value class Path(fields.String): """A validated path field. Validation occurs during both serialization and deserialization. :param args: The same positional arguments that :class:`~marshmallow.fields.String` receives. :param kwargs: The same keyword arguments that :class:`~marshmallow.fields.String` receives. """ default_error_messages = {'invalid_path': 'Path "{input}" does not exist'} def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) # Insert validation into self.validators so that multiple errors can be self.validators.append(PathValidator(error=self.error_messages['invalid_path'])) class UnwrapNested(fields.Nested): """Nested fields class that will unwrapped at deserialization Useful when used with UnwrapSchema :param prefix: Optional prefix to add to every key when unwrapping a field :type prefix: str """ def __init__(self, *args, prefix='', **kwargs): self.prefix = prefix super().__init__(*args, **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": "more_functions_than_classes", "question": "Does this file define more functions than clas...
3
cfg_loader/fields.py
theatro/cfg-loader
class HTTPException(Exception): """ Exception which happens when HTTP status code is not 200 (OK). """ def __init__(self, code, url) -> None: self.error = f"While requesting to {url}, request returned status {code}." def __str__(self) -> str: return self.error class NoCatalogResult(Exception): """ Exception which happens when there is no product with given product id. """ def __init__(self, product_id) -> None: self.error = f"There is no catalog result with id {product_id}." def __str__(self) -> str: return self.error
[ { "point_num": 1, "id": "every_class_has_docstring", "question": "Does every class in this file have a docstring?", "answer": true }, { "point_num": 2, "id": "all_return_types_annotated", "question": "Does every function in this file have a return type annotation?", "answer": tru...
3
pyapple/interface/exceptions.py
fxrcha/PyApple
from typing import Dict, List, Optional from pydantic import BaseModel class SetuData(BaseModel): title: str urls: Dict[str, str] author: str tags: List[str] pid: int p: int r18: bool class SetuApiData(BaseModel): error: Optional[str] data: List[SetuData] class Setu: def __init__(self, data: SetuData): self.title: str = data.title self.urls: Dict[str, str] = data.urls self.author: str = data.author self.tags: List[str] = data.tags self.pid: int = data.pid self.p: int = data.p self.r18: bool = data.r18 self.img: Optional[bytes] = None self.msg: Optional[str] = None class SetuMessage(BaseModel): send: List[str] cd: List[str] class SetuNotFindError(Exception): pass
[ { "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
nonebot_plugin_setu_now/models.py
kexue-z/nonebot-plugin-setu-now
import unittest import os import pytest import testinfra.utils.ansible_runner class TestIntermediateSetup(unittest.TestCase): def setUp(self): self.host = testinfra.utils.ansible_runner.AnsibleRunner( os.environ['MOLECULE_INVENTORY_FILE']).get_host('instance') @pytest.mark.parametrize('file, content', [ "/Users/vagrant/Library/LaunchAgents/bitrise.io.tools.keychain-unlocker.plist", "bitrise.io.tools.keychain-unlocker", "/opt/bitrise/unlock_keychain.sh", "#!/bin/bash" ]) def test_keychain_unlocker_files(self, file, content): file = self.host.file(file) assert file.exists assert file.contains(content) @pytest.mark.parametrize('file, content', [ "/Users/vagrant/logs/bitrise.io.tools.keychain-unlocker.log", "Successfully unlocked login.keychain" ]) def test_keychain_unlocker_has_run(self, file, content): file = host.file(file) assert file.exists assert file.contains(content)
[ { "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
roles/keychain/tests/test_keychain.py
nimi0112/osx-box-bootstrap
import unittest from my_program import make_it_uppercase, get_first_word, return_a_list class TestMyProgram(unittest.TestCase): def test_hello_world(self): result = make_it_uppercase("hello world") self.assertEqual(result, 'HELLO WORLD') def test_first_word_in_sentence(self): sentence = "Lorem ipsum dolor sit amet, consectetur adipisicing elit. Veniam laboriosam consequatur saepe. Repellat itaque dolores neque, impedit reprehenderit eum culpa voluptates harum sapiente nesciunt ratione." result = get_first_word(sentence) self.assertEqual(result, 'Lorem') def test_first_word_in_sentence_with_one_word(self): sentence = "Lorem" result = get_first_word(sentence) self.assertEqual(result, 'Lorem') def test_return_a_list(self): result = return_a_list() self.assertListEqual( result, ['Cats', 'Dogs', 'Birds'], "THE LIST WAS WRONG!!", ) 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": "all_function_names_snake_case", "question": "Are all function names in this file written in snake_case?", "answer": ...
3
630_Unit_Tests/tests.py
PacktPublishing/Python-for-Everybody-The-Ultimate-Python-3-Bootcamp
# # iris data set # 150 total entries # features are: sepal length in cm, sepal width in cm, petal length in cm, petal width in cm\n # labels names: setosa, versicolor, virginica # # used algorithm: SVC (C-Support Vector Classifiction) # # accuracy ~100% # from time import time import numpy as np from sklearn.datasets import load_iris from sklearn import svm from sklearn.metrics import accuracy_score def main(): data_set = load_iris() features, labels = split_features_labels(data_set) train_features, train_labels, test_features, test_labels = split_train_test(features, labels, 0.18) print(len(train_features), " ", len(test_features)) clf = svm.SVC() print("Start training...") t_start = time() clf.fit(train_features, train_labels) print("Training time: ", round(time() - t_start, 3), "s") print("Accuracy: ", accuracy_score(clf.predict(test_features), test_labels)) def split_train_test(features, labels, test_size): total_test_size = int(len(features) * test_size) np.random.seed(2) indices = np.random.permutation(len(features)) train_features = features[indices[:-total_test_size]] train_labels = labels[indices[:-total_test_size]] test_features = features[indices[-total_test_size:]] test_labels = labels[indices[-total_test_size:]] return train_features, train_labels, test_features, test_labels def split_features_labels(data_set): features = data_set.data labels = data_set.target return features, labels if __name__ == "__main__": main()
[ { "point_num": 1, "id": "all_params_annotated", "question": "Does every function parameter in this file have a type annotation (excluding self/cls)?", "answer": false }, { "point_num": 2, "id": "all_function_names_snake_case", "question": "Are all function names in this file written ...
3
iris_svc.py
LSchultebraucks/support-vector-machines-blog-post
""" @brief test log(time=150s) """ import os import unittest from pyquickhelper.loghelper import fLOG from pyquickhelper.pycode import check_pep8, ExtTestCase class TestCodeStyle(ExtTestCase): """Test style.""" def test_style_src(self): thi = os.path.abspath(os.path.dirname(__file__)) src_ = os.path.normpath(os.path.join(thi, "..", "..", "src")) check_pep8(src_, fLOG=fLOG, pylint_ignore=('C0103', 'C1801', 'R0201', 'R1705', 'W0108', 'W0613', 'C0111', 'W0223', 'W0201', 'W0212', 'C0415', 'C0209'), skip=["Parameters differ from overridden 'fit' method", "Module 'numpy.random' has no 'RandomState' member", "Instance of 'SkLearnParameters' has no '", " in module 'sklearn.cluster._k_means'", "Instance of 'Struct' has no '", ]) def test_style_test(self): thi = os.path.abspath(os.path.dirname(__file__)) test = os.path.normpath(os.path.join(thi, "..", )) check_pep8(test, fLOG=fLOG, neg_pattern="temp_.*", pylint_ignore=('C0103', 'C1801', 'R0201', 'R1705', 'W0108', 'W0613', 'C0111', 'W0612', 'E0632', 'C0415', 'C0209'), skip=["Instance of 'tuple' has no ", ]) if __name__ == "__main__": unittest.main()
[ { "point_num": 1, "id": "has_multiple_inheritance", "question": "Does any class in this file use multiple inheritance?", "answer": false }, { "point_num": 2, "id": "more_functions_than_classes", "question": "Does this file define more functions than classes?", "answer": true },...
3
_unittests/ut_module/test_code_style.py
sdpython/papierstat
#! /usr/bin/env python3 # -*- coding: utf-8 -*- import unittest from happy_python import bytearray_to_str, gen_random_str, to_hex_str1, is_ascii_str, to_hex_str2, \ from_hex_str from happy_python import bytes_to_str from happy_python import dict_to_str from happy_python import str_to_dict class TestUtils(unittest.TestCase): def test_bytes_to_str(self): result = bytes_to_str(b'test') self.assertEqual(result, 'test') def test_bytearray_to_str(self): result = bytearray_to_str(bytearray(b'test')) self.assertEqual(result, 'test') def test_str_to_dict(self): result = str_to_dict('{"code": 1}') self.assertEqual(result, {"code": 1}) def test_dict_to_str(self): result = dict_to_str({"code": 1}) self.assertEqual(result, '{"code": 1}') def test_random_str(self): result = gen_random_str(11) self.assertEqual(11, len(result)) def test_to_hex_str1(self): self.assertEqual(to_hex_str1('abcde'), '6162636465') self.assertEqual(to_hex_str1('abcde', True, ' '), '61 62 63 64 65') def test_to_hex_str2(self): self.assertEqual(to_hex_str2('abcde'.encode('utf-8')), '6162636465') self.assertEqual(to_hex_str2('Hello World'.encode('utf-8')), '48656C6C6F20576F726C64') self.assertEqual(to_hex_str2('abcde'.encode('utf-8'), True, ' '), '61 62 63 64 65') self.assertEqual(to_hex_str2( 'Hello World'.encode('utf-8'), True, ' '), '48 65 6C 6C 6F 20 57 6F 72 6C 64') def test_is_ascii_str(self): self.assertTrue(is_ascii_str('ab123--')) self.assertFalse(is_ascii_str('测试')) def test_from_hex_str(self): self.assertEqual(from_hex_str('0x0E0x0A'), b'\x0e\n') self.assertEqual(from_hex_str('0E 0A', ' '), b'\x0e\n')
[ { "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/str_util_test.py
geekcampchina/happy-python
import itertools def turn(face, dir): nface=face[:] if dir==1: nface=[0, face[2],face[6],face[3],face[1],face[5],face[4]] if dir==2: nface=[0, face[3],face[2],face[6],face[4],face[1],face[5]] if dir==3: nface=[0, face[4],face[1],face[3],face[6],face[5],face[2]] if dir==4: nface=[0, face[5],face[2],face[1],face[4],face[6],face[3]] return nface def dfs(si, nowface): global link, visited result=True visited[si]=True if nowface[1] != si: return False for dir in range(1,5): if link[si][dir] and not visited[link[si][dir]]: face = turn(nowface, dir) result = result and dfs(link[si][dir], face) return result x=[[0]*8] for i in range(6): x.append([0] + list(map(int,input().split())) + [0]) x.append([0]*8) link=[[None]*5 for i in range(10)] for i in range(1, 7): for j in range(1, 7): if x[i][j]: if x[i-1][j]: link[x[i][j]][1]=x[i-1][j] if x[i+1][j]: link[x[i][j]][3]=x[i+1][j] if x[i][j-1]: link[x[i][j]][4]=x[i][j-1] if x[i][j+1]: link[x[i][j]][2]=x[i][j+1] for i in itertools.permutations(map(int,'123456'), 6): face=list((0,)+i) visited=[0]*7 if dfs(face[1], face) and sum(visited)>=6: print(face[6]) exit(0) print(0)
[ { "point_num": 1, "id": "every_function_has_docstring", "question": "Does every function in this file have a docstring?", "answer": false }, { "point_num": 2, "id": "no_function_exceeds_5_params", "question": "Does every function in this file take 5 or fewer parameters (excluding sel...
3
problem/01000~09999/02642/2642.py3.py
njw1204/BOJ-AC
from datetime import datetime from decimal import Decimal from typing import Tuple, List from gps import gps, WATCH_ENABLE, WATCH_NEWSTYLE from . import constants as c from .location import Location class GPSD: gpsd = gps(mode=WATCH_ENABLE | WATCH_NEWSTYLE) @classmethod def get_location(cls) -> Location: """Create a new Location object based on the GPS coordinates""" latitude, longitude, datetime_ = GPSD._get_coordinates() return Location(latitude, longitude, datetime_) @classmethod def _get_coordinates(cls) -> Tuple[Decimal, Decimal, datetime]: """Get GPS coordinates as an average of the coordinates since last time it was collected""" time = datetime.utcnow().strftime(c.DATETIME_FORMAT) needed = {"lat", "lon", "time"} coords = {"lat", "lon"} lats = [] lons = [] location = cls.gpsd.next() keys = set(location) while needed - keys or time > location.time: if not coords - keys: lats.append(Decimal(location.lat)) lons.append(Decimal(location.lon)) location = cls.gpsd.next() keys = set(location) location_time = datetime.strptime(location.time, c.DATETIME_FORMAT) return cls._avg(lats), cls._avg(lons), location_time @staticmethod def _avg(items: List[Decimal]) -> Decimal: """Return the average value of a list of Decimals""" try: return sum(items) / len(items) except ZeroDivisionError: return Decimal(0)
[ { "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": tru...
3
client/gps_tracker/gpsd.py
jorgemira/gps_tracker
# -*- coding: utf-8 -*- """ shellstreaming.util.resource ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :synopsis: Reports HW resource info """ # standard modules import time # 3rd party moduels import psutil _cpu_percent_called = False def avail_cores(): """Return number of available cores on the node""" # Since :func:`psutil.cpu_percent()` is implemented to compare cpu time of current & previous call, # 1st result of this function is not necessarily relavant to shellstreaming itself. global _cpu_percent_called if not _cpu_percent_called: psutil.cpu_percent(interval=0, percpu=True) _cpu_percent_called = True time.sleep(0.1) ret = 0 for core_usage in psutil.cpu_percent(interval=0, percpu=True): if core_usage < 20.0: # [todo] - change parameter to calc available cores? ret += 1 return ret def avail_memory_byte(): # [todo] - after implementing memory controller (which evicts data into disk sometimes), # [todo] - file cache would be important. Then `free` is better to use than `available` return psutil.virtual_memory().available
[ { "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
shellstreaming/util/resource.py
laysakura/shellstreaming
# SPDX-FileCopyrightText: 2022 Tim Hawes <me@timhawes.com> # # SPDX-License-Identifier: MIT from django.contrib import admin from .models import ChangeOfAddress, GroupPolicy, MailingList class GroupPolicyInline(admin.TabularInline): model = GroupPolicy fields = ("group", "policy", "prompt") extra = 0 def groups(obj): return [policy.group.name for policy in obj.group_policies.order_by("group__name")] groups.short_description = "Groups" @admin.register(MailingList) class MailingListAdmin(admin.ModelAdmin): list_display = ( "name", "description", "advertised", "subscribe_policy", groups, "auto_unsubscribe", ) ordering = ("name",) readonly_fields = ( "name", "description", "info", "advertised", "subscribe_policy", "archive_private", "subscribe_auto_approval", ) inlines = (GroupPolicyInline,) @admin.register(ChangeOfAddress) class ChangeOfAddressAdmin(admin.ModelAdmin): list_display = ("created", "user", "old_email", "new_email") ordering = ("created",) readonly_fields = ("created", "user", "old_email", "new_email")
[ { "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
mailman2/admin.py
edinburghhacklab/hackdb
#!/usr/bin/env python3 import trio async def a(): print('enter a') await trio.sleep(0) print('leave a') async def b(): print('enter b') await trio.sleep(0) print('leave b') async def main(): async with trio.open_nursery() as nursery: print(nursery.start_soon(a)) nursery.start_soon(b) # seems like the output order is non-deterministic if __name__ == '__main__': trio.run(main)
[ { "point_num": 1, "id": "has_nested_function_def", "question": "Does this file contain any function defined inside another function?", "answer": false }, { "point_num": 2, "id": "all_function_names_snake_case", "question": "Are all function names in this file written in snake_case?",...
3
trio-stuff/interleaved_output.py
bmintz/python-snippets
import os import sys from clint.textui import puts, colored import conf def display_intro(): print_message(''' __ ____ ____ ___ _____ __ ___ _______ __ / / / ___|| _ \\ / _ \\_ _| \\ \\ |_ _| ___\\ \\ / / | | \\___ \\| |_) | | | || | | | | || |_ \\ V / | | ___) | __/| |_| || | | | | || _| | | | | |____/|_| \\___/ |_| | | |___|_| |_| \\_\\ /_/ Welcome to Spotted on Spotify!\n''', color='green') def print_message(message, color='white', exit=False): color_map = { 'cyan' : colored.cyan, 'green' : colored.green, 'red' : colored.red, 'white' : colored.white, 'yellow' : colored.yellow } puts(color_map[color](message)) if exit: if os.path.isfile(conf.YOUTUBE_DL_OPTS['outtmpl']): os.remove(conf.YOUTUBE_DL_OPTS['outtmpl']) sys.exit(1)
[ { "point_num": 1, "id": "every_function_has_docstring", "question": "Does every function in this file have a docstring?", "answer": false }, { "point_num": 2, "id": "no_function_exceeds_5_params", "question": "Does every function in this file take 5 or fewer parameters (excluding sel...
3
spotted_on_spotify/util.py
anthonymirand/SpottedOnSpotify-cmdline
from collections import OrderedDict import re from dockerfile_parse import DockerfileParser from dockerfile_parse.constants import COMMENT_INSTRUCTION # class CheckovDockerFileParser(DockerfileParser) from checkov.common.comment.enum import COMMENT_REGEX def parse(filename): dfp = DockerfileParser(path=filename) return dfp_group_by_instructions(dfp) def dfp_group_by_instructions(dfp): result = OrderedDict() for instruction in dfp.structure: instruction_literal = instruction["instruction"] if instruction_literal not in result: result[instruction_literal] = [] result[instruction_literal].append(instruction) return result, dfp.lines def collect_skipped_checks(parse_result): skipped_checks = [] if COMMENT_INSTRUCTION in parse_result: for comment in parse_result[COMMENT_INSTRUCTION]: skip_search = re.search(COMMENT_REGEX, comment["value"]) if skip_search: skipped_checks.append( { 'id': skip_search.group(2), 'suppress_comment': skip_search.group(3)[1:] if skip_search.group( 3) else "No comment provided" } ) return skipped_checks
[ { "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
checkov/dockerfile/parser.py
kylelaker/checkov
from __future__ import print_function _ = raw_input() words = [set(w) for w in raw_input().split()] result = 0 def search(words, layer=0): global result if len(words) + layer <= result: # simple cut return if layer > result: result = layer def isConflict(word1, word2): return any(c1 in word2 for c1 in word1) for i in range(len(words)): nw = [w for w in words[i + 1:] if not isConflict(words[i], w)] search(nw, layer + 1) search(words) print(result)
[ { "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_nested_function_def", "question": "Does this file contain any function defined insid...
3
0000 hihoOnce/170 Word Construction/main.py
SLAPaper/hihoCoder
# -*- coding: utf-8 -*- """Python e GTK 4: PyGObject Gtk.Calendar().""" import gi gi.require_version(namespace='Gtk', version='4.0') from gi.repository import Gio, Gtk class MainWindow(Gtk.ApplicationWindow): def __init__(self, **kwargs): super().__init__(**kwargs) self.set_title(title='Python e GTK 4: PyGObject Gtk.Calendar()') # Tamanho inicial da janela. self.set_default_size(width=1366 / 2, height=768 / 2) # Tamanho minimo da janela. self.set_size_request(width=1366 / 2, height=768 / 2) vbox = Gtk.Box.new(orientation=Gtk.Orientation.VERTICAL, spacing=12) vbox.set_homogeneous(homogeneous=True) # No GTK 3: set_border_width(). vbox.set_margin_top(margin=12) vbox.set_margin_end(margin=12) vbox.set_margin_bottom(margin=12) vbox.set_margin_start(margin=12) # Adicionando o box na janela principal. # No GTK 3: add(). self.set_child(child=vbox) calendar = Gtk.Calendar.new() # calendar.connect('day-selected-double-click', self.day_double_click) calendar.connect('day-selected', self.day_double_click) vbox.append(child=calendar) def on_day_selected(self, calendar): date = calendar.get_date() print(f'Dia: {date.get_day_of_month()}') print(f'Mês: {date.get_month()}') print(f'Ano: {date.get_year()}') class Application(Gtk.Application): def __init__(self): super().__init__(application_id='br.natorsc.Exemplo', flags=Gio.ApplicationFlags.FLAGS_NONE) def do_startup(self): Gtk.Application.do_startup(self) def do_activate(self): win = self.props.active_window if not win: win = MainWindow(application=self) win.present() def do_shutdown(self): Gtk.Application.do_shutdown(self) if __name__ == '__main__': import sys app = Application() app.run(sys.argv)
[ { "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_class_has_docstring", "question": "Does every class in this file have a docstring?", "answer": false }, ...
3
src/gtk4/calendar/MainWindow.py
natorsc/gui-python-gtk
from lib.compileException import compileException class WhileStmtNode(): def __init__(self, stmt_type=None, expr=None, block=None, line=None ): self.stmt_type = stmt_type self.expr = expr self.block = block self.line = line self.return_type = None def checkType(self, s): expr_type = self.expr.checkType(s) if expr_type not in ["int", "boolean"]: raise compileException(f"Condition must bo of type int/boolean cant be {expr_type} :C",self.line) self.block.checkType(s) def text(self): print(f"While stmt: ") self.expr.text() print(f" ") print(f"[{self.block.text()}]") def checkReturn(self,s,fun): # print(f"WHILE ->\n\n") self.return_type = self.block.checkReturn(s,fun) if self.return_type is not None: return self.return_type if self.expr.const == True: self.return_type = "inf" return self.return_type
[ { "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
src/lib/WhileStmtNode.py
Amtoniusz/latte
# -*- coding: utf-8 -*- """ mod: api version: v1 """ from flask import ( Flask, Blueprint, request, session, g, redirect, url_for, abort, render_template, flash, current_app, make_response ) from flask_restful import reqparse, abort, Resource, Api bp = Blueprint(__name__, __name__, url_prefix='/api') api = Api(prefix='/v1', app=bp) TODOS = { 'todo1': {'task': 'build an API'}, 'todo2': {'task': '?????'}, 'todo3': {'task': 'profit!'}, } def abort_if_todo_doesnt_exist(todo_id): if todo_id not in TODOS: abort(404, message="Todo {} doesn't exist".format(todo_id)) parser = reqparse.RequestParser() parser.add_argument('task', type=str) # show a single todos item and lets you delete them class Todo(Resource): def get(self, todo_id): abort_if_todo_doesnt_exist(todo_id) return TODOS[todo_id] def delete(self, todo_id): abort_if_todo_doesnt_exist(todo_id) del TODOS[todo_id] return '', 204 def put(self, todo_id): args = parser.parse_args() task = {'task': args['task']} TODOS[todo_id] = task return task, 201 # shows a list of all todos, and lets you POST to add new tasks class TodoList(Resource): def get(self): return TODOS def post(self): args = parser.parse_args() todo_id = int(max(TODOS.keys()).lstrip('todo')) + 1 todo_id = 'todo%i' % todo_id TODOS[todo_id] = {'task': args['task']} return TODOS[todo_id], 201 # Actually setup the Api resource routing here # api.add_resource(TodoList, 'todos', endpoint='todos') api.add_resource(TodoList, '/todos') api.add_resource(Todo, '/todos/<todo_id>')
[ { "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
blueprints/api_v1.py
gaohongsong/flask-demo
#!/usr/bin/env python3 """ Convert COCO17 2D poses to dummy embeddings for 2D-VPD. """ import os import argparse import numpy as np from tqdm import tqdm from util.io import store_pickle, load_gz_json from vipe_dataset.dataset_base import normalize_2d_skeleton def get_args(): parser = argparse.ArgumentParser() parser.add_argument('pose_dir', type=str) parser.add_argument('-o', '--out_dir', type=str) parser.add_argument('--no_flip', action='store_true') return parser.parse_args() def main(pose_dir, out_dir, no_flip): for video_name in tqdm(sorted(os.listdir(pose_dir))): if video_name.endswith('.json.gz'): # Flat case video_pose_path = os.path.join(pose_dir, video_name) video_name = video_name.split('.json.gz')[0] else: # Nested case video_pose_path = os.path.join( pose_dir, video_name, 'coco_keypoints.json.gz') if not os.path.exists(video_pose_path): print('Not found:', video_pose_path) continue embs = [] for frame_num, pose_data in load_gz_json(video_pose_path): raw_2d = np.array(pose_data[0][-1]) pose_2d = normalize_2d_skeleton(raw_2d, False, to_tensor=False) emb = pose_2d[:, :2].flatten() # drop confidence column meta = {'is_2d': True, 'kp_score': np.mean(pose_2d[:, 2] + 0.5).item()} if not no_flip: emb2 = normalize_2d_skeleton( raw_2d, True, to_tensor=False)[:, :2].flatten() emb = np.stack([emb, emb2]) embs.append((frame_num, emb, meta)) if out_dir is not None: os.makedirs(out_dir, exist_ok=True) store_pickle(os.path.join(out_dir, video_name + '.emb.pkl'), embs) print('Done!') if __name__ == '__main__': main(**vars(get_args()))
[ { "point_num": 1, "id": "every_function_under_20_lines", "question": "Is every function in this file shorter than 20 lines?", "answer": false }, { "point_num": 2, "id": "no_function_exceeds_5_params", "question": "Does every function in this file take 5 or fewer parameters (excluding...
3
dummy_2d_features.py
jhong93/vpd
"""inline_tags Revision ID: a92d92aa678e Revises: e7004224f284 Create Date: 2018-05-10 15:41:28.053237 """ import re from funcy import flatten, compact from alembic import op import sqlalchemy as sa from sqlalchemy.dialects import postgresql from redash import models # revision identifiers, used by Alembic. revision = "a92d92aa678e" down_revision = "e7004224f284" branch_labels = None depends_on = None def upgrade(): op.add_column( "dashboards", sa.Column("tags", postgresql.ARRAY(sa.Unicode()), nullable=True) ) op.add_column( "queries", sa.Column("tags", postgresql.ARRAY(sa.Unicode()), nullable=True) ) def downgrade(): op.drop_column("queries", "tags") op.drop_column("dashboards", "tags")
[ { "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
migrations/versions/a92d92aa678e_inline_tags.py
zero1number/redash
from flask import Flask, render_template, redirect from jinja2 import Template from splinter import browser from flask_pymongo import PyMongo import scrape_mars # Create an instance of our Flask app. app = Flask(__name__) # Use flask_pymongo to set up mongo connection app.config["MONGO_URI"] = "mongodb://localhost:27017/mars_app" mongo = PyMongo(app) mongo.db.mars_page.drop() # Set route @app.route("/") def home(): mars_page = mongo.db.mars_page.find_one() return render_template("index.html", mars_page = mars_page) # Set route @app.route("/scrape") def scraper(): mars_page = mongo.db.mars_page mars_page_data = scrape_mars.scrape() mars_page.update({}, mars_page_data, upsert=True) return redirect("/", code=302) if __name__ == "__main__": app.run(debug=True)
[ { "point_num": 1, "id": "has_nested_function_def", "question": "Does this file contain any function defined inside another function?", "answer": false }, { "point_num": 2, "id": "every_function_under_20_lines", "question": "Is every function in this file shorter than 20 lines?", ...
3
app.py
computercavemen/web-scraping-challenge
import unittest import numpy import nlcpy from nlcpy import testing import nlcpy as vp nan_dtypes = ( numpy.float32, numpy.float64, numpy.complex64, numpy.complex128, ) shapes = ( (4,), (3, 4), (2, 3, 4), ) @testing.parameterize(*( testing.product({ 'shape': shapes, }) )) class TestQuantile(unittest.TestCase): @testing.for_dtypes(['i', 'q', 'f', 'd', 'F', 'D']) @testing.numpy_nlcpy_array_equal() def test_case_00(self, xp, dtype): a = testing.shaped_random(self.shape, xp, dtype) a = xp.asarray(a) return xp.quantile(a, 0.5) @testing.for_dtypes(['i', 'q', 'f', 'd', 'F', 'D']) @testing.numpy_nlcpy_array_equal() def test_case_01(self, xp, dtype): a = testing.shaped_random(self.shape, xp, dtype) a = xp.asarray(a) return xp.quantile(a, 0.5, axis=0) @testing.numpy_nlcpy_array_equal() def test_me_case_1(self, xp): a = xp.array([[10, 7, 4], [3, 2, 1]]) return xp.quantile(a, 0.5) @testing.numpy_nlcpy_array_equal() def test_me_case_2(self, xp): a = xp.array([[10, 7, 4], [3, 2, 1]]) return xp.quantile(a, 0.5, axis=0) @testing.numpy_nlcpy_array_equal() def test_me_case_3(self, xp): a = xp.array([[10, 7, 4], [3, 2, 1]]) return xp.quantile(a, 0.5, axis=1) @testing.numpy_nlcpy_array_equal() def test_me_case_4(self, xp): a = xp.array([[10, 7, 4], [3, 2, 1]]) return xp.quantile(a, 0.5, axis=1, keepdims=True) @testing.numpy_nlcpy_array_equal() def test_me_case_5(self, xp): a = xp.array([[10, 7, 4], [3, 2, 1]]) m = xp.quantile(a, 0.5, axis=0) out = xp.zeros_like(m) return xp.quantile(a, 0.5, axis=0, out=out) def testinge_case_6(): a = vp.array([[10, 7, 4], [3, 2, 1]]) b = a.copy() vp.quantile(b, 0.5, axis=1, overwrite_input=True) return vp.all(a == b)
[ { "point_num": 1, "id": "every_function_under_20_lines", "question": "Is every function in this file shorter than 20 lines?", "answer": true }, { "point_num": 2, "id": "more_functions_than_classes", "question": "Does this file define more functions than classes?", "answer": true ...
3
tests/pytest/statistics_tests/test_quantile.py
SX-Aurora/nlcpy
#!/usr/bin/env python import os import pyfwk from pyfi.entity.entity.db import EntityDB # -----------------------------EXCHANGE-MODEL-----------------------------# class ExchangeModel(pyfwk.Model): model = None dbase = None table = None columns = None @staticmethod def instance(): if not ExchangeModel.model: ExchangeModel.model = ExchangeModel() return ExchangeModel.model def __init__(self): self.dbase = EntityDB.instance() self.table = 'exchange' id = pyfwk.DBCol('id', 'INTEGER PRIMARY KEY') symbol = pyfwk.DBCol('symbol', 'TEXT') name = pyfwk.DBCol('name', 'TEXT') self.columns = [id, symbol, name] self.validate() # ----------------------------------MAIN----------------------------------# def main(): fm = pyfwk.FileManager.instance() fm.set_root(os.path.dirname(os.path.dirname(__file__))) xm = ExchangeModel.instance() if __name__ == '__main__': main()
[ { "point_num": 1, "id": "has_nested_function_def", "question": "Does this file contain any function defined inside another function?", "answer": false }, { "point_num": 2, "id": "every_function_has_docstring", "question": "Does every function in this file have a docstring?", "ans...
3
pyfi/entity/exchange/model.py
rlinguri/pyfi
import pylab def rgb2gray(rgb_image): "Based on http://stackoverflow.com/questions/12201577" # [0.299, 0.587, 0.144] normalized gives [0.29, 0.57, 0.14] return pylab.dot(rgb_image[:, :, :3], [0.29, 0.57, 0.14]) def initialize(usegpu): return 1 def describe(image): return rgb2gray(image).reshape([1, image.shape[0], image.shape[1]]) def update_roi(old_roi, moved_by): roi = old_roi roi[0] = round(moved_by[1]) + roi[0] roi[1] = round(moved_by[0]) + roi[1] return roi def get_name(): return "RawGray"
[ { "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_nested_function_def", "question": "Does this file contain any function defined insid...
3
descriptors/raw_gray_descriptor.py
RealJohnSmith/circulant_matrix_tracker
"""included ordering for sections Revision ID: 91052a50e2b0 Revises: 5716caecc491 Create Date: 2020-06-26 14:49:21.905034 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = '91052a50e2b0' down_revision = '5716caecc491' branch_labels = None depends_on = None def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.add_column('section', sa.Column('section_ordering', sa.Integer(), nullable=False, server_default='0')) # ### end Alembic commands ### def downgrade(): # ### commands auto generated by Alembic - please adjust! ### op.drop_column('section', 'section_ordering') # ### end Alembic commands ###
[ { "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
app/alembic/versions/2020_06_26_14_49_21.py
Juan7655/wfh-movies
from abc import ABCMeta import logging import json class BaseObject(object): __metaclass__ = ABCMeta def __init__(self, **kwargs): self.log = logging.getLogger("irchooky") for prop in self.properties: setattr(self, prop, kwargs.get(prop, "")) def load(self, object_dict): if not object_dict: return for prop in self.properties: default = getattr(self, prop) setattr(self, prop, object_dict.get(prop, default)) def __str__(self): return_dict = {} for prop in self.properties: return_dict.update({prop: str(getattr(self, prop))}) return json.dumps(return_dict) def __eq__(self, other): for prop in self.properties: if not getattr(self, prop) == getattr(other, prop): self.log.debug("Property %s is different" % prop) self.log.debug("%s != %s" % (getattr(self, prop), getattr(other, prop))) return False return True def __ne__(self, other): return not self.__eq__(other)
[ { "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
irc_hooky/base_object.py
byorgey/irc-hooky
import master_duel_auto_scan_version as mda from threading import Thread def start(): """method to start searching """ scan_card = Thread(target=mda.main) scan_card.start() def kill(): """method to exit searching """ mda.status_change(False, False, True,False) def pause(): """method to pause searching """ mda.status_change(False, True, False,False) def switch_mode(): """method to switch between deck / duel searching """ mda.status_change(True, False, False,False) # more methodes can be added to fit database search result def get_card_No(): """method to get card code """ if mda.g_card_show: return mda.g_card_show["card"] else: return None def get_card_name(): """method to get card name """ if mda.g_card_show: return mda.g_card_show["name"] else: return None def get_card_desc(): """method to get card description """ if mda.g_card_show: return mda.g_card_show["desc"] else: return None
[ { "point_num": 1, "id": "every_function_has_docstring", "question": "Does every function in this file have a docstring?", "answer": true }, { "point_num": 2, "id": "has_nested_function_def", "question": "Does this file contain any function defined inside another function?", "answ...
3
search_engine.py
lqzhou123/MasterDuelSimpleTranslateTool
from datetime import datetime from typing import Any, Dict, List, Union from fastapi.encoders import jsonable_encoder from sqlalchemy.orm import Session from .crud_base import CRUDBase from models import Show from schemas.shows import ShowCreate, ShowUpdate, ShowDelete class CRUDShow(CRUDBase[Show, ShowCreate, ShowUpdate, ShowDelete]): def get_shows(self, db: Session) -> List[Show]: # return db.query(self.model).all() return super().get_multi(db, skip=0, limit=1000) def get_show_by_id(self, db: Session, *, show_id: int) -> List[Show]: return super().get(db, id=show_id) def create_show(self, db: Session, *, show_to_create: ShowCreate) -> Show: return super().create(db, show_to_create) def update_show( self, db: Session, *, show_obj: Show, updated_show_obj: Union[ShowUpdate, Dict[str, Any]] ) -> Show: if isinstance(updated_show_obj, ShowUpdate): updated_show_obj.edit_date = datetime.utcnow() else: updated_show_obj["edit_date"] = datetime.utcnow() return super().update(db, show_obj, updated_show_obj) def remove(self, db: Session, *, show_id: int) -> Show: return super().remove(db, id=show_id) crud_show = CRUDShow(Show)
[ { "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": "all_function_names_snake_case", "question": "Are all function names in this file written i...
3
pilitgui2/api/crud/crud_show.py
skypanther/clc
# -*- coding: utf-8 -*- """kmp_algorithm.ipynb Automatically generated by Colaboratory. Original file is located at https://colab.research.google.com/drive/1wsUiWXaWKuIxv-udYnxqV463PD4z2ps- """ def init_next(pattern): M = len(pattern) next = [0 for _ in range(M)] # 정보 저장용 배열 j = 0 # 배열의 값을 불러오고, 패턴의 인덱스에 접근 for i in range(1, M): # 배열에 값 저장하기 위해 활용하는 인덱스 # j가 0이 되거나, i와 j의 pattern 접근 값이 같아질 때까지 진행 while j > 0 and pattern[i] != pattern[j]: j = next[j-1] # 이전의 일치한 곳까지 돌아가서 다시 비교 # 값이 일치하는 경우, if pattern[i] == pattern[j] : # j의 값을 1 증가시키고 그 값을 next에 갱신 j += 1 next[i] = j return next def KMP(pattern, text): M = len(pattern) N = len(text) next = init_next(pattern) j = 0 for i in range(N): # 단어와 패턴이 일치하지 않을 때 while j > 0 and text[i] != pattern[j] : j = next[j-1] # 이전의 일치한 곳까지 돌아가서 다시 비교 # 만약 j가 패턴의 끝까지 도달하였다면, if text[i] == pattern[j]: if j == M - 1 : print("패턴이 발생한 위치:", i - (M - 1)) j = next[j] # 위치를 옮겨주고 다시 탐색 else: # 해당 인덱스에서 값이 일치한다면, j를 1 증가시킴 j += 1 print("탐색 종료") text1 = "ababababcababababcaabbabababcaab" pattern1 = "abababca" KMP(pattern1, text1) text2 = "This class is an algorithm design class. Therefore, students will have time to learn about algorithms and implement each algorithm themselves." pattern2 = "algorithm" KMP(pattern2, text2)
[ { "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
3. Algorithms/04. String Process Algorithm/KMP Algorithm Design/kmp_algorithm.py
oneonlee/Computer-Science
from discord.ext import commands """ A custom Cooldown type subclassing built in cooldowns from discord.ext commands. This is a bucket type that allows cooldowns to work based on some text, allowing things like cooldown on individual `Tags`, or message spam detection. """ class MessageTextBucket(commands.BucketType): custom = 7 def get_key(self, text): return text def __call__(self, msg): return self.get_key(msg)
[ { "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
utils/message_cooldown.py
Chr1sDev/Bloo
## # Copyright (c) 2012-2017 Apple 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. ## from caldavclientlibrary.protocol.http.data.string import ResponseDataString from caldavclientlibrary.protocol.webdav.definitions import statuscodes, \ headers from caldavclientlibrary.protocol.webdav.propfind import PropFind from contrib.performance.sqlusage.requests.httpTests import HTTPTestBase from caldavclientlibrary.protocol.caldav.definitions import csxml class PropfindInviteTest(HTTPTestBase): """ A propfind operation """ def __init__(self, label, sessions, logFilePath, logFilePrefix, depth=1): super(PropfindInviteTest, self).__init__(label, sessions, logFilePath, logFilePrefix) self.depth = headers.Depth1 if depth == 1 else headers.Depth0 def doRequest(self): """ Execute the actual HTTP request. """ props = ( csxml.invite, ) # Create WebDAV propfind request = PropFind(self.sessions[0], self.sessions[0].calendarHref, self.depth, props) result = ResponseDataString() request.setOutput(result) # Process it self.sessions[0].runSession(request) # If its a 207 we want to parse the XML if request.getStatusCode() == statuscodes.MultiStatus: pass else: raise RuntimeError("Propfind request failed: %s" % (request.getStatusCode(),))
[ { "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
contrib/performance/sqlusage/requests/propfind_invite.py
backwardn/ccs-calendarserver
from bs4 import BeautifulSoup from datetime import datetime import requests import time def get_code(company_code): url="https://finance.naver.com/item/main.nhn?code=" + company_code result = requests.get(url) bs_obj = BeautifulSoup(result.content, "html.parser") return bs_obj def get_price(company_code): bs_obj = get_code(company_code) no_today = bs_obj.find("p", {"class": "no_today"}) blind = no_today.find("span", {"class": 'blind'}) now_price = blind.text return now_price company_codes = ["175250","153490"] prices =[] while True: now = datetime.now() print(now) for item in company_codes: now_price = get_price(item) # print(now_price, company_codes) prices.append(now_price) # print("------------------------") print(prices) prices =[] time.sleep(60)
[ { "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
classification-multi/a/a.py
fishduke/vision
def selectionSort(arr): for i in range(len(arr)): minIdx = i for j in range(i+1, len(arr)): if arr[minIdx] > arr[j]: minIdx = j arr[i], arr[minIdx] = arr[minIdx], arr[i] for i in arr: print(i, end=" ") print() def bubbleSort(arr): for i in range(len(arr)-1): for j in range(len(arr)-i-1): if(arr[j] > arr[j + 1]): arr[j], arr[j + 1] = arr[j + 1], arr[j] for i in arr: print(i, end=" ") print() def insertionSort(arr): for i in range(1, len(arr)): key = arr[i] j = i - 1 while j >= 0 and key < arr[j]: arr[j + 1] = arr[j] j -= 1 arr[j + 1] = key for i in arr: print(i, end=" ") print() def countSort(arr): max_element = int(max(arr)) min_element = int(min(arr)) range_of_elements = max_element - min_element + 1 count_arr = [0 for _ in range(range_of_elements)] output_arr = [0 for _ in range(len(arr))] for i in range(0, len(arr)): count_arr[arr[i]-min_element] += 1 for i in range(1, len(count_arr)): count_arr[i] += count_arr[i-1] for i in range(len(arr)-1, -1, -1): output_arr[count_arr[arr[i] - min_element] - 1] = arr[i] count_arr[arr[i] - min_element] -= 1 for i in output_arr: print(i, end=" ") print() arr = [1, 5, 5421, -454, 100, 0] selArr = arr[:] bubArr = arr[:] insArr = arr[:] countArr = arr[:] selectionSort(selArr) bubbleSort(bubArr) insertionSort(insArr) countSort(countArr) for i in arr: print(i, end=" ")
[ { "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
Topic-2/sort.py
PritishWadhwa/Python-DSA
# -*- coding: utf-8 -*- # Copyright (C) 2021 GIS OPS UG # # # 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. # """Tests for convert module.""" from routingpy import convert import tests as _test class UtilsTest(_test.TestCase): # noqa: E741 def test_delimit_list(self): l = [(8.68864, 49.42058), (8.68092, 49.41578)] # noqa: E741 s = convert.delimit_list([convert.delimit_list(pair, ",") for pair in l], "|") self.assertEqual(s, "8.68864,49.42058|8.68092,49.41578") def test_delimit_list_error(self): falses = ["8", 8, {"a": "b", 3: "a", 4: 4}] for f in falses: with self.assertRaises(TypeError): convert.delimit_list(f)
[ { "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
tests/test_convert.py
schaemar/routing-py
# -*- coding: utf-8 -*- """ AsciiDoc Reader =============== This plugin allows you to use AsciiDoc to write your posts. File extension should be ``.asc``, ``.adoc``, or ``asciidoc``. """ from pelican.readers import BaseReader from pelican.utils import pelican_open from pelican import signals import six try: # asciidocapi won't import on Py3 from .asciidocapi import AsciiDocAPI, AsciiDocError # AsciiDocAPI class checks for asciidoc.py AsciiDocAPI() except: asciidoc_enabled = False else: asciidoc_enabled = True class AsciiDocReader(BaseReader): """Reader for AsciiDoc files""" enabled = asciidoc_enabled file_extensions = ['asc', 'adoc', 'asciidoc'] default_options = ["--no-header-footer", "-a newline=\\n"] default_backend = 'html5' def read(self, source_path): """Parse content and metadata of asciidoc files""" from cStringIO import StringIO with pelican_open(source_path) as source: text = StringIO(source.encode('utf8')) content = StringIO() ad = AsciiDocAPI() options = self.settings.get('ASCIIDOC_OPTIONS', []) options = self.default_options + options for o in options: ad.options(*o.split()) backend = self.settings.get('ASCIIDOC_BACKEND', self.default_backend) ad.execute(text, content, backend=backend) content = content.getvalue().decode('utf8') metadata = {} for name, value in ad.asciidoc.document.attributes.items(): name = name.lower() metadata[name] = self.process_metadata(name, six.text_type(value)) if 'doctitle' in metadata: metadata['title'] = metadata['doctitle'] return content, metadata def add_reader(readers): for ext in AsciiDocReader.file_extensions: readers.reader_classes[ext] = AsciiDocReader def register(): signals.readers_init.connect(add_reader)
[ { "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
plugins/asciidoc_reader/asciidoc_reader.py
craigriley39/pelican-site
# Copyright (c) 2021 Xiaomi Corporation (authors: Guo Liyong) # Apache 2.0 from typing import List, Union from pathlib import Path import k2 import sentencepiece as spm Pathlike = Union[str, Path] class Numericalizer(object): def __init__(self, tokenizer, tokens_list): super().__init__() self.tokenizer=tokenizer self.tokens_list = tokens_list def EncodeAsIds(self, text: str) -> List[int]: tokens = self.tokenizer.EncodeAsPieces(text.upper()) assert len(tokens) != 0 tokenids = [self.tokens_list[token] for token in tokens] return tokenids @classmethod def build_numericalizer(cls, tokenizer_model_file: str, tokens_file: Pathlike): sp = spm.SentencePieceProcessor() if not isinstance(tokenizer_model_file, str): # sp.Load only support path in str format assert isinstance(tokenizer_model_file, Path) tokenizer_model_file = str(tokenizer_model_file) sp.Load(tokenizer_model_file) tokens_list = k2.SymbolTable.from_file(tokens_file) assert sp.GetPieceSize() == len(tokens_list) return Numericalizer(sp, tokens_list)
[ { "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
snowfall/text/numericalizer.py
aarora8/snowfall
# -*- coding: utf-8 -*- """ Created on Sat Mar 23 06:08:57 2019 @author: Khoi To """ class PopulationHandler(object): def __init__(self, characteristics): self.characteristics = characteristics def init(self, number_of_population): pass def selection(self): pass def replace(self): pass
[ { "point_num": 1, "id": "has_nested_function_def", "question": "Does this file contain any function defined inside another function?", "answer": false }, { "point_num": 2, "id": "has_multiple_inheritance", "question": "Does any class in this file use multiple inheritance?", "answ...
3
ga/population.py
tokhoi/genetic-algorithm
""" :class:`~allennlp.common.tqdm.Tqdm` wraps tqdm so we can add configurable global defaults for certain tqdm parameters. Adopted from AllenNLP: https://github.com/allenai/allennlp/blob/v0.6.1/allennlp/common/tqdm.py """ from tqdm import tqdm as _tqdm # This is neccesary to stop tqdm from hanging # when exceptions are raised inside iterators. # It should have been fixed in 4.2.1, but it still # occurs. # TODO(Mark): Remove this once tqdm cleans up after itself properly. # https://github.com/tqdm/tqdm/issues/469 _tqdm.monitor_interval = 0 class Tqdm: # These defaults are the same as the argument defaults in tqdm. default_mininterval: float = 0.1 @staticmethod def set_default_mininterval(value: float) -> None: Tqdm.default_mininterval = value @staticmethod def set_slower_interval(use_slower_interval: bool) -> None: """ If ``use_slower_interval`` is ``True``, we will dramatically slow down ``tqdm's`` default output rate. ``tqdm's`` default output rate is great for interactively watching progress, but it is not great for log files. You might want to set this if you are primarily going to be looking at output through log files, not the terminal. """ if use_slower_interval: Tqdm.default_mininterval = 10.0 else: Tqdm.default_mininterval = 0.1 @staticmethod def tqdm(*args, **kwargs): new_kwargs = { 'mininterval': Tqdm.default_mininterval, **kwargs } return _tqdm(*args, **new_kwargs)
[ { "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
miso/utils/tqdm.py
pitrack/arglinking
from PySide2.QtCore import Qt from PySide2.QtWidgets import QCheckBox, QLabel, QWidget, QHBoxLayout from traitlets import HasTraits, Bool, link, Unicode from regexport.model import AppState from regexport.views.utils import HasWidget class CheckboxModel(HasTraits): label = Unicode(default_value='') checked = Bool(default_value=True) def register(self, model: AppState, model_property: str): link( (self, 'checked'), (model, model_property) ) def click(self): self.checked = not self.checked print('checked:', self.checked) class CheckboxView(HasWidget): def __init__(self, model: CheckboxModel): self.checkbox = QCheckBox(model.label) HasWidget.__init__(self, widget=self.checkbox) self.checkbox.setChecked(model.checked) self.checkbox.clicked.connect(model.click) model.observe(self.render, 'checked') def render(self, changed): self.checkbox.setChecked(changed.new)
[ { "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
regexport/views/checkbox.py
jonnykohl/ABBA-QuPath-RegistrationAnalysis
from random import * from turtle import * from freegames import vector bird = vector(0, 0) balls = [] def tap(x, y): "Move bird up in response to screen tap." up = vector(0, 30) bird.move(up) def inside(point): "Return True if point on screen." return -200 < point.x < 200 and -200 < point.y < 200 def draw(alive): "Draw screen objects." clear() goto(bird.x, bird.y) if alive: dot(10, 'green') else: dot(10, 'red') for ball in balls: goto(ball.x, ball.y) dot(20, 'black') update() def move(): "Update object positions." bird.y -= 5 for ball in balls: ball.x -= 3 if randrange(10) == 0: y = randrange(-199, 199) ball = vector(199, y) balls.append(ball) while len(balls) > 0 and not inside(balls[0]): balls.pop(0) if not inside(bird): draw(False) return for ball in balls: if abs(ball - bird) < 15: draw(False) return draw(True) ontimer(move, 50) setup(420, 420, 370, 0) hideturtle() up() tracer(False) onscreenclick(tap) move() done()
[ { "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
Python/Projects/flappy.py
janvi16/-HACKTOBERFEST2K20
# -*- coding: utf-8 -*- from ccxt.btcbox import btcbox class jubi (btcbox): def describe(self): return self.deep_extend(super(jubi, self).describe(), { 'id': 'jubi', 'name': 'jubi.com', 'countries': 'CN', 'rateLimit': 1500, 'version': 'v1', 'has': { 'CORS': False, 'fetchTickers': True, }, 'urls': { 'logo': 'https://user-images.githubusercontent.com/1294454/27766581-9d397d9a-5edd-11e7-8fb9-5d8236c0e692.jpg', 'api': 'https://www.jubi.com/api', 'www': 'https://www.jubi.com', 'doc': 'https://www.jubi.com/help/api.html', }, }) def fetch_markets(self): markets = self.publicGetAllticker() keys = list(markets.keys()) result = [] for p in range(0, len(keys)): id = keys[p] base = id.upper() quote = 'CNY' # todo symbol = base + '/' + quote base = self.common_currency_code(base) quote = self.common_currency_code(quote) result.append({ 'id': id, 'symbol': symbol, 'base': base, 'quote': quote, 'info': id, }) return result
[ { "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
python/ccxt/jubi.py
hippylover/ccxt
''' @Author: ZM @Date and Time: 2019/10/8 6:28 @File: Dataset.py ''' class Dataset: def __init__(self, x, y=None, transform=None, y_transform=None): self.x = x self.y = y self.transform = transform self.y_transform = y_transform def __len__(self): return len(self.x) def __getitem__(self, item): x = self.x[item] if self.transform is not None: x = self.transform(x) if self.y is not None: y = self.y[item] if self.y_transform is not None: y = self.y_transform(y) return x, y return x
[ { "point_num": 1, "id": "has_multiple_inheritance", "question": "Does any class in this file use multiple inheritance?", "answer": false }, { "point_num": 2, "id": "all_params_annotated", "question": "Does every function parameter in this file have a type annotation (excluding self/c...
3
word_similarity/Dataset.py
mengzhu0308/word2vec
import boto3 import json import pprint pp = pprint.PrettyPrinter(width=41, compact=True) # Create IAM client iam = boto3.client('iam') response = iam.list_roles() # list all roles def getRoles(): role_data = [] for role in response['Roles']: role_list = {} role_name = role['RoleName'] role_list['role'] = role role_managed_policy = getRoleManagedPolicies(role_name) role_inline_policy = getRoleInlinePolicies(role_name) role_list['managed_role_policies'] = role_managed_policy role_list['inline_role_policies'] = role_inline_policy role_data.append(role_list) pp.pprint(role_data) # managed Policies in a role def getRoleManagedPolicies(role_name): managed = iam.list_attached_role_policies(RoleName=role_name) for attached_policies in managed['AttachedPolicies']: managed_data = getPolicyDetails(attached_policies) return managed_data #get Policy Details def getPolicyDetails(policy): policy_version = {} policy_data = iam.get_policy(PolicyArn = policy['PolicyArn']) policy_de = iam.get_policy_version(PolicyArn = policy['PolicyArn'], VersionId = policy_data['Policy']['DefaultVersionId']) policy_version['policy_data'] = policy_data policy_version['policy_details'] = policy_de return policy_version # inline Policies in a role def getRoleInlinePolicies(role_name): inline_policy = [] inline = iam.list_role_policies(RoleName=role_name) for policy in inline['PolicyNames']: inline_data = iam.get_role_policy(RoleName=role_name,PolicyName=policy) inline_policy.append(inline_data) return inline_policy getRoles()
[ { "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
scripts/IAM/getRolesData.py
Taranpreet26311/myrepo
import numpy as np import matplotlib.pyplot as plt def sigmoid(val): return 1/(1 + np.exp(-val)) def stable_coeff(rho, psi): r = sigmoid(rho) theta = np.pi * sigmoid(psi) a_1 = -2*r*np.cos(theta) a_2 = r**2 return a_1, a_2 def roots_polynomial(a_1, a_2): delta = a_1**2 - 4 * a_2 delta = delta.astype(np.complex) root_1 = (-a_1 + np.sqrt(delta))/2 root_2 = (-a_1 - np.sqrt(delta))/2 idx_real = delta > 0 return root_1, root_2, idx_real if __name__ == '__main__': N = 100000 rho = np.random.randn(N)*1 psi = np.random.randn(N)*1 a_1, a_2 = stable_coeff(rho, psi) r_1, r_2, idx_real = roots_polynomial(a_1, a_2) fig, ax = plt.subplots() ax.plot(a_1, a_2, '*') ax.plot(a_1[idx_real], a_2[idx_real], 'k*') ax.set_xlabel('a_1') ax.set_ylabel('a_2') ax.set_xlim([-2, 2]) ax.set_ylim([-2, 2]) fig, ax = plt.subplots() ax.plot(np.real(r_1), np.imag(r_1), 'r*') ax.plot(np.real(r_2), np.imag(r_2), 'r*') ax.plot(np.real(r_1)[idx_real], np.imag(r_1)[idx_real], 'k*') ax.plot(np.real(r_2)[idx_real], np.imag(r_2)[idx_real], 'k*') ax.set_xlim([-1.2, 1.2]) ax.set_ylim([-1.2, 1.2]) perc_real = np.sum(idx_real) / N *100 print(f"Real poles in {perc_real:.1f} cases")
[ { "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
test_code/stable_ocs_param.py
temcdrm/dynonet
"""Add signature for st Revision ID: 38a1521607b5 Revises: 2fd64f1e524c Create Date: 2015-01-04 15:40:04.177104 """ from alembic import op import sqlalchemy as sa import base64 import pkg_resources # revision identifiers, used by Alembic. revision = '38a1521607b5' down_revision = '2fd64f1e524c' def upgrade(): op.drop_column('user', 'signature') op.add_column( 'user', sa.Column('signature', sa.String(), nullable=True)) signature = pkg_resources.resource_stream( 'sw.allotmentclub.signatures', 'st.png').read() signature = 'data:application/png;base64,{}'.format( base64.b64encode(signature)) op.execute(u"""UPDATE public.user SET signature = '{signature}' WHERE username = 'st';""".format(signature=signature)) def downgrade(): op.drop_column('user', 'signature') op.add_column( 'user', sa.Column('signature', sa.LargeBinary(length=10485760), nullable=True))
[ { "point_num": 1, "id": "every_function_has_docstring", "question": "Does every function in this file have a docstring?", "answer": false }, { "point_num": 2, "id": "has_nested_function_def", "question": "Does this file contain any function defined inside another function?", "ans...
3
src/sw/allotmentclub/alembic/versions/add_signature_for_st_38a1521607b5.py
sweh/sw.allotmentclub.backend
#-*- coding: utf-8 -*- ''' Created on 2021. 7. 11. @author: FlareWizard ''' from Game.Scene.SceneBase import SceneBase, eSceneType #------------------------------------------------------------------------------- # SceneLobby #------------------------------------------------------------------------------- class SceneLobby(SceneBase): ''' 게임 장면 클래스 : 로비 ''' ## Public Methods def Initialize(self): ''' 초기화 ''' return True def Process(self): ''' 프로세스 ''' pass def Release(self): ''' 해제 ''' pass ## Private Methods def __init__(self): ''' 생성자 ''' print("SceneLobby constructed") super().__init__() SceneBase.sceneType = eSceneType.Lobby def __del__(self): ''' 소멸자 ''' print('SceneLobby destroyed') super().__del__()
[ { "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
FirstPythonGame/Game/Scene/SceneLobby.py
chowizard/StudyPython
def invertBinaryTree(tree): invert(tree) return tree def invert(tree): if (tree) is None: return if(tree) is not None: tree.right, tree.left = tree.left, tree.right invert(tree.left) invert(tree.right) def invertBinaryTree(tree): treeStack = [tree] while len(treeStack) > 0: item = treeStack.pop() if item is None: continue swapTreeElement(item) treeStack.append(item.left) treeStack.append(item.right) return tree def swapTreeElement(tree): tree.left, tree.right = tree.right, tree.left def invertBinaryTreePracticeWithWhile(tree): treeStack = [tree] while len(treeStack) > 0: item = treeStack.pop() if(item) is None: continue item.left, item.right = item.right, item.left treeStack.append(item.left) treeStack.append(item.right) return tree class BinaryTree: def __init__(self, value): self.value = value self.left = None self.right = None
[ { "point_num": 1, "id": "more_functions_than_classes", "question": "Does this file define more functions than classes?", "answer": true }, { "point_num": 2, "id": "has_multiple_inheritance", "question": "Does any class in this file use multiple inheritance?", "answer": false },...
3
AlgoExpert/InvertBinaryTree.py
akhil-ece/160Days
import torch.nn as nn class LSTMClassifier(nn.Module): """ This is the simple RNN model we will be using to perform Sentiment Analysis. """ def __init__(self, embedding_dim, hidden_dim, vocab_size): """ Initialize the model by settingg up the various layers. """ super(LSTMClassifier, self).__init__() self.embedding = nn.Embedding(vocab_size, embedding_dim, padding_idx=0) self.lstmA = nn.LSTM(embedding_dim, hidden_dim) self.lstmB = nn.LSTM(hidden_dim, hidden_dim) self.dense = nn.Linear(in_features=hidden_dim, out_features=1) self.sig = nn.Sigmoid() self.word_dict = None def forward(self, x): """ Perform a forward pass of our model on some input. """ x = x.t() lengths = x[0,:] reviews = x[1:,:] embeds = self.embedding(reviews) lstm_out1, _ = self.lstmA(embeds) lstm_out, _ = self.lstmB(lstm_out1) out = self.dense(lstm_out) out = out[lengths - 1, range(len(lengths))] return self.sig(out.squeeze())
[ { "point_num": 1, "id": "all_params_annotated", "question": "Does every function parameter in this file have a type annotation (excluding self/cls)?", "answer": false }, { "point_num": 2, "id": "more_functions_than_classes", "question": "Does this file define more functions than clas...
3
train/model_stack.py
pabloserna/SentimentAnalysisinAWS
#!/usr/bin/env python # Copyright 2014 Boundary, 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. class Metric: def __init__(self): pass def setSource(self,source): self.source = source def getSource(self): return self.source def setName(self, name): self.name = name def getName(self): return self.name def setValue(self, value): self.value = value def getValue(self): return self.value def __str__(self): return "{} {} {}".format(self.name,self.value,self.source)
[ { "point_num": 1, "id": "every_function_has_docstring", "question": "Does every function in this file have a docstring?", "answer": false }, { "point_num": 2, "id": "more_functions_than_classes", "question": "Does this file define more functions than classes?", "answer": true }...
3
metric.py
jdgwartney/sdk
from djoser.conf import settings __all__ = ['settings'] def get_user_email(user): email_field_name = get_user_email_field_name(user) return getattr(user, email_field_name, None) def get_user_email_field_name(user): try: # Assume we are Django >= 1.11 return user.get_email_field_name() except AttributeError: # we are using Django < 1.11 return settings.USER_EMAIL_FIELD_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": "every_function_has_docstring", "question": "Does every function in this file have a docstring?", "answer": fals...
3
djoser/compat.py
mark-slepkov/djoser
#!/Users/yaroten/Library/Mobile Documents/com~apple~CloudDocs/git/crawling_scraping/crawling_scraping/bin/python3 # $Id: rst2odt_prepstyles.py 5839 2009-01-07 19:09:28Z dkuhlman $ # Author: Dave Kuhlman <dkuhlman@rexx.com> # Copyright: This module has been placed in the public domain. """ Fix a word-processor-generated styles.odt for odtwriter use: Drop page size specifications from styles.xml in STYLE_FILE.odt. """ # # Author: Michael Schutte <michi@uiae.at> from lxml import etree import sys import zipfile from tempfile import mkstemp import shutil import os NAMESPACES = { "style": "urn:oasis:names:tc:opendocument:xmlns:style:1.0", "fo": "urn:oasis:names:tc:opendocument:xmlns:xsl-fo-compatible:1.0" } def prepstyle(filename): zin = zipfile.ZipFile(filename) styles = zin.read("styles.xml") root = etree.fromstring(styles) for el in root.xpath("//style:page-layout-properties", namespaces=NAMESPACES): for attr in el.attrib: if attr.startswith("{%s}" % NAMESPACES["fo"]): del el.attrib[attr] tempname = mkstemp() zout = zipfile.ZipFile(os.fdopen(tempname[0], "w"), "w", zipfile.ZIP_DEFLATED) for item in zin.infolist(): if item.filename == "styles.xml": zout.writestr(item, etree.tostring(root)) else: zout.writestr(item, zin.read(item.filename)) zout.close() zin.close() shutil.move(tempname[1], filename) def main(): args = sys.argv[1:] if len(args) != 1: print >> sys.stderr, __doc__ print >> sys.stderr, "Usage: %s STYLE_FILE.odt\n" % sys.argv[0] sys.exit(1) filename = args[0] prepstyle(filename) if __name__ == '__main__': main() # vim:tw=78:sw=4:sts=4:et:
[ { "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
crawling_scraping/bin/rst2odt_prepstyles.py
litteletips/crawling_scraping-scrapy_tool
#!/usr/bin/env python # -*- coding: utf-8 -*- """Tests for `cookiecutter_pydemo` package.""" import unittest from click.testing import CliRunner from cookiecutter_pydemo import cookiecutter_pydemo from cookiecutter_pydemo import cli class TestCookiecutter_pydemo(unittest.TestCase): """Tests for `cookiecutter_pydemo` package.""" def setUp(self): """Set up test fixtures, if any.""" def tearDown(self): """Tear down test fixtures, if any.""" def test_000_something(self): """Test something.""" def test_command_line_interface(self): """Test the CLI.""" runner = CliRunner() result = runner.invoke(cli.main) assert result.exit_code == 0 assert 'cookiecutter_pydemo.cli.main' in result.output help_result = runner.invoke(cli.main, ['--help']) assert help_result.exit_code == 0 assert '--help Show this message and exit.' in help_result.output
[ { "point_num": 1, "id": "every_function_under_20_lines", "question": "Is every function in this file shorter than 20 lines?", "answer": true }, { "point_num": 2, "id": "every_function_has_docstring", "question": "Does every function in this file have a docstring?", "answer": true...
3
tests/test_cookiecutter_pydemo.py
cgDeepLearn/cookiecutter_pydemo
import pytest from unyt.unit_object import define_unit from unyt.unit_registry import UnitRegistry from unyt.array import unyt_quantity def test_define_unit(): define_unit("mph", (1.0, "mile/hr")) a = unyt_quantity(2.0, "mph") b = unyt_quantity(1.0, "mile") c = unyt_quantity(1.0, "hr") assert a == 2.0 * b / c d = unyt_quantity(1000.0, "cm**3") define_unit("Baz", d, prefixable=True) e = unyt_quantity(1.0, "mBaz") f = unyt_quantity(1.0, "cm**3") assert e == f define_unit("Foo", (1.0, "V/sqrt(s)")) g = unyt_quantity(1.0, "Foo") volt = unyt_quantity(1.0, "V") second = unyt_quantity(1.0, "s") assert g == volt / second ** (0.5) # Test custom registry reg = UnitRegistry() define_unit("Foo", (1, "m"), registry=reg) define_unit("Baz", (1, "Foo**2"), registry=reg) h = unyt_quantity(1, "Baz", registry=reg) i = unyt_quantity(1, "m**2", registry=reg) assert h == i def test_define_unit_error(): from unyt import define_unit with pytest.raises(RuntimeError): define_unit("foobar", "baz") with pytest.raises(RuntimeError): define_unit("foobar", 12) with pytest.raises(RuntimeError): define_unit("C", (1.0, "A*s"))
[ { "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
unyt/tests/test_define_unit.py
migueldvb/unyt
# coding: utf-8 """ Qc API Qc API # noqa: E501 The version of the OpenAPI document: 3.0.0 Contact: cloudsupport@telestream.net Generated by: https://openapi-generator.tech """ from __future__ import absolute_import import unittest import datetime import telestream_cloud_qc from telestream_cloud_qc.models.location_test import LocationTest # noqa: E501 from telestream_cloud_qc.rest import ApiException class TestLocationTest(unittest.TestCase): """LocationTest unit test stubs""" def setUp(self): pass def tearDown(self): pass def make_instance(self, include_optional): """Test LocationTest include_option is a boolean, when False only required params are included, when True both required and optional params are included """ # model = telestream_cloud_qc.models.location_test.LocationTest() # noqa: E501 if include_optional : return LocationTest( header = '0', body = '0', footer = '0', header_or_body_or_footer = True, reject_on_error = True, checked = True ) else : return LocationTest( ) def testLocationTest(self): """Test LocationTest""" inst_req_only = self.make_instance(include_optional=False) inst_req_and_optional = self.make_instance(include_optional=True) 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
telestream_cloud_qc_sdk/test/test_location_test.py
pandastream/telestream-cloud-python-sdk
from django.views import generic from django.shortcuts import redirect class IndexView(generic.ListView): template_name = 'Dashboard.html' def get_queryset(self): pass def home(request): return redirect('/privacy/')
[ { "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
server/views.py
sylar233/de-identification
# -*- coding: utf-8 -*- """ To connect the power meter you'll need to use the "Power meter driver switcher" application to switch to the PM100D (Ni-Visa) drivers. Then the resource name should show up when exceuting: import visa visa.ResourceManager().list_resources() """ from lantz.messagebased import MessageBasedDriver from lantz import Feat class PM100D(MessageBasedDriver): DEFAULTS = { 'COMMON': { 'read_termination': '\n', 'write_termination': '\n', }, } @Feat(read_once=True) def idn(self): return self.query('*IDN?') @Feat(units='W') def power(self): return float(self.query('MEAS:POWER?')) @Feat(units='nm') def correction_wavelength(self): return float(self.query('SENSE:CORRECTION:WAVELENGTH?')) @correction_wavelength.setter def correction_wavelength(self, wavelength): self.write('SENSE:CORRECTION:WAVELENGTH {}'.format(wavelength)) @Feat() def correction_wavelength_range(self): cmd = 'SENSE:CORRECTION:WAVELENGTH? {}' cmd_vals = ['MIN', 'MAX'] return tuple(float(self.query(cmd.format(cmd_val))) for cmd_val in cmd_vals)
[ { "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
lantz/drivers/thorlabs/pm100d.py
ZixiLi0520/lantz
import unittest from acme import Product, BoxingGlove from acme_report import generate_products, ADJECTIVES, NOUNS """Tests for Acme Python modules.""" class AcmeProductTests(unittest.TestCase): """Making sure Acme products are the tops!""" def test_default_product_price(self): """Test default product price being 10.""" prod = Product('Test Product') self.assertEqual(prod.price, 10) def test_default_product_weight(self): """Test default product weight being 20.""" prod = Product('Another day, another anvil') self.assertEqual(prod.weight, 20) def test_default_boxing_weight(self): """Test weight of default boxing gloves""" glove = BoxingGlove('Punch Puncher') self.assertEqual(glove.weight, 10) def test_stealable_and_explode(self): """Is a product stealable or explosive...or both?""" babomb = Product('Danger!', price=20, weight=20, flammability=2.5) self.assertEqual(babomb.stealability(), 'Very stealable!') self.assertEqual(babomb.explode(), '...BABOOM!!') class AcmeReportTests(unittest.TestCase): """Running unittest on products.""" def test_default_num_products(self): """Check that Acme makes 30 products by default.""" self.assertEqual(len(generate_products()), 30) def test_legal_names(self): """Check that all products have valid names.""" for product in generate_products(): adjective, noun = product.name.split() self.assertIn(adjective, ADJECTIVES) self.assertIn(noun, NOUNS) if __name__ == '__main__': unittest.main()
[ { "point_num": 1, "id": "has_multiple_inheritance", "question": "Does any class in this file use multiple inheritance?", "answer": false }, { "point_num": 2, "id": "more_functions_than_classes", "question": "Does this file define more functions than classes?", "answer": true },...
3
Sprint-challenge/acme_test.py
iesous-kurios/DS-Unit-3-Sprint-1-Software-Engineering
from ast import mod from msilib.schema import ListView from pyexpat import model from django.shortcuts import render from django.views import generic from . import models class Index(generic.TemplateView): template_name = 'catalog/index.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['num_books'] = models.Book.objects.all().count() context['num_instances'] = models.BookInstance.objects.all().count() context['num_instances_available'] = models.BookInstance.objects.filter(status__exact='a').count() context['num_authors'] = models.Author.objects.count() # The 'all()' is implied by default. return context class BookListView(generic.ListView): template_name = 'catalog/book_list.html' model = models.Book class BookDetailView(generic.DetailView): template_name = 'catalog/book_detail.html' model = models.Book class AuthorListView(generic.ListView): template_name = 'catalog/author_list.html' model = models.Author class AuthorDetailView(generic.DetailView): template_name = 'catalog/author_detail.html' model = models.Author # def index(request): # """ # View function for home page of site. # """ # # Generate counts of some of the main objects # num_books = models.Book.objects.all().count() # num_instances = models.BookInstance.objects.all().count() # # Available books (status = 'a') # num_instances_available = models.BookInstance.objects.filter(status__exact='a').count() # num_authors = models.Author.objects.count() # The 'all()' is implied by default. # # Render the HTML template index.html with the data in the context variable # return render( # request, # 'catalog/index.html', # context={'num_books':num_books,'num_instances':num_instances,'num_instances_available':num_instances_available,'num_authors':num_authors}, # )
[ { "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
.history/catalog/views_20220304001504.py
arsalandehghani/locallibrary
# Fix the code so that there's no error! def count_evens(start, end): """Returns the number of even numbers between start and end.""" counter = start num_evens = 0 while counter <= end: if counter % 2 == 0: num_evens += 1 counter += 1 return num_evens def count_multiples(start, end, divisor): """Returns the number of multiples of divisor between start and end.""" counter = start num_multiples = 0 while counter <= end: if counter % divisor == 0: num_multiples += 1 counter += 1 return num_multiples count_both = count_evens(10, 20) + count_multiples(10, 20, 3)
[ { "point_num": 1, "id": "every_function_has_docstring", "question": "Does every function in this file have a docstring?", "answer": true }, { "point_num": 2, "id": "has_nested_function_def", "question": "Does this file contain any function defined inside another function?", "answ...
3
exercise_brokencounts_solution.py
annezola/gdi-python
# compare contents of two files in binary form import sys def compareFile(srcFile,destFile): with open(srcFile,"rb") as src: srcData = src.read() with open(destFile,"rb") as dest: destData = dest.read() checked = False if(len(srcData)!=len(destData)): print("It unequal between ",srcFile,destFile,". The file size is different") checked = True for i in range(min(len(srcData),len(destData))): if(srcData[i] != destData[i]): print("unequal index:%d, modleDatata:%d, flashData:%d " % (i,srcData[i],destData[i])) checked = True if checked: print('Check Result: unequal') else: print('Check Result: equal') def main(): if(len(sys.argv) !=3 ): print('Wrong parameters,need two files') return compareFile(sys.argv[1],sys.argv[2]) if __name__ == '__main__': main()
[ { "point_num": 1, "id": "every_function_under_20_lines", "question": "Is every function in this file shorter than 20 lines?", "answer": true }, { "point_num": 2, "id": "every_function_has_docstring", "question": "Does every function in this file have a docstring?", "answer": fals...
3
compare.py
zhoukaisspu/py_script
from moto.core.responses import BaseResponse class PlacementGroups(BaseResponse): def create_placement_group(self): if self.is_not_dryrun("CreatePlacementGroup"): raise NotImplementedError( "PlacementGroups.create_placement_group is not yet implemented" ) def delete_placement_group(self): if self.is_not_dryrun("DeletePlacementGroup"): raise NotImplementedError( "PlacementGroups.delete_placement_group is not yet implemented" ) def describe_placement_groups(self): raise NotImplementedError( "PlacementGroups.describe_placement_groups is not yet implemented" )
[ { "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
moto/ec2/responses/placement_groups.py
symroe/moto
# coding: utf-8 from __future__ import absolute_import from google.appengine.ext import ndb import flask_restful import flask from api import helpers import auth import model import util from main import api_v1 @api_v1.resource('/repo/', endpoint='api.repo.list') class RepoListAPI(flask_restful.Resource): def get(self): repo_dbs, repo_cursor = model.Repo.get_dbs() return helpers.make_response(repo_dbs, model.Repo.FIELDS, repo_cursor) @api_v1.resource('/repo/<string:repo_key>/', endpoint='api.repo') class RepoAPI(flask_restful.Resource): def get(self, repo_key): repo_db = ndb.Key(urlsafe=repo_key).get() if not repo_db: helpers.make_not_found_exception('Repo %s not found' % repo_key) return helpers.make_response(repo_db, model.Repo.FIELDS) ############################################################################### # Admin ############################################################################### @api_v1.resource('/admin/repo/', endpoint='api.admin.repo.list') class AdminRepoListAPI(flask_restful.Resource): @auth.admin_required def get(self): repo_keys = util.param('repo_keys', list) if repo_keys: repo_db_keys = [ndb.Key(urlsafe=k) for k in repo_keys] repo_dbs = ndb.get_multi(repo_db_keys) return helpers.make_response(repo_dbs, model.repo.FIELDS) repo_dbs, repo_cursor = model.Repo.get_dbs() return helpers.make_response(repo_dbs, model.Repo.FIELDS, repo_cursor) @api_v1.resource('/admin/repo/<string:repo_key>/', endpoint='api.admin.repo') class AdminRepoAPI(flask_restful.Resource): @auth.admin_required def get(self, repo_key): repo_db = ndb.Key(urlsafe=repo_key).get() if not repo_db: helpers.make_not_found_exception('Repo %s not found' % repo_key) return helpers.make_response(repo_db, model.Repo.FIELDS)
[ { "point_num": 1, "id": "any_function_over_40_lines", "question": "Is any function in this file longer than 40 lines?", "answer": false }, { "point_num": 2, "id": "every_class_has_docstring", "question": "Does every class in this file have a docstring?", "answer": false }, { ...
3
main/api/v1/repo.py
AlexRogalskiy/github-stats
from .net_stream_interface import INetStream class NetStream(INetStream): def __init__(self, muxed_stream): self.muxed_stream = muxed_stream self.mplex_conn = muxed_stream.mplex_conn self.protocol_id = None def get_protocol(self): """ :return: protocol id that stream runs on """ return self.protocol_id def set_protocol(self, protocol_id): """ :param protocol_id: protocol id that stream runs on :return: true if successful """ self.protocol_id = protocol_id async def read(self): """ read from stream :return: bytes of input until EOF """ return await self.muxed_stream.read() async def write(self, data): """ write to stream :return: number of bytes written """ return await self.muxed_stream.write(data) async def close(self): """ close stream :return: true if successful """ await self.muxed_stream.close() return True
[ { "point_num": 1, "id": "every_function_has_docstring", "question": "Does every function in this file have a docstring?", "answer": false }, { "point_num": 2, "id": "every_function_under_20_lines", "question": "Is every function in this file shorter than 20 lines?", "answer": tru...
3
libp2p/network/stream/net_stream.py
ChihChengLiang/py-libp2p
# coding: utf-8 """ Cloudsmith API The API to the Cloudsmith Service OpenAPI spec version: v1 Contact: support@cloudsmith.io Generated by: https://github.com/swagger-api/swagger-codegen.git """ from __future__ import absolute_import import os import sys import unittest import cloudsmith_api from cloudsmith_api.rest import ApiException from cloudsmith_api.apis.rates_api import RatesApi class TestRatesApi(unittest.TestCase): """ RatesApi unit test stubs """ def setUp(self): self.api = cloudsmith_api.apis.rates_api.RatesApi() def tearDown(self): pass def test_rates_limits_list(self): """ Test case for rates_limits_list Endpoint to check rate limits for current user. """ 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": "all_function_names_snake_case", "question": "Are all function names in this file written in snake_case?", "answer": ...
3
bindings/python/src/test/test_rates_api.py
cloudsmith-io/cloudsmith-api
""" EDID helper """ from subprocess import CalledProcessError, check_output from typing import ByteString, List __all__ = ["EdidHelper"] class EdidHelper: """Class for working with EDID data""" @staticmethod def hex2bytes(hex_data: str) -> ByteString: """Convert hex EDID string to bytes Args: hex_data (str): hex edid string Returns: ByteString: edid byte string """ # delete edid 1.3 additional block if len(hex_data) > 256: hex_data = hex_data[:256] numbers = [] for i in range(0, len(hex_data), 2): pair = hex_data[i:i+2] numbers.append(int(pair, 16)) return bytes(numbers) @classmethod def get_edids(cls, xrandr_file='') -> List[ByteString]: """Get edids from xrandr Raises: `RuntimeError`: if error with retrieving xrandr util data Returns: List[ByteString]: list with edids """ if xrandr_file: output = open(xrandr_file, "r").read() else: try: output = check_output(["xrandr", "--verbose"]) except (CalledProcessError, FileNotFoundError) as err: raise RuntimeError("Error retrieving xrandr util data: {}".format(err)) from None edids = [] lines = output.splitlines() for i, line in enumerate(lines): line = line.strip() if line.startswith("EDID:"): selection = lines[i+1:i+9] selection = list(s.strip() for s in selection) selection = "".join(selection) bytes_section = cls.hex2bytes(selection) edids.append(bytes_section) return edids
[ { "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": "has_multiple_inheritance", "question": "Does any class in this file use multiple inheritance?", "answer"...
3
pyedid/helpers/edid_helper.py
timotheuslin/pyedid
# Global Imports import json from collections import defaultdict # Metaparser from genie.metaparser import MetaParser # ============================================= # Collection for '/mgmt/tm/ltm/profile/server-ssl' resources # ============================================= class LtmProfileServersslSchema(MetaParser): schema = {} class LtmProfileServerssl(LtmProfileServersslSchema): """ To F5 resource for /mgmt/tm/ltm/profile/server-ssl """ cli_command = "/mgmt/tm/ltm/profile/server-ssl" def rest(self): response = self.device.get(self.cli_command) response_json = response.json() if not response_json: return {} return response_json
[ { "point_num": 1, "id": "every_class_has_docstring", "question": "Does every class in this file have a docstring?", "answer": false }, { "point_num": 2, "id": "more_functions_than_classes", "question": "Does this file define more functions than classes?", "answer": false }, {...
3
src/genie/libs/parser/bigip/get_ltm_profileserver_ssl.py
balmasea/genieparser