source
string
points
list
n_points
int64
path
string
repo
string
# Copyright (C) 2020, 2021 Satoru SATOH <satoru.satoh@gmail.com> # SPDX-License-Identifier: MIT # # pylint: disable=invalid-name # pylint: disable=too-few-public-methods,missing-class-docstring # pylint: disable=missing-function-docstring """Test cases for the rule, DebugRule. """ import os import unittest.mock import pytest from rules import DebugRule as TT from tests import common @pytest.mark.parametrize( ('env', 'exp'), (({}, False), ({TT.E_ENABLED_VAR: ''}, False), ({TT.E_ENABLED_VAR: '1'}, True), ) ) def test_is_enabled(env, exp): with unittest.mock.patch.dict(os.environ, env, clear=True): assert TT.is_enabled() == exp class Base(common.Base): this_mod: common.MaybeModT = TT class RuleTestCase(common.RuleTestCase): base_cls = Base def test_base_get_filename(self): self.assertEqual(self.base.get_filename(), 'TestDebugRule.py') def test_base_get_rule_name(self): self.assertEqual(self.base.get_rule_name(), 'DebugRule') def test_base_get_rule_class_by_name(self): rule_class = self.base.get_rule_class_by_name(self.base.name) self.assertTrue(bool(rule_class)) self.assertTrue(isinstance(rule_class(), type(self.base.rule))) def test_base_is_runnable(self): self.assertTrue(self.base.is_runnable()) def test_list_test_data_dirs(self): self.assertTrue(self.list_test_data_dirs(True)) self.assertTrue(self.list_test_data_dirs(False)) def test_clear_fns(self): fns = self.base.clear_fns self.assertTrue(fns) self.assertTrue(len(fns) > 1) class CliTestCase(common.CliTestCase): base_cls = Base
[ { "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": true }, { ...
3
tests/TestDebugRule.py
ssato/ansibl-lint-custom-rules
class Layer: def forward(self, x): ''' forward propagation Parameters --- x: matrix input from last layer Returns --- out: matrix output of current layer ''' raise NotImplementedError def backprop(self, d): ''' backward propagation Parameters --- d: matrix derivation from next layer Returns --- out_d: matrix derivation of current layer ''' raise NotImplementedError def gradient(self, alpha): ''' gradient descent Parameters --- alpha: float learning rate Returns: None ''' raise NotImplementedError
[ { "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
blog-record/record-4/cnn-py/layer.py
MaxXSoft/Deeplearning-Notes
import logging from typing import TYPE_CHECKING, Dict, Optional, Tuple import settings from .mappers import FoliumMapBuilder if TYPE_CHECKING: from pandas.core.frame import DataFrame logger = logging.getLogger(__name__) class MapPlotter: def __init__( self, data: "DataFrame", columns_dict: Dict[str, int], file_name: str, output_file_name: str, icon_filename: Optional[str] = None, icon_size: Optional[Tuple[int, int]] = None, ) -> None: self._data = data self._columns_dict = columns_dict self.file_name = file_name self._icon_filename = icon_filename self._icon_size = icon_size self.output_file_name = output_file_name self.map_builder = FoliumMapBuilder() def generate_example_map(self) -> None: # Create an empty map self.map_builder.initialize_map() rows = self._data.iloc[:, list(self._columns_dict.values())].values logger.info("Start adding markers...") for row in rows: dict_row = { field_name: row_field for row_field, field_name in zip(row, self._columns_dict.keys()) } coordinates = (dict_row[settings.LATITUDE], dict_row[settings.LONGITUDE]) self.map_builder.add_marker( coordinates=coordinates, legend=dict_row.get(settings.LEGEND), tooltip_text=dict_row.get(settings.TOOLTIP), icon_file_name=self._icon_filename, icon_size=self._icon_size, ) logger.info("Markers successfully added.") self.map_builder.add_layer_control().add_measure_control() self.map_builder.save_map(self.output_file_name)
[ { "point_num": 1, "id": "more_functions_than_classes", "question": "Does this file define more functions than classes?", "answer": true }, { "point_num": 2, "id": "all_return_types_annotated", "question": "Does every function in this file have a return type annotation?", "answer"...
3
map_generator/app.py
Plazas87/map_generator
import unittest import unittest.mock import os from programy.clients.restful.client import RestBotClient from programy.clients.restful.config import RestConfiguration from programytest.clients.arguments import MockArgumentParser class RestBotClientTests(unittest.TestCase): def test_init(self): arguments = MockArgumentParser() client = RestBotClient("testrest", arguments) self.assertIsNotNone(client) self.assertIsNotNone(client.get_client_configuration()) self.assertIsInstance(client.get_client_configuration(), RestConfiguration) self.assertEquals([], client.api_keys) request = unittest.mock.Mock() response, code = client.process_request(request) def test_api_keys(self): arguments = MockArgumentParser() client = RestBotClient("testrest", arguments) self.assertIsNotNone(client) client.configuration.client_configuration._use_api_keys = True client.configuration.client_configuration._api_key_file = os.path.dirname(__file__) + os.sep + ".." + os.sep + "api_keys.txt" client.load_api_keys() self.assertEquals(3, len(client.api_keys)) self.assertTrue(client.is_apikey_valid("11111111")) self.assertTrue(client.is_apikey_valid("22222222")) self.assertTrue(client.is_apikey_valid("33333333")) self.assertFalse(client.is_apikey_valid("99999999"))
[ { "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
test/programytest/clients/restful/test_client.py
whackur/chatbot
import os import shutil from pathlib import Path from test.convert_worker.unit.convert_test import ConvertTest from workers.convert.convert_pdf import convert_pdf_to_tif class PdfToTifTest(ConvertTest): def setUp(self): super().setUp() self.pdf_src = os.path.join(f'{self.resource_dir}', 'files', 'test_small.pdf') self.pdf_path = os.path.join(f'{self.working_dir}', 'test.pdf') shutil.copy(self.pdf_src, self.pdf_path) def test_success(self): convert_pdf_to_tif(self.pdf_path, self.working_dir) name = os.path.splitext(os.path.basename(self.pdf_path))[0] tif_0_path = os.path.join(self.working_dir, f'{name}_0000.tif') self.assertTrue(Path(tif_0_path).is_file()) stat = os.stat(tif_0_path) self.assertGreater(stat.st_size, 0)
[ { "point_num": 1, "id": "has_multiple_inheritance", "question": "Does any class in this file use multiple inheritance?", "answer": false }, { "point_num": 2, "id": "more_functions_than_classes", "question": "Does this file define more functions than classes?", "answer": true },...
3
test/convert_worker/unit/test_pdf_to_tif.py
dainst/cilantro
import discord import subprocess import os, random, re, requests, json import asyncio from datetime import datetime from discord.ext import commands class Economy(commands.Cog): def __init__(self, bot): self.bot = bot @commands.Cog.listener() async def on_ready(self): print('[+] Shop Code ACTIVE!') @commands.command() async def shop(self,ctx): embed = discord.Embed(title='Shop') for item in ourshop: name = item['name'] price = item['price'] embed.add_field(name=name, value=f'{price}wls') await ctx.send(embed=embed) ourshop = [{"name":"diamond-axe","price":400}, {"name":"rift-cape","price":650}, {"name":"lava-cape","price":500}, {"name":"diamond-shoes","price":50}, {"name":"fishnet","price":2}, {"name":"da-vinci","price":990}, {"name":"l-bot","price":1000}, {"name":"gab","price":800}, {"name":"golden-diaper","price":800}, {"name":"box-gacha","price":100}, {"name":"poke-card","price":250}] def setup(bot): bot.add_cog(Economy(bot))
[ { "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
GT-ECONOMY-BOT/economy/shop.py
iFanID/e.Koenomi-DBot
''' This example demonstrates creating and using an AdvancedEffectBase. In this case, we use it to efficiently pass the touch coordinates into the shader. ''' from kivy.base import runTouchApp from kivy.properties import ListProperty from kivy.lang import Builder from kivy.uix.effectwidget import EffectWidget, AdvancedEffectBase effect_string = ''' uniform vec2 touch; vec4 effect(vec4 color, sampler2D texture, vec2 tex_coords, vec2 coords) { vec2 distance = 0.025*(coords - touch); float dist_mag = (distance.x*distance.x + distance.y*distance.y); vec3 multiplier = vec3(abs(sin(dist_mag - time))); return vec4(multiplier * color.xyz, 1.0); } ''' class TouchEffect(AdvancedEffectBase): touch = ListProperty([0.0, 0.0]) def __init__(self, *args, **kwargs): super(TouchEffect, self).__init__(*args, **kwargs) self.glsl = effect_string self.uniforms = {'touch': [0.0, 0.0]} def on_touch(self, *args, **kwargs): self.uniforms['touch'] = [float(i) for i in self.touch] class TouchWidget(EffectWidget): def __init__(self, *args, **kwargs): super(TouchWidget, self).__init__(*args, **kwargs) self.effect = TouchEffect() self.effects = [self.effect] def on_touch_down(self, touch): super(TouchWidget, self).on_touch_down(touch) self.on_touch_move(touch) def on_touch_move(self, touch): self.effect.touch = touch.pos root = Builder.load_string(''' TouchWidget: Button: text: 'Some text!' Image: source: 'data/logo/kivy-icon-512.png' allow_stretch: True keep_ratio: False ''') runTouchApp(root)
[ { "point_num": 1, "id": "every_class_has_docstring", "question": "Does every class in this file have a docstring?", "answer": false }, { "point_num": 2, "id": "all_function_names_snake_case", "question": "Are all function names in this file written in snake_case?", "answer": true...
3
examples/widgets/effectwidget3_advanced.py
yunus-ceyhan/kivy
''' This is a sample class that you can use to control the mouse pointer. It uses the pyautogui library. You can set the precision for mouse movement (how much the mouse moves) and the speed (how fast it moves) by changing precision_dict and speed_dict. Calling the move function with the x and y output of the gaze estimation model will move the pointer. This class is provided to help get you started; you can choose whether you want to use it or create your own from scratch. ''' import pyautogui pyautogui.FAILSAFE = False class MouseController: def __init__(self, precision, speed): precision_dict={'high':100, 'low':1000, 'medium':500} speed_dict={'fast':1, 'slow':10, 'medium':5} self.precision=precision_dict[precision] self.speed=speed_dict[speed] def move(self, x, y): pyautogui.moveRel(x*self.precision, -1*y*self.precision, duration=self.speed)
[ { "point_num": 1, "id": "no_function_exceeds_5_params", "question": "Does every function in this file take 5 or fewer parameters (excluding self/cls)?", "answer": true }, { "point_num": 2, "id": "every_function_under_20_lines", "question": "Is every function in this file shorter than...
3
src/mouse_controller.py
NAITTOU/computer_pointer_controller
# Determine whether or not one string is a permutation of another. def is_permutation(str1, str2): counter = Counter() for letter in str1: counter[letter] += 1 for letter in str2: if not letter in counter: return False counter[letter] -= 1 if counter[letter] == 0: del counter[letter] return len(counter) == 0 class Counter(dict): def __missing__(self, key): return 0 if __name__ == "__main__": import sys print(is_permutation(sys.argv[-2], sys.argv[-1]))
[ { "point_num": 1, "id": "no_function_exceeds_5_params", "question": "Does every function in this file take 5 or fewer parameters (excluding self/cls)?", "answer": true }, { "point_num": 2, "id": "all_params_annotated", "question": "Does every function parameter in this file have a ty...
3
Cracking the Coding Interview/ctci-solutions-master/ch-01-arrays-and-strings/02-is-permutation.py
nikku1234/Code-Practise
from libsaas import http, parsers from libsaas.services import base from . import resource, labels class MilestonesBase(resource.GitHubResource): path = 'milestones' def get_url(self): if self.object_id is None: return '{0}/{1}'.format(self.parent.get_url(), self.path) return '{0}/{1}/{2}'.format(self.parent.get_url(), self.path, self.object_id) class Milestone(MilestonesBase): @base.resource(labels.MilestoneLabels) def labels(self): """ Return the resource corresponding to the labels of this milestone. """ return labels.MilestoneLabels(self) class Milestones(MilestonesBase): @base.apimethod def get(self, state='open', sort='due_date', direction='desc', page=None, per_page=None): """ Fetch milestones for this repository, based on the filter parameters. For details on the meanings and allowed values for each parameter, see {0}. """ url = self.get_url() params = base.get_params( ('state', 'sort', 'direction', 'page', 'per_page'), locals()) return http.Request('GET', url, params), parsers.parse_json get.__doc__ = get.__doc__.format( 'http://developer.github.com/v3/issues/milestones/' '#list-milestones-for-a-repository')
[ { "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
libsaas/services/github/milestones.py
MidtownFellowship/libsaas
""" Copyright 2020 The OneFlow Authors. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ import unittest import oneflow as flow import oneflow.unittest from oneflow.test_utils.automated_test_util import * @autotest(n=1, check_graph=False) def do_test_dot_impl(test_case, placement, sbp): k = random(100, 1000) * 8 x = random_tensor(ndim=1, dim0=k).to_global(placement=placement, sbp=sbp) y = random_tensor(ndim=1, dim0=k).to_global(placement=placement, sbp=sbp) z = torch.dot(x, y) return z class TestDotConsistent(flow.unittest.TestCase): @globaltest def test_dot(test_case): for placement in all_placement(): for sbp in all_sbp(placement, max_dim=1): do_test_dot_impl(test_case, placement, sbp) 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_params_annotated", "question": "Does every function parameter in this file have a type annotation (excluding self/cl...
3
python/oneflow/test/modules/test_consistent_dot.py
L-Net-1992/oneflow
import torch import pandas as pd from io import BytesIO from subprocess import check_output from . import writing import time def memory(device=0): total_mem = torch.cuda.get_device_properties(f'cuda:{device}').total_memory writing.max(f'gpu-memory/cache/{device}', torch.cuda.max_memory_cached(device)/total_mem) torch.cuda.reset_max_memory_cached() writing.max(f'gpu-memory/alloc/{device}', torch.cuda.max_memory_allocated(device)/total_mem) torch.cuda.reset_max_memory_allocated() torch.cuda.reset_max_memory_cached() def dataframe(): """Use `nvidia-smi --help-query-gpu` to get a list of query params""" params = { 'device': 'index', 'compute': 'utilization.gpu', 'access': 'utilization.memory', 'memused': 'memory.used', 'memtotal': 'memory.total', 'fan': 'fan.speed', 'power': 'power.draw', 'temp': 'temperature.gpu'} command = f"""nvidia-smi --format=csv,nounits,noheader --query-gpu={','.join(params.values())}""" df = pd.read_csv(BytesIO(check_output(command, shell=True)), header=None) df.columns = list(params.keys()) df = df.set_index('device') df = df.apply(pd.to_numeric, errors='coerce') return df _last = -1 def vitals(device=None, throttle=0): # This is a fairly expensive op, so let's avoid doing it too often global _last if time.time() - _last < throttle: return _last = time.time() df = dataframe() if device is None: pass elif isinstance(device, int): df = df.loc[[device]] else: df = df.loc[device] fields = ['compute', 'access', 'fan', 'power', 'temp'] for (device, field), value in df[fields].stack().iteritems(): writing.mean(f'gpu/{field}/{device}', value) for device in df.index: writing.mean(f'gpu/memory/{device}', 100*df.loc[device, 'memused']/df.loc[device, 'memtotal'])
[ { "point_num": 1, "id": "has_nested_function_def", "question": "Does this file contain any function defined inside another function?", "answer": false }, { "point_num": 2, "id": "no_function_exceeds_5_params", "question": "Does every function in this file take 5 or fewer parameters (...
3
rebar/stats/gpu.py
JulianKu/megastep
from django.db import models from django.conf import settings class EducationalInstitution(models.Model): name = models.CharField(max_length=255) def __str__(self): return self.name @classmethod def get_institutions_with_enrolled_students(cls): """ For recruiters to use, so they can know which institutions are relevant to choose students from. """ return cls.objects.filter(students__isnull=False) class Student(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, primary_key=True) full_name = models.CharField(max_length=255) email = models.EmailField(max_length=255) date_of_birth = models.DateField() phone_number = models.CharField(max_length=15, blank=True) educational_institution = models.ForeignKey(EducationalInstitution, on_delete=models.PROTECT, default=None, related_name="students") graduation_date = models.DateField() def __str__(self): return f'{self.full_name}' @classmethod def get_students_enrolled_at_specified_institutions(cls, institutions): """ For recruiters to use when they want to only view students from specific institutions. """ return cls.objects.filter(educational_institution__in=institutions) @classmethod def get_students_that_graduate_after_specified_year(cls, year): """ For recruiters to use when they want to view students according to their graduation year. """ return cls.objects.filter(graduation_date__year__gte=year)
[ { "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_class_has_docstring", "question": "Does every class in this file have a docstring?", "answer": false },...
3
student/models.py
yaelerdr/SJMaster
from nxt.sensor import * class ColorControl(object): def __init__(self, brick): self.brick = brick self.colorSensor = Color20(brick, PORT_1) def get_color(self): return self.colorSensor.get_color() def get_light_color(self): return self.colorSensor.get_light_color() def set_light_color(self, color): self.colorSensor.set_light_color(color)
[ { "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
brick_control/colorControl.py
GambuzX/Pixy-SIW
from ...shared.utils.restApi import RestResource from ...shared.utils.api_utils import build_req_parser from ..models.statistics import Statistic from ..models.quota import ProjectQuota class StatisticAPI(RestResource): result_rules = ( dict(name="ts", type=int, location="json"), dict(name="results", type=str, location="json"), dict(name="stderr", type=str, location="json") ) def __init__(self): super().__init__() self.__init_req_parsers() def __init_req_parsers(self): self._result_parser = build_req_parser(rules=self.result_rules) def get(self, project_id: int): statistic = Statistic.query.filter_by(project_id=project_id).first().to_json() quota = ProjectQuota.query.filter_by(project_id=project_id).first().to_json() stats = {} for each in ["performance_test_runs", "ui_performance_test_runs", "sast_scans", "dast_scans", "storage_space", "tasks_count", "tasks_executions"]: stats[each] = {"current": statistic[each], "quota": quota[each]} stats["data_retention_limit"] = {"current": 0, "quota": quota["data_retention_limit"]} return stats
[ { "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
api/statistics.py
nikitosboroda/projects
import os, sys, requests from flask import Flask, request from flask_restful import Resource, Api app = Flask(__name__) api = Api(app) #curl -H "Content-Type: application/json" -X POST -d '{"job_id":"ac97682c-c81e-4170-bb46-8301df317587"}' http://localhost:9000/scheduled-bod class UIHRecurrence(Resource): def post(self): """Receive Post from UIH-scheduler""" data = request.get_json() res_msg = "Launching job id : '{0}'".format(data['job_id']) print(data['job_id']) return res_msg, 200 def main(*args, **kwargs): print('Press Ctrl+{0} to exit'.format('Break' if os.name == 'nt' else 'C')) try: if len(sys.argv) > 2 and sys.argv[1] == 'debug': app.debug = True else: app.debug = False app.run(host='localhost', port=9000) except (KeyboardInterrupt, SystemExit): print("Exit program") if __name__ == '__main__': api.add_resource(UIHRecurrence, '/scheduled-bod') main()
[ { "point_num": 1, "id": "more_functions_than_classes", "question": "Does this file define more functions than classes?", "answer": true }, { "point_num": 2, "id": "has_multiple_inheritance", "question": "Does any class in this file use multiple inheritance?", "answer": false },...
3
main.py
elcolie/scheduled-bod
def dev_cors_middleware(get_response): """ Adds CORS headers for local testing only to allow the frontend, which is served on localhost:3000, to access the API, which is served on localhost:8000. """ def middleware(request): response = get_response(request) if request.META['HTTP_HOST'] == '127.0.0.1:8000': response['Access-Control-Allow-Origin'] = 'http://localhost:8000' elif request.META['HTTP_HOST'] == '127.0.0.1:3000': response['Access-Control-Allow-Origin'] = 'http://localhost:3000' response['Access-Control-Allow-Methods'] = 'GET, POST, PUT, PATCH, OPTIONS, DELETE, HEAD' response['Access-Control-Allow-Headers'] = 'Content-Type, X-CSRFToken' response['Access-Control-Allow-Credentials'] = 'true' return response return middleware
[ { "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
myblog/myblog/middleware.py
daxia07/fancyBlog
from autosklearn.pipeline.constants import DENSE, UNSIGNED_DATA, INPUT, SPARSE from autosklearn.pipeline.components.data_preprocessing.rescaling.abstract_rescaling \ import Rescaling from autosklearn.pipeline.components.base import AutoSklearnPreprocessingAlgorithm class NoRescalingComponent(Rescaling, AutoSklearnPreprocessingAlgorithm): def __init__(self, random_state=None): pass def fit(self, X, y=None): return self def transform(self, X): return X @staticmethod def get_properties(dataset_properties=None): return {'shortname': 'NoRescaling', 'name': 'NoRescaling', 'handles_missing_values': False, 'handles_nominal_values': False, 'handles_numerical_features': True, 'prefers_data_scaled': False, 'prefers_data_normalized': False, 'handles_regression': True, 'handles_classification': True, 'handles_multiclass': True, 'handles_multilabel': True, 'handles_multioutput': True, 'is_deterministic': True, # TODO find out if this is right! 'handles_sparse': True, 'handles_dense': True, 'input': (SPARSE, DENSE, UNSIGNED_DATA), 'output': (INPUT,), 'preferred_dtype': None}
[ { "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
autosklearn/pipeline/components/data_preprocessing/rescaling/none.py
ihounie/auto-sklearn
from conans import ConanFile, CMake class LibB(ConanFile): name = "libB" version = "0.0" settings = "os", "arch", "compiler", "build_type" options = {"shared": [True, False]} default_options = {"shared": False} generators = "cmake" scm = {"type": "git", "url": "auto", "revision": "auto"} exports_sources = "LICENSE" # to avoid build info bug def requirements(self): self.requires("libA/[>=0.0]@demo/testing") self.requires("libF/0.0@demo/testing") def build(self): cmake = CMake(self) cmake.configure() cmake.build() cmake.install() def package(self): self.copy("LICENSE", dst="licenses") def package_info(self): self.cpp_info.libs = ["libB",]
[ { "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
conanfile.py
demo-ci-conan/libB
from django.core.exceptions import ValidationError from django.utils.translation import ugettext_lazy as _ import datetime # for checking renewal date range. from django import forms class RenewBookForm(forms.Form): """Form for a librarian to renew books.""" renewal_date = forms.DateField( help_text="Enter a date between now and 4 weeks (default 3).") def clean_renewal_date(self): data = self.cleaned_data['renewal_date'] # Check date is not in past. if data < datetime.date.today(): raise ValidationError(_('Invalid date - renewal in past')) # Check date is in range librarian allowed to change (+4 weeks) if data > datetime.date.today() + datetime.timedelta(weeks=4): raise ValidationError( _('Invalid date - renewal more than 4 weeks ahead')) # Remember to always return the cleaned data. return data class ReturnBookForm(forms.Form): """Form for a librarian to renew books.""" return_date = forms.DateField( help_text="Enter a date between borrow date and today.") penalty = forms.IntegerField( help_text="Penalty (in IDR).", initial=0) def clean_return_date(self): data = self.cleaned_data['return_date'] # Check date is not in future. if data > datetime.date.today(): raise ValidationError(_('Invalid date - return in future')) return data
[ { "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": false }...
3
catalog/forms.py
PMPL-Arieken/django-locallibrary-tutorial
import pytest from astropy.io import fits import numpy as np from numpy.testing import assert_array_equal from lightkurve.io.k2sff import read_k2sff_lightcurve from lightkurve import search_lightcurve @pytest.mark.remote_data def test_read_k2sff(): """Can we read K2SFF files?""" url = "http://archive.stsci.edu/hlsps/k2sff/c16/212100000/00236/hlsp_k2sff_k2_lightcurve_212100236-c16_kepler_v1_llc.fits" f = fits.open(url) # Verify different extensions fluxes = [] for ext in ["BESTAPER", "CIRC_APER9"]: lc = read_k2sff_lightcurve(url, ext=ext) assert type(lc).__name__ == "KeplerLightCurve" # Are `time` and `flux` consistent with the FITS file? assert_array_equal(f[ext].data["T"], lc.time.value) assert_array_equal(f[ext].data["FCOR"], lc.flux.value) fluxes.append(lc.flux) # Different extensions should show different fluxes assert not np.array_equal(fluxes[0], fluxes[1]) @pytest.mark.remote_data def test_search_k2sff(): """Can we search and download a K2SFF light curve?""" # Try an early campaign search = search_lightcurve("K2-18", author="K2SFF", campaign=1) assert len(search) == 1 assert search.table["author"][0] == "K2SFF" lc = search.download() assert type(lc).__name__ == "KeplerLightCurve" assert lc.campaign == 1 # Try a late campaign lc = search_lightcurve("GJ 9827", author="K2SFF", campaign=19).download() assert type(lc).__name__ == "KeplerLightCurve" assert lc.targetid == 246389858 assert lc.campaign == 19
[ { "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
tests/io/test_k2sff.py
jorgemarpa/lightkurve
import discord from discord.ext import commands from Systems.levelsys import levelling import os from Systems.gettext_init import GettextInit # Set up environment variables: PREFIX = os.environ["BOT_PREFIX"] # Set up gettext _ = GettextInit(__file__).generate() # Spam system class class xpcolour(commands.Cog): def __init__(self, client): self.client = client @commands.command() async def xpcolour(self, ctx, colour=None): await ctx.message.delete() if colour: levelling.update_one({"guildid": ctx.guild.id, "id": ctx.author.id}, {"$set": {"xp_colour": f"{colour}"}}) embed = discord.Embed(title=_(":white_check_mark: **XP COLOUR CHANGED!**"), description=_("Your xp colour has been changed. If you type ") + PREFIX + _("rank and nothing appears, try a new hex code. \n**Example**:\n*#0000FF* = " "*Blue*")) embed.set_thumbnail( url="https://cdn.discordapp.com/attachments/812895798496591882/825363205853151252/ML_1.png") await ctx.send(embed=embed) elif colour is None: embed = discord.Embed(title=_(":x: **SOMETHING WENT WRONG!**"), description=_("Please make sure you typed a hex code in!.")) await ctx.send(embed=embed) return xpcolour.__doc__ = _('''\nxpcolour <hex code> \n\nAbout:\nThe XPColour command will allow you to change your rank cards xp bar colour to any hex code of your choosing.''') # Sets-up the cog for help def setup(client): client.add_cog(xpcolour(client))
[ { "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
Commands/xpcolour/xpcolour.py
Chromeilion/kyoshi
# Thomas (Desnord) # O objetivo desta tarefa é fazer um programa # que use recursividade e que, dada a matriz # que descreve a hierarquia de uma empresa, # encontre a cadeia hierárquica relativa a # um determinado funcionário. #entrada: # A primeira linha contém dois inteiros: n, # o número de funcionários entre 3 e 30, e k, # o identificador numérico do funcionário sobre # o qual deseja-se conhecer a cadeira hierárquica. # A seguir tem-se n linhas que correspondem as # linhas da matriz que descrevem a hierarquia # da empresa. #saída: # Na saída devem ser impressos os números # que identificam todos os funcionários # que estejam na cadeia hierárquica do # funcionário k, começando pelo próprio, # e então imprimindo, em ordem crescente # por identificador, os outros funcionários. '''------------------------------------------''' #lendo entradas nk = input().split() n = int(nk[0]) k = int(nk[1]) matriz = [] for i in range(n): linha = input().split() matriz.append(linha) resultado = [] resultado.append(k) #função recursiva para achar a cadeia hierarquica def cadeiahier(mat, res): aux = res[:] for i in range(len(mat[aux[len(aux)-1]])): if(int(mat[aux[len(aux)-1]][i]) == 1): res.append(i) res = cadeiahier(mat, res) return res #função para ordernar def ckts(res): for w in range(len(res)-1, 0, -1): trocou = False for i in range(w, 0, -1): if (res[i] < res[i-1]): res[i], res[i-1] = res[i-1], res[i] trocou = True for i in range(w): if (res[i] > res[i+1]): res[i], res[i+1] = res[i+1], res[i] trocou = True if not trocou: return res return res #gera a cadeia hierárquica resultado = cadeiahier(matriz,resultado) #arrumando a saída no formato exigido resultado.remove(k) if(len(resultado) != 0): resultado = ckts(resultado) resstr = ' '.join(map(str, resultado)) print(str(k) +' '+ str(resstr)) else: print(k)
[ { "point_num": 1, "id": "no_function_exceeds_5_params", "question": "Does every function in this file take 5 or fewer parameters (excluding self/cls)?", "answer": true }, { "point_num": 2, "id": "all_params_annotated", "question": "Does every function parameter in this file have a ty...
3
lab19/thomas.py
Desnord/lab-mc102
from django_unicorn.components import QuerySetType, UnicornView from example.coffee.models import Flavor, Taste class AddFlavorView(UnicornView): is_adding = False flavors = None flavor_qty = 1 flavor_id = None def __init__(self, *args, **kwargs): super().__init__(**kwargs) # calling super is required self.flavor_id = kwargs.get('flavor_id') self.is_adding = False def create(self): if int(self.flavor_qty) > 0: for i in range(int(self.flavor_qty)): flavor = Flavor.objects.create(id = self.flavor_id) flavor.save() print("create flavor") self.is_adding = False self.show_table() def add_flavor(self): self.is_adding = True self.show_table() def cancel(self): self.is_adding = False self.show_table() def show_table(self): self.flavors = Flavor.objects.all() def mount(self): self.show_table()
[ { "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
example/unicorn/components/add_flavor.py
Franziskhan/django-unicorn
""" Upwork OAuth1 backend """ from .oauth import BaseOAuth1 class UpworkOAuth(BaseOAuth1): """Upwork OAuth authentication backend""" name = 'upwork' ID_KEY = 'id' AUTHORIZATION_URL = 'https://www.upwork.com/services/api/auth' REQUEST_TOKEN_URL = 'https://www.upwork.com/api/auth/v1/oauth/token/request' REQUEST_TOKEN_METHOD = 'POST' ACCESS_TOKEN_URL = 'https://www.upwork.com/api/auth/v1/oauth/token/access' ACCESS_TOKEN_METHOD = 'POST' REDIRECT_URI_PARAMETER_NAME = 'oauth_callback' def get_user_details(self, response): """Return user details from Upwork account""" info = response.get('info', {}) auth_user = response.get('auth_user', {}) first_name = auth_user.get('first_name') last_name = auth_user.get('last_name') fullname = '{} {}'.format(first_name, last_name) profile_url = info.get('profile_url', '') username = profile_url.rsplit('/')[-1].replace('~', '') return { 'username': username, 'fullname': fullname, 'first_name': first_name, 'last_name': last_name } def user_data(self, access_token, *args, **kwargs): """Loads user data from service""" return self.get_json( 'https://www.upwork.com/api/auth/v1/info.json', auth=self.oauth_auth(access_token) )
[ { "point_num": 1, "id": "every_function_has_docstring", "question": "Does every function in this file have a docstring?", "answer": true }, { "point_num": 2, "id": "more_functions_than_classes", "question": "Does this file define more functions than classes?", "answer": true },...
3
social_core/backends/upwork.py
astofsel/package_2
import random from itertools import chain def split_train_test_without_chaining(proteins, asas, train_ratio): indices = list(range(len(proteins))) random.shuffle(indices) train_indices = indices[:int(train_ratio * len(indices))] test_indices = indices[int(train_ratio * len(indices)):] train_proteins = [proteins[i] for i in train_indices] train_asas = [asas[i] for i in train_indices] test_proteins = [proteins[i] for i in test_indices] test_asas = [asas[i] for i in test_indices] return train_proteins, train_asas, test_proteins, test_asas def split_train_test(proteins, asas, train_ratio): train_proteins, train_asas, test_proteins, test_asas = split_train_test_without_chaining(proteins, asas, train_ratio) train_proteins = list(chain(*train_proteins)) train_asas = list(chain(*train_asas)) test_proteins = list(chain(*test_proteins)) test_asas = list(chain(*test_asas)) return train_proteins, train_asas, test_proteins, test_asas
[ { "point_num": 1, "id": "no_function_exceeds_5_params", "question": "Does every function in this file take 5 or fewer parameters (excluding self/cls)?", "answer": true }, { "point_num": 2, "id": "all_params_annotated", "question": "Does every function parameter in this file have a ty...
3
src/split_train_test.py
ibraheem-moosa/protein-asa-prediction
# /usr/bin/env python # coding=utf-8 from pylinux.common.file_config.rc_local_file_config import RcLocalFileConfig from pylinux.common.modifier.rc_local_modifier import RcLocalModifier from pylinux.common.acessor.rc_local_accessor import RcLocalAccessor from pylinux.system_file.base_system_file import BaseSystemFile from pylinux.exception.name_not_valid_exception import NameNotValidException from pylinux.exception.setting_not_valid_exception import SettingNotValidException class RcLocal(BaseSystemFile): """ rc.local的配置文件类 """ def __init__(self, filepath="/etc/rc.local", searcher=RcLocalAccessor, modifier=RcLocalModifier, file_config=RcLocalFileConfig()): super(RcLocal, self).__init__(filepath, searcher, modifier, file_config=file_config) def add_boot_item(self, cmd, name): """ 增加启动项 :param name: :param cmd: """ if not name: raise NameNotValidException("name not valid while adding boot item") if not cmd: raise SettingNotValidException("setting not valid while adding boot item") def add_multi_line_setting(self, name, value): pass
[ { "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
pylinux/system_file/rc_local.py
ruiruige/pylinux
# -*- coding: utf-8 -*- """Import exampledata""" from os import path as osp import pandas as pd DATADIR = osp.join(osp.dirname(osp.realpath(__file__)), 'exampledata') def getOECD(): return pd.read_table(osp.join(DATADIR, 'Cancer_men_perc.txt'), index_col=0) def getA(): return pd.read_table(osp.join(DATADIR, 'A.txt'), index_col=0) def getB(): return pd.read_table(osp.join(DATADIR, 'B.txt'), index_col=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": "all_function_names_snake_case", "question": "Are all function names in this file written in snake_case?", "answer"...
3
hoggormplot/data.py
olivertomic/hoggormPlot
"""Patient Model Revision ID: 64fb26819d4f Revises: 1f3baa1921c7 Create Date: 2018-07-27 00:50:36.593722 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = '64fb26819d4f' down_revision = '1f3baa1921c7' branch_labels = None depends_on = None def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.create_table('patient', sa.Column('id', sa.Integer(), nullable=False), sa.Column('patient_name', sa.String(length=100), nullable=True), sa.Column('patient_description', sa.String(length=300), nullable=True), sa.Column('patient_lat', sa.Float(), nullable=False), sa.Column('patient_lng', sa.Float(), nullable=False), sa.Column('timestamp', sa.DateTime(), nullable=True), sa.Column('user_id', sa.Integer(), nullable=True), sa.ForeignKeyConstraint(['user_id'], ['user.id'], ), sa.PrimaryKeyConstraint('id') ) op.create_index(op.f('ix_patient_timestamp'), 'patient', ['timestamp'], unique=False) # ### end Alembic commands ### def downgrade(): # ### commands auto generated by Alembic - please adjust! ### op.drop_index(op.f('ix_patient_timestamp'), table_name='patient') op.drop_table('patient') # ### end Alembic commands ###
[ { "point_num": 1, "id": "has_nested_function_def", "question": "Does this file contain any function defined inside another function?", "answer": false }, { "point_num": 2, "id": "every_function_has_docstring", "question": "Does every function in this file have a docstring?", "ans...
3
migrations/versions/64fb26819d4f_patient_model.py
owenabrams/greyapp
from __future__ import print_function from splunklib.searchcommands import dispatch, StreamingCommand, Configuration, Option, validators import sys import socket import struct @Configuration() class IPDecodeCommand(StreamingCommand): def stream(self, records): self.logger.debug('IPDecodeCommand: %s', self) # logs command line for record in records: for field in self.fieldnames: record[field] = self.int2ip(record[field]) yield record def int2ip(self, intIP): try: return socket.inet_ntoa(struct.pack('!L', int(intIP))) except: return '-' dispatch(IPDecodeCommand, sys.argv, sys.stdin, sys.stdout, __name__)
[ { "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
bin/ipdecode.py
onura/Splunk-IPEncoder
from django.contrib.auth.models import User from django.db import models from django.urls import reverse from django.utils.text import slugify from django_md_editor.models import EditorMdField from core.cooggerapp.choices import ISSUE_CHOICES, make_choices from ...threaded_comment.models import AbstractThreadedComments from .common import Common, View, Vote from .topic import UTopic from .utils import dor, second_convert class Issue(AbstractThreadedComments, Common, View, Vote): user = models.ForeignKey(User, on_delete=models.CASCADE) issue_id = models.PositiveIntegerField(default=0) title = models.CharField( max_length=200, help_text="Be sure to choose the best title", null=True, blank=True, ) utopic = models.ForeignKey(UTopic, on_delete=models.CASCADE) body = EditorMdField( null=True, blank=True, help_text="Your problem | question | or anything else" ) status = models.CharField( default="open", choices=make_choices(ISSUE_CHOICES), max_length=55, help_text="Status", null=True, blank=True, ) class Meta: ordering = ["-created"] unique_together = [["user", "issue_id", "utopic"]] @property def get_absolute_url(self): return reverse( "detail-issue", kwargs=dict( username=str(self.utopic.user), utopic_permlink=self.utopic.permlink, issue_id=self.issue_id, ), ) @property def get_dor(self): # TODO this function same in content.py models times = "" for f, t in second_convert(dor(self.body)).items(): if t != 0: times += f" {t}{f} " if times == "": return "0" return times
[ { "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
core/cooggerapp/models/issue.py
bisguzar/coogger
from collections import defaultdict from aoc.util import load_example, load_input def part1(lines): """ >>> part1(load_example(__file__, '6')) 11 """ answers = [] a = {} for line in lines: if not line.strip(): answers.append(len(a.keys())) a = {} else: for k in line.strip(): a[k] = True answers.append(len(a.keys())) return sum(answers) def part2(lines): """ >>> part2(load_example(__file__, '6')) 6 """ answers = [] a = defaultdict(lambda: 0) count_people = 0 for line in lines: if not line.strip(): answers.append(len([1 for v in a.values() if v == count_people])) a = defaultdict(lambda: 0) count_people = 0 else: for k in line.strip(): a[k] += 1 count_people += 1 answers.append(len([1 for v in a.values() if v == count_people])) return sum(answers) if __name__ == "__main__": data = load_input(__file__, 2020, "6") print(part1(data)) print(part2(data))
[ { "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
python/src/aoc/year2020/day6.py
ocirne/adventofcode
from ..script import tools from ...serialize import b2h from .ScriptType import ScriptType class ScriptNulldata(ScriptType): TEMPLATE = tools.compile("OP_RETURN OP_NULLDATA") def __init__(self, nulldata): self.nulldata = nulldata self._script = None @classmethod def from_script(cls, script): r = cls.match(script) if r: nulldata = r["NULLDATA_LIST"][0] s = cls(nulldata) return s raise ValueError("bad script") def script(self): if self._script is None: # create the script STANDARD_SCRIPT_OUT = "OP_RETURN %s" script_text = STANDARD_SCRIPT_OUT % b2h(self.nulldata) self._script = tools.compile(script_text) return self._script def info(self, netcode="BTC"): return dict(type="nulldata", script=self._script, summary=self.nulldata) def __repr__(self): return "<Script: nulldata %s>" % self.nulldata
[ { "point_num": 1, "id": "has_multiple_inheritance", "question": "Does any class in this file use multiple inheritance?", "answer": false }, { "point_num": 2, "id": "all_function_names_snake_case", "question": "Are all function names in this file written in snake_case?", "answer":...
3
lib/pycoin/pycoin/tx/pay_to/ScriptNulldata.py
AYCHDO/Dominus
# Copyright 2014 Google Inc. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from adb import adb_protocol from cryptography.hazmat.backends import default_backend from cryptography.hazmat.primitives import hashes from cryptography.hazmat.primitives import serialization from cryptography.hazmat.primitives.asymmetric import padding from cryptography.hazmat.primitives.asymmetric import utils class CryptographySigner(adb_protocol.AuthSigner): """AuthSigner using cryptography.io.""" def __init__(self, rsa_key_path): with open(rsa_key_path + '.pub') as rsa_pub_file: self.public_key = rsa_pub_file.read() with open(rsa_key_path) as rsa_prv_file: self.rsa_key = serialization.load_pem_private_key( rsa_prv_file.read().encode('ascii'), None, default_backend()) def Sign(self, data): return self.rsa_key.sign( data, padding.PKCS1v15(), utils.Prehashed(hashes.SHA1())) def GetPublicKey(self): return self.public_key
[ { "point_num": 1, "id": "has_multiple_inheritance", "question": "Does any class in this file use multiple inheritance?", "answer": false }, { "point_num": 2, "id": "all_function_names_snake_case", "question": "Are all function names in this file written in snake_case?", "answer":...
3
adb/sign_cryptography.py
4oo4/python-adb
import collections import pytest # noqa: F401 from pudb.py3compat import builtins from pudb.settings import load_breakpoints, save_breakpoints def test_load_breakpoints(mocker): fake_data = ["b /home/user/test.py:41"], ["b /home/user/test.py:50"] mock_open = mocker.mock_open() mock_open.return_value.readlines.side_effect = fake_data mocker.patch.object(builtins, "open", mock_open) mocker.patch("pudb.settings.lookup_module", mocker.Mock(return_value="/home/user/test.py")) mocker.patch("pudb.settings.get_breakpoint_invalid_reason", mocker.Mock(return_value=None)) result = load_breakpoints() expected = [("/home/user/test.py", 41, False, None, None), ("/home/user/test.py", 50, False, None, None)] assert result == expected def test_save_breakpoints(mocker): MockBP = collections.namedtuple("MockBreakpoint", "file line cond") mock_breakpoints = [MockBP("/home/user/test.py", 41, None), MockBP("/home/user/test.py", 50, None)] mocker.patch("pudb.settings.get_breakpoints_file_name", mocker.Mock(return_value="saved-breakpoints")) mock_open = mocker.mock_open() mocker.patch.object(builtins, "open", mock_open) save_breakpoints(mock_breakpoints) mock_open.assert_called_with("saved-breakpoints", "w")
[ { "point_num": 1, "id": "every_function_under_20_lines", "question": "Is every function in this file shorter than 20 lines?", "answer": true }, { "point_num": 2, "id": "every_function_has_docstring", "question": "Does every function in this file have a docstring?", "answer": fals...
3
test/test_settings.py
mm40/pudb
from collections import namedtuple from dataclasses import dataclass, field from datetime import datetime from typing import List from .base import MangadexBase from .exceptions import MangadexException from .group import Group from .language import Language @dataclass(frozen=True) class PartialChapter(MangadexBase): hash: str = None mangaId: int = None mangaTitle: int = None volume: float = None chapter: float = None title: str = None groups: List[int] = field(default_factory=list) uploader: int = None language: Language = Language.NoLang() timestamp: datetime = None comments: int = 0 views: int = None def __hash__(self): return self.hash @classmethod def from_json(cls, json, http): timestamp = datetime.fromtimestamp(json.pop('timestamp')) language = Language(json.pop('language')) return cls(timestamp=timestamp, http=http, language=language, **json) async def download_page(self, page: int, data_saver: bool=True): raise NotImplementedError("Cannot download pages from PartialChapter. Fetch full chapter first.") def download_all_pages(self, data_saver: bool=True): raise NotImplementedError("Cannot download pages from PartialChapter. Fetch full chapter first.") async def fetch_full(self): from .chapter import Chapter return Chapter.from_json(await self.http.fetch_chapter(self.id), http=self.http) async def fetch_uploader(self): raise NotImplementedError
[ { "point_num": 1, "id": "every_function_has_docstring", "question": "Does every function in this file have a docstring?", "answer": false }, { "point_num": 2, "id": "all_function_names_snake_case", "question": "Are all function names in this file written in snake_case?", "answer"...
3
aiomangadex/partialchapter.py
lukesaltweather/aiomangadex
# -*- coding: utf-8 -*- ''' 【简介】 PyQt5中 QCheckBox 例子 ''' import sys from PyQt5.QtCore import * from PyQt5.QtGui import * from PyQt5.QtWidgets import * from PyQt5.QtCore import Qt class CheckBoxDemo(QWidget): def __init__(self, parent=None): super(CheckBoxDemo , self).__init__(parent) groupBox = QGroupBox("Checkboxes") groupBox.setFlat( False ) layout = QHBoxLayout() self.checkBox1= QCheckBox("&Checkbox1") self.checkBox1.setChecked(True) self.checkBox1.stateChanged.connect( lambda:self.btnstate(self.checkBox1) ) layout.addWidget(self.checkBox1) self.checkBox2 = QCheckBox("Checkbox2") self.checkBox2.toggled.connect( lambda:self.btnstate(self.checkBox2) ) layout.addWidget(self.checkBox2) self.checkBox3 = QCheckBox("tristateBox") self.checkBox3.setTristate(True) self.checkBox3.setCheckState(Qt.PartiallyChecked ) self.checkBox3.stateChanged.connect( lambda:self.btnstate(self.checkBox3) ) layout.addWidget(self.checkBox3) groupBox.setLayout(layout) mainLayout = QVBoxLayout() mainLayout.addWidget(groupBox) self.setLayout(mainLayout) self.setWindowTitle("checkbox demo") def btnstate(self,btn ): chk1Status = self.checkBox1.text()+", isChecked="+ str( self.checkBox1.isChecked() ) + ', chekState=' + str(self.checkBox1.checkState()) +"\n" chk2Status = self.checkBox2.text()+", isChecked="+ str( self.checkBox2.isChecked() ) + ', checkState=' + str(self.checkBox2.checkState()) +"\n" chk3Status = self.checkBox3.text()+", isChecked="+ str( self.checkBox3.isChecked() ) + ', checkState=' + str(self.checkBox3.checkState()) +"\n" print(chk1Status + chk2Status + chk3Status ) if __name__ == '__main__': app = QApplication(sys.argv) checkboxDemo = CheckBoxDemo() checkboxDemo.show() sys.exit(app.exec_())
[ { "point_num": 1, "id": "every_function_under_20_lines", "question": "Is every function in this file shorter than 20 lines?", "answer": false }, { "point_num": 2, "id": "has_nested_function_def", "question": "Does this file contain any function defined inside another function?", ...
3
PyQt5-master/PyQt5-master/Chapter04/qt0410_QCheckbox.py
chaiwenda/Qt-mind
from django.contrib.auth.models import AbstractUser from django.db import models from django.utils.translation import gettext_lazy as _ from . import managers class CustomUser(AbstractUser): username = models.CharField( max_length=150, help_text=_("The username of the user."), unique=True ) email = models.EmailField(help_text=_("Email of the user."), unique=True) USERNAME_FIELD = "email" REQUIRED_FIELDS = ["username"] objects = managers.CustomUserManager() class Meta: ordering = ("id",) def __str__(self): return f"{self.email}'s account"
[ { "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
example_project/example_app/models.py
IgnisDa/django-tokens
# -*- coding: utf-8 -*- # Define here the models for your spider middleware # # See documentation in: # http://doc.scrapy.org/en/latest/topics/spider-middleware.html from scrapy import signals class SpacebattlesSpiderMiddleware(object): # Not all methods need to be defined. If a method is not defined, # scrapy acts as if the spider middleware does not modify the # passed objects. @classmethod def from_crawler(cls, crawler): # This method is used by Scrapy to create your spiders. s = cls() crawler.signals.connect(s.spider_opened, signal=signals.spider_opened) return s def process_spider_input(response, spider): # Called for each response that goes through the spider # middleware and into the spider. # Should return None or raise an exception. return None def process_spider_output(response, result, spider): # Called with the results returned from the Spider, after # it has processed the response. # Must return an iterable of Request, dict or Item objects. for i in result: yield i def process_spider_exception(response, exception, spider): # Called when a spider or process_spider_input() method # (from other spider middleware) raises an exception. # Should return either None or an iterable of Response, dict # or Item objects. pass def process_start_requests(start_requests, spider): # Called with the start requests of the spider, and works # similarly to the process_spider_output() method, except # that it doesn’t have a response associated. # Must return only requests (not items). for r in start_requests: yield r def spider_opened(self, spider): spider.logger.info('Spider opened: %s' % spider.name)
[ { "point_num": 1, "id": "no_function_exceeds_5_params", "question": "Does every function in this file take 5 or fewer parameters (excluding self/cls)?", "answer": true }, { "point_num": 2, "id": "every_function_under_20_lines", "question": "Is every function in this file shorter than...
3
scrapers/Spacebattles/Spacebattles/middlewares.py
NovelTorpedo/noveltorpedo
import os, sys import typing import discord class TestPlugin: async def ping_func(message, discord_client: object) -> str: await discord_client.send_message(message.channel, "WE WUZ KINGS N SHIET") async def echo_func( message, discord_client: object) -> str: await discord_client.send_message(message.channel, message.content.split("!echo ")[-1]) async def echoto_func(message, discord_client: object) -> str: temp = message.content.split() await discord_client.send_message(discord.Object(id=temp[1]), temp[2])
[ { "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
plugin/test_plugin/__main__.py
Joule4247532/CS-Army-World-Destroying-Discord-Bot
#!/usr/bin/env python3 from test_framework.test_framework import BitcoinTestFramework from test_framework.util import * from test_framework.script import * from test_framework.mininode import * from test_framework.address import * from test_framework.qtum import * class QtumEVMConstantinopleActivationTest(BitcoinTestFramework): def set_test_params(self): self.setup_clean_chain = True self.num_nodes = 1 self.extra_args = [['-txindex=1', '-logevents=1', '-constantinopleheight=552']] def skip_test_if_missing_module(self): self.skip_if_no_wallet() def run_test(self): self.nodes[0].generate(COINBASE_MATURITY+50) self.node = self.nodes[0] """ pragma solidity ^0.5; contract PostConstantinopleOpCodesTest { constructor() public { uint256 x; assembly { x := shl(2, 2) } } } """ bytecode = "6080604052348015600f57600080fd5b5060006002801b90505060358060266000396000f3fe6080604052600080fdfea165627a7a7230582050b41bb4079fe4c4ec2ab007d83304ad1680585dd519d188151a4ff4af2f4ded0029" for i in range(5): self.node.createcontract(bytecode)['address'] self.node.generate(1) if __name__ == '__main__': QtumEVMConstantinopleActivationTest().main()
[ { "point_num": 1, "id": "has_multiple_inheritance", "question": "Does any class in this file use multiple inheritance?", "answer": false }, { "point_num": 2, "id": "all_function_names_snake_case", "question": "Are all function names in this file written in snake_case?", "answer":...
3
test/functional/qtum_evm_constantinople_activation.py
TopoX84/newlux
from myimageboard_1.models.MainModel import MainModel from myimageboard_1.models.UsersModel import UsersModel class MainController: def __init__(self, request = None): self.main = MainModel() self.users = UsersModel() if request != None: self.request = request self.session_signin() def session_signin(self): if hasattr(self, "request") and hasattr(self.request, "session") and "user_id" in self.request.session: self.users.signin(self.request.session['user_id']) def signed_user(self): return self.users.signed()
[ { "point_num": 1, "id": "has_multiple_inheritance", "question": "Does any class in this file use multiple inheritance?", "answer": false }, { "point_num": 2, "id": "every_function_under_20_lines", "question": "Is every function in this file shorter than 20 lines?", "answer": true...
3
src-python/myimageboard_1/controllers/MainController.py
yuriysydor1991/repository-4-imageboard1
class MessageId: """The CAN MessageId of an PDU. The MessageId consists of three parts: * Priority * Parameter Group Number * Source Address """ def __init__(self, **kwargs): #priority=0, parameter_group_number=0, source_address=0): """ :param priority: 3-bit Priority :param parameter_group_number: 18-bit Parameter Group Number :param source_address: 8-bit Source Address There is a total of 253 addresses available and every address must be unique within the network. :param can_id: A 29-bit CAN-Id the MessageId should be parsed from. """ if 'can_id' in kwargs: # let the property can_id parse the given value self.can_id = kwargs.get('can_id') else: self.priority = kwargs.get('priority', 0) & 7 self.parameter_group_number = kwargs.get('parameter_group_number', 0) & 0x3FFFF self.source_address = kwargs.get('source_address', 0) & 0xFF @property def can_id(self): """Transforms the MessageId object to a 29 bit CAN-Id""" return (self.priority << 26) | (self.parameter_group_number << 8) | (self.source_address) @can_id.setter def can_id(self, can_id): """Fill the MessageId with the information given in the 29 bit CAN-Id""" self.source_address = can_id & 0xFF self.parameter_group_number = (can_id >> 8) & 0x3FFFF self.priority = (can_id >> 26) & 0x7
[ { "point_num": 1, "id": "every_function_has_docstring", "question": "Does every function in this file have a docstring?", "answer": true }, { "point_num": 2, "id": "all_function_names_snake_case", "question": "Are all function names in this file written in snake_case?", "answer":...
3
j1939/message_id.py
rliebscher/python-can-j1939
import disnake as discord import random from disnake.ext import commands from api.check import utils, block from api.server import base, main class Gay(commands.Cog): def __init__(self, client): self.client = client @commands.command() @block.block() async def gay(self, ctx, user: discord.Member = None): if not user: user = ctx.author embed = discord.Embed(color = 9579219) embed.add_field(name = main.get_lang(ctx.guild, 'GAY_FIELD_TITLE'), value = main.get_lang(ctx.guild, 'GAY_FIELD_VALUE').format(user.mention, random.randint(1,100))) await ctx.reply(embed = embed) def setup(client): client.add_cog(Gay(client))
[ { "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
commands/gay.py
DiscordHackers/BetterBot-1.0.2.2
from rest_framework_jwt.views import JSONWebTokenAPIView from rest_framework_jwt.serializers import JSONWebTokenSerializer from django.contrib.auth import authenticate from rest_framework import serializers from django.utils.translation import ugettext as _ from rest_framework_jwt.settings import api_settings jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER class AdminJSONWebTokenSerializer(JSONWebTokenSerializer): def validate(self, attrs): credentials = { self.username_field: attrs.get(self.username_field), 'password': attrs.get('password') } if all(credentials.values()): user = authenticate(**credentials) if user: if not user.is_active: msg = _('User account is disabled.') raise serializers.ValidationError(msg) # 新增添加 if not user.is_staff: msg = _('User account is disabled.') raise serializers.ValidationError(msg) payload = jwt_payload_handler(user) return { 'token': jwt_encode_handler(payload), 'user': user } else: msg = _('Unable to log in with provided credentials.') raise serializers.ValidationError(msg) else: msg = _('Must include "{username_field}" and "password".') msg = msg.format(username_field=self.username_field) raise serializers.ValidationError(msg) class AdminJsonWebTokenAPIView(JSONWebTokenAPIView): serializer_class = AdminJSONWebTokenSerializer admin_jwt_token=AdminJsonWebTokenAPIView.as_view()
[ { "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
meiduo_mall/apps/meiduo_admin/login.py
zhengcongreal/meiduo_project-
"""""" from screws.freeze.main import FrozenOnly from objects.CSCG._3d.forms.standard.base.dofs.visualize.matplot._0sf import _3dCSCG_S0F_DOFs_Matplot from objects.CSCG._3d.forms.standard.base.dofs.visualize.matplot._1sf import _3dCSCG_S1F_DOFs_Matplot from objects.CSCG._3d.forms.standard.base.dofs.visualize.matplot._2sf import _3dCSCG_S2F_DOFs_Matplot from objects.CSCG._3d.forms.standard.base.dofs.visualize.matplot._3sf import _3dCSCG_S3F_DOFs_Matplot class _3dCSCG_SF_DOFs_VISUALIZE(FrozenOnly): """""" def __init__(self, dofs): """""" self._dofs_ = dofs self._matplot_ = None self._freeze_self_() def __call__(self, *args, **kwargs): return self.matplot(*args, **kwargs) @property def matplot(self): if self._matplot_ is None: if self._dofs_._sf_.k == 0: self._matplot_ = _3dCSCG_S0F_DOFs_Matplot(self._dofs_) elif self._dofs_._sf_.k == 1: self._matplot_ = _3dCSCG_S1F_DOFs_Matplot(self._dofs_) elif self._dofs_._sf_.k == 2: self._matplot_ = _3dCSCG_S2F_DOFs_Matplot(self._dofs_) elif self._dofs_._sf_.k == 3: self._matplot_ = _3dCSCG_S3F_DOFs_Matplot(self._dofs_) else: raise Exception() return self._matplot_
[ { "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
objects/CSCG/_3d/forms/standard/base/dofs/visualize/main.py
mathischeap/mifem
"""Preprocess the Vivi Ornitier model The model is available for download from https://sketchfab.com/models/be1e505ef3304343bf00736644730c70 The Python Imaging Library is required pip install pillow """ from __future__ import print_function import json import os import zipfile from PIL import Image from .utils.gltf import dump_obj_data SRC_FILENAME = "vivi_ornitier_-_retrogasm_art_competition.zip" DST_DIRECTORY = "../assets/vivi" IMG_FILENAMES = { "textures/lambert14SG_baseColor.png": "vivi_diffuse.tga", "textures/lambert16SG_baseColor.png": "floor_diffuse.tga", } def process_meshes(zip_file): gltf = json.loads(zip_file.read("scene.gltf")) buffer = zip_file.read("scene.bin") for mesh_index in range(len(gltf["meshes"])): obj_data = dump_obj_data(gltf, buffer, mesh_index) filename = "vivi{}.obj".format(mesh_index) filepath = os.path.join(DST_DIRECTORY, filename) with open(filepath, "w") as f: f.write(obj_data) def load_image(zip_file, filename): with zip_file.open(filename) as f: image = Image.open(f) image = image.transpose(Image.FLIP_TOP_BOTTOM) return image def save_image(image, filename, size=512): if max(image.size) > size: image = image.resize((size, size), Image.LANCZOS) filepath = os.path.join(DST_DIRECTORY, filename) image.save(filepath, rle=True) def process_images(zip_file): for old_filename, tga_filename in IMG_FILENAMES.items(): image = load_image(zip_file, old_filename) save_image(image, tga_filename) def main(): if not os.path.exists(DST_DIRECTORY): os.makedirs(DST_DIRECTORY) with zipfile.ZipFile(SRC_FILENAME) as zip_file: process_meshes(zip_file) process_images(zip_file) 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": "every_function_has_docstring", "question": "Does every function in this file have a docst...
3
scripts/vivi.py
FTD2012/software-renderer
from rlcard.agents.nfsp_agent import NFSPAgent from rlcard.agents.dqn_agent import DQNAgent from rlcard.agents.random_agent import RandomAgent from rlcard.utils.pettingzoo_utils import wrap_state class NFSPAgentPettingZoo(NFSPAgent): def step(self, state): return super().step(wrap_state(state)) def eval_step(self, state): return super().eval_step(wrap_state(state)) def feed(self, ts): state, action, reward, next_state, done = tuple(ts) state = wrap_state(state) next_state = wrap_state(next_state) ts = (state, action, reward, next_state, done) return super().feed(ts) class DQNAgentPettingZoo(DQNAgent): def step(self, state): return super().step(wrap_state(state)) def eval_step(self, state): return super().eval_step(wrap_state(state)) def feed(self, ts): state, action, reward, next_state, done = tuple(ts) state = wrap_state(state) next_state = wrap_state(next_state) ts = (state, action, reward, next_state, done) return super().feed(ts) class RandomAgentPettingZoo(RandomAgent): def step(self, state): return super().step(wrap_state(state)) def eval_step(self, state): return super().eval_step(wrap_state(state))
[ { "point_num": 1, "id": "has_nested_function_def", "question": "Does this file contain any function defined inside another function?", "answer": false }, { "point_num": 2, "id": "all_params_annotated", "question": "Does every function parameter in this file have a type annotation (ex...
3
rlcard/agents/pettingzoo_agents.py
xiviu123/rlcard
from .layer_norm import LayerNorm from . import dy_model @dy_model class SublayerConnection: """ A residual connection followed by a layer norm. Note for code simplicity the norm is first as opposed to last. """ def __init__(self, model, size, p): pc = model.add_subcollection() self.norm = LayerNorm(pc, size) self.p = p self.spec = (size, p) def __call__(self, x, sublayer): "Apply residual connection to any sublayer with the same size." return x + dy.dropout(sublayer(self.norm(x)), self.p)
[ { "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
antu/nn/dynet/modules/sublayer.py
AntNLP/pyAnt
from unittest import TestCase from maki.color import Color class ColorTest(TestCase): def test_is_light(self): self.assertTrue(Color.from_hex("#ffffff").is_light) self.assertTrue(Color.from_hex("#fff").is_light) self.assertFalse(Color.from_hex("#000").is_light) def test_invalid_hex(self): with self.assertRaises(ValueError): Color.from_hex("azz") def test_valid_hex(self): self.assertEqual(Color.from_hex("000").rgb, (0, 0, 0)) self.assertEqual(Color.from_hex("aff").rgb, (170, 255, 255)) def test_equality(self): self.assertEqual(Color.from_hex("#fff"), Color(255, 255, 255)) self.assertEqual(Color.from_hex("aff"), Color.from_hex("aaffff")) def test_luminance(self): self.assertEqual(Color(0, 0, 0).luminance, 0) self.assertEqual(Color(255, 255, 255).luminance, 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": "has_multiple_inheritance", "question": "Does any class in this file use multiple inheritance?", "answer": false ...
3
tests/test_color.py
zostera/python-makiwich
def generateMatrice(data, K_mer, k): # Variables X = [] # Generate K-mer dictionnary X_dict = {} for i, e in enumerate(K_mer): X_dict[e] = 0; # Generates X (matrix attributes) for d in data: x = [] x_dict = X_dict.copy() # Count K-mer occurences (with overlaping) for i in range(0, len(d[1]) - k + 1, 1): try: x_dict[d[1][i:i + k]] = x_dict[d[1][i:i + k]] + 1; except: pass # Get only occurences from dictionnary for value in x_dict: x.append(x_dict.get(value)) X.append(x) # Return matrices X (matrix attributes) return X def generateXYMatrice(data, K_mer, k): # Variables X = generateMatrice(data, K_mer, k) y = [] # Generates y (matrix class) for i in data: y.append(i[2]) # Return matrices X and y (matrix attributes and matrix class) return X, y
[ { "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
castor_krfe/matrices.py
maremita/CASTOR_KRFE
import os import unittest import json from spaceone.core.unittest.runner import RichTestRunner from spaceone.tester import TestCase, print_json GOOGLE_APPLICATION_CREDENTIALS_PATH = os.environ.get('GOOGLE_APPLICATION_CREDENTIALS', None) if GOOGLE_APPLICATION_CREDENTIALS_PATH is None: print(""" ################################################## # ERROR # # Configure your GCP credential first for test # https://console.cloud.google.com/apis/credentials ################################################## example) export GOOGLE_APPLICATION_CREDENTIALS="<PATH>" """) exit def _get_credentials(): with open(GOOGLE_APPLICATION_CREDENTIALS_PATH) as json_file: json_data = json.load(json_file) return json_data class TestCollector(TestCase): def test_init(self): v_info = self.inventory.Collector.init({'options': {}}) print_json(v_info) def test_verify(self): options = { } secret_data = _get_credentials() print(secret_data) v_info = self.inventory.Collector.verify({'options': options, 'secret_data': secret_data}) print_json(v_info) def test_collect(self): secret_data = _get_credentials() options = {} filter = {} resource_stream = self.inventory.Collector.collect({'options': options, 'secret_data': secret_data, 'filter': filter}) # print(resource_stream) print('###################') for res in resource_stream: print_json(res) if __name__ == "__main__": unittest.main(testRunner=RichTestRunner)
[ { "point_num": 1, "id": "has_multiple_inheritance", "question": "Does any class in this file use multiple inheritance?", "answer": false }, { "point_num": 2, "id": "all_function_names_snake_case", "question": "Are all function names in this file written in snake_case?", "answer":...
3
test/api/test_collector.py
choonho/plugin-google-cloud-compute-inven-collector
def half(i, n): return "".join(str(d%10) for d in range(1, n-i+1)) def line(i, n): h = half(i, n) return " " * i + h + h[-2::-1] def get_a_down_arrow_of(n): return "\n".join(line(i, n) for i in range(n))
[ { "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
CodeWars/7 Kyu/Down Arrow With Numbers.py
anubhab-code/Competitive-Programming
from unittest.mock import patch from pydragonfly.sdk.const import ANALYZED, MALICIOUS from tests.mock_utils import MockAPIResponse from tests.resources import APIResourceBaseTestCase from tests.resources.test_analysis import AnalysisResultTestCase class DragonflyTestCase(APIResourceBaseTestCase): @property def resource(self): return self.df @patch( "pydragonfly.sdk.resources.analysis.Analysis.create", return_value=MockAPIResponse({"id": 1}, 200), ) def test_analyze_file(self, *args, **kwargs): ret = self.df.analyze_file( sample_name="test", sample_buffer=b"test_sample", retrieve_analysis=False ) self.assertEqual(ret, 1) @patch( "pydragonfly.sdk.resources.analysis.Analysis.retrieve", return_value=MockAPIResponse(AnalysisResultTestCase.result_json, 200), ) @patch( "pydragonfly.sdk.resources.report.Report.matched_rules", return_value=MockAPIResponse(AnalysisResultTestCase.matched_rules_json, 200), ) def test_analysis_result(self, *args, **kwargs): result = self.df.analysis_result(12) self.assertEqual(result.id, 12) self.assertEqual(result.status, ANALYZED) self.assertEqual(result.evaluation, MALICIOUS) self.assertEqual(result.score, 10)
[ { "point_num": 1, "id": "has_multiple_inheritance", "question": "Does any class in this file use multiple inheritance?", "answer": false }, { "point_num": 2, "id": "every_function_under_20_lines", "question": "Is every function in this file shorter than 20 lines?", "answer": true...
3
tests/test_dragonfly.py
certego/pydragonfly
"""Wrapper to integrate with Arcanist's .arcconfig file.""" # ============================================================================= # CONTENTS # ----------------------------------------------------------------------------- # phlsys_arcconfig # # Public Functions: # find_arcconfig # load # get_arcconfig # # ----------------------------------------------------------------------------- # (this contents block is generated, edits will be lost) # ============================================================================= from __future__ import absolute_import from __future__ import division from __future__ import print_function import json import os def _parent_dir(path): return os.path.abspath(os.path.join(path, os.pardir)) def find_arcconfig(): path = None nextpath = os.getcwd() while path != nextpath: path, nextpath = nextpath, _parent_dir(nextpath) config_path = os.path.join(path, ".arcconfig") if os.path.isfile(config_path): return config_path return None def load(path): with open(path) as f: return json.load(f) def get_arcconfig(): return load(find_arcconfig()) # ----------------------------------------------------------------------------- # Copyright (C) 2013-2014 Bloomberg Finance L.P. # # 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. # ------------------------------ END-OF-FILE ----------------------------------
[ { "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
py/phl/phlsys_arcconfig.py
aevri/phabricator-tools
from sqlalchemy.orm import Session from models import sql from models.api import SubscriptionDB, Subscription from models.covid_data.school_cases_by_district import SchoolDistricts def add_(db: Session, subscription: SubscriptionDB): sub_dict = subscription.dict() sub_dict["district"] = subscription.district.value subscription = sql.Subscription(**sub_dict) try: db.add(subscription) except Exception: db.rollback() raise finally: db.commit() def get_(db: Session, email: str) -> list[Subscription]: subs = db.query(sql.Subscription).filter(sql.Subscription.email == email).all() for sub in subs: print(sub.email) Subscription.from_orm(sub) return [Subscription.from_orm(sub) for sub in subs] def delete_(db: Session, email: str, districts: list[SchoolDistricts]): try: for district in districts: db.query(sql.Subscription).filter( sql.Subscription.email == email and sql.Subscription.district == district.value ).delete() except Exception: db.rollback() raise finally: db.commit()
[ { "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
utils/database/db_subscriptions.py
peterHoburg/utah_covid_alerting
from django.core.urlresolvers import resolve from django.http import HttpRequest from django.template.loader import render_to_string from django.test import TestCase from lists.views import home_page class HomePageTest(TestCase): def test_root_url_resolves_to_home_page_view(self): found = resolve('/') self.assertEqual(found.func, home_page) def test_home_page_returns_correct_html(self): request = HttpRequest() response = home_page(request) expected_html = render_to_string('home.html') self.assertEqual(response.content.decode(), expected_html) def test_home_page_can_save_a_POST_request(self): request = HttpRequest() request.method = 'POST' request.POST['item_text'] = 'A new list item' response = home_page(request) self.assertIn('A new list item', response.content.decode())
[ { "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
superlists/lists/tests.py
kentaro0919/obeythetestinggoat
import json, os from planutils import manifest_converter # This should eventually be changed once the prefix is customizable PLANUTILS_PREFIX = os.path.join(os.path.expanduser('~'), '.planutils') SETTINGS_FILE = os.path.join(PLANUTILS_PREFIX, 'settings.json') PAAS_SERVER = 'http://45.113.232.43:5001' PAAS_SERVER_LIMIT = 100 def load(): with open(SETTINGS_FILE, 'r') as f: settings = json.loads(f.read()) return settings def save(s): with open(SETTINGS_FILE, 'w') as f: f.write(json.dumps(s)) manifest_converter.generate_manifest()
[ { "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
planutils/settings.py
AI-Planning/planning-utils
import unittest import mock from pythonwarrior.abilities.base import AbilityBase class TestAbilityBase(unittest.TestCase): def setUp(self): unit = mock.Mock() self.ability = AbilityBase(unit) def test_should_have_offset_for_directions(self): self.assertEqual(self.ability.offset('forward'), [1, 0]) self.assertEqual(self.ability.offset('right'), [0, 1]) self.assertEqual(self.ability.offset('backward'), [-1, 0]) self.assertEqual(self.ability.offset('left'), [0, -1]) def test_should_have_offset_for_relative_forward_and_right_amounts(self): self.assertEqual(self.ability.offset('forward', forward=2), [2, 0]) self.assertEqual(self.ability.offset('forward', forward=2, right=1), [2, -1]) self.assertEqual(self.ability.offset('right', forward=2, right=1), [1, 2]) self.assertEqual(self.ability.offset('backward', forward=2, right=1), [-2, 1]) self.assertEqual(self.ability.offset('left', forward=2, right=1), [-1, -2]) @mock.patch('pythonwarrior.abilities.base.AbilityBase.space') def test_should_fetch_unit_at_given_direction_with_distance(self, mock_space): space = mock.Mock() space.unit = 'unit' mock_space.return_value = space self.assertEqual(self.ability.unit('right', 3, 1), 'unit') def test_should_have_no_description(self): self.assertEqual(self.ability.description(), None) def test_should_raise_an_exception_if_direction_isnt_recognized(self): self.assertRaises(Exception, self.ability.verify_direction, 'foo') 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": "all_function_names_snake_case", "question": "Are all function names in this file written in snake_case?", "answ...
3
pythonwarrior/tests/abilities/test_base.py
kuvaszkah/python_warrior
from Block import Block class Blockchain: def __init__(self): self.difficulty = 4 # number of leading 0's needed for proofed hash genesis_block = Block(["Genesis Block"], "0", self.difficulty) self.chain = [genesis_block] print(f"Genesis Block created!\nHash: {genesis_block.generate_hash()}\n") # Creates block with data and appends to chain def add_block(self, data): if self.validate_chain() == -1: prev_hash = (self.chain[-1]).generate_hash() new_block = Block(data, prev_hash, self.difficulty) self.chain.append(new_block) print(f"Block {len(self.chain)-1} added!\n" f"Data: {data}\n" f"Hash: {new_block.generate_hash()}\n") else: print(f"Block not added. Invalid chain at Block {self.validate_chain()}!\n") # Prints full contents of the blockchain and verifies links def print_chain(self): print("Printing Blockchain...") for i in range(len(self.chain)): print(f"Block {i}") self.chain[i].print_contents() if self.validate_chain() == -1: print("Chain is valid!\n") else: print(f"Chain is invalid at Block {self.validate_chain()}!\n") # Validates linked hashes in chain. # Returns index of invalid block or -1 for valid chain def validate_chain(self): for i in range(1, len(self.chain)): current = self.chain[i] previous = self.chain[i - 1] if current.hash != current.generate_hash() or current.prev_hash != previous.generate_hash(): return i return -1
[ { "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
Blockchain.py
sgongidi/Local-Blockchain
# coding: utf-8 """ Isilon SDK Isilon SDK - Language bindings for the OneFS API # noqa: E501 OpenAPI spec version: 7 Contact: sdk@isilon.com Generated by: https://github.com/swagger-api/swagger-codegen.git """ from __future__ import absolute_import import unittest import isi_sdk_8_2_0 from isi_sdk_8_2_0.models.event_settings_settings_maintenance import EventSettingsSettingsMaintenance # noqa: E501 from isi_sdk_8_2_0.rest import ApiException class TestEventSettingsSettingsMaintenance(unittest.TestCase): """EventSettingsSettingsMaintenance unit test stubs""" def setUp(self): pass def tearDown(self): pass def testEventSettingsSettingsMaintenance(self): """Test EventSettingsSettingsMaintenance""" # FIXME: construct object with mandatory attributes with example values # model = isi_sdk_8_2_0.models.event_settings_settings_maintenance.EventSettingsSettingsMaintenance() # noqa: E501 pass if __name__ == '__main__': unittest.main()
[ { "point_num": 1, "id": "all_function_names_snake_case", "question": "Are all function names in this file written in snake_case?", "answer": false }, { "point_num": 2, "id": "every_function_under_20_lines", "question": "Is every function in this file shorter than 20 lines?", "ans...
3
isi_sdk_8_2_0/test/test_event_settings_settings_maintenance.py
mohitjain97/isilon_sdk_python
############################################################################### # # Tests for XlsxWriter. # # Copyright (c), 2013-2020, John McNamara, jmcnamara@cpan.org # from ..excel_comparsion_test import ExcelComparisonTest from ...workbook import Workbook class TestCompareXLSXFiles(ExcelComparisonTest): """ Test file created by XlsxWriter against a file created by Excel. """ def setUp(self): self.set_filename('page_breaks05.xlsx') self.ignore_files = ['xl/printerSettings/printerSettings1.bin', 'xl/worksheets/_rels/sheet1.xml.rels'] self.ignore_elements = {'[Content_Types].xml': ['<Default Extension="bin"'], 'xl/worksheets/sheet1.xml': ['<pageMargins', '<pageSetup']} def test_create_file(self): """Test the creation of a simple XlsxWriter file with page breaks.""" workbook = Workbook(self.got_filename) worksheet = workbook.add_worksheet() worksheet.set_v_pagebreaks([8, 3, 1, 0]) worksheet.write('A1', 'Foo') workbook.close() self.assertExcelEqual()
[ { "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
xlsxwriter/test/comparison/test_page_breaks05.py
timgates42/XlsxWriter
def create_new(numbers): n = len(numbers) keys = [None for i in range(2 * n)] for num in numbers: idx = num % len(keys) while keys[idx] is not None: idx = (idx + 1) % len(keys) keys[idx] = num return keys def create_new_broken(numbers): n = len(numbers) keys = [None for i in range(n)] for num in numbers: idx = num % len(keys) keys[idx] = num return keys def has_key(keys, key): idx = key % len(keys) while keys[idx] is not None: if keys[idx] == key: return True idx = (idx + 1) % len(keys) return False def linear_search(numbers, number): return number in numbers
[ { "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
python_code/hash_chapter1_impl.py
possnfiffer/inside_python_dict
import torch import torch.nn as nn import torch.nn.functional as F from torch_utils.models import FeedForward class EIIEFeedForwarad(nn.Module): def __init__(self, model_params, cash_bias): super(EIIEFeedForwarad, self).__init__() self.lower_model = FeedForward(model_params['lower_params']) self.upper_model = FeedForward(model_params['upper_params']) self.cash_bias = nn.Parameter(cash_bias) def forward(self, states, prev_actions): n_batch = states.shape[0] outputs = self.lower_model(states) # We do not use cash actions as input, prev_actions[:, 0] prev_actions = prev_actions[:, None, None, 1:] # Concatenation with channel dimension outputs = torch.cat((outputs, prev_actions), dim=1) prev_softmax = self.upper_model(outputs) _cash_bias = self.cash_bias.repeat(n_batch, 1) prev_softmax = torch.cat((_cash_bias, prev_softmax), dim=-1) actions = F.softmax(prev_softmax, dim=-1) return actions def predict(self, state, prev_action): states = state[None, :] prev_actions = prev_action[None, :] return self.forward(states, prev_actions)[0].detach().numpy()
[ { "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
rl_traders/models.py
jjakimoto/rl_traders.py
from .bases import DotloopObject from .document import Document class Folder(DotloopObject, id_field='folder_id'): @property def document(self): return Document(parent=self) def get(self, **kwargs): return self.fetch('get', params=kwargs) def patch(self, **kwargs): return self.fetch('patch', json=kwargs) def post(self, **kwargs): return self.fetch('post', json=kwargs)
[ { "point_num": 1, "id": "has_multiple_inheritance", "question": "Does any class in this file use multiple inheritance?", "answer": false }, { "point_num": 2, "id": "all_function_names_snake_case", "question": "Are all function names in this file written in snake_case?", "answer":...
3
dotloop/folder.py
spentaur/dotloop-python
from model.group import Group def test_group_list(app, db): ui_list = app.group.get_group_list() def clean(group): return Group(id=group.id, name=group.name.strip()) db_list = map(clean, db.get_group_list()) assert sorted(ui_list, key=Group.id_or_max) == sorted (db_list, key=Group.id_or_max)
[ { "point_num": 1, "id": "no_function_exceeds_5_params", "question": "Does every function in this file take 5 or fewer parameters (excluding self/cls)?", "answer": true }, { "point_num": 2, "id": "all_params_annotated", "question": "Does every function parameter in this file have a ty...
3
test/test_db_matches_ui.py
ntomczyk/python_training
from django.conf.urls import url from rest_framework import fields, generics, versioning from snippets.models import Snippet from snippets.serializers import SnippetSerializer from testproj.urls import SchemaView, required_urlpatterns class SnippetSerializerV2(SnippetSerializer): v2field = fields.IntegerField(help_text="version 2.0 field") class Meta: ref_name = 'SnippetV2' class SnippetList(generics.ListCreateAPIView): """SnippetList classdoc""" queryset = Snippet.objects.all() serializer_class = SnippetSerializer versioning_class = versioning.URLPathVersioning def get_serializer_class(self): context = self.get_serializer_context() request = context['request'] if int(float(request.version)) >= 2: return SnippetSerializerV2 else: return SnippetSerializer def perform_create(self, serializer): serializer.save(owner=self.request.user) def post(self, request, *args, **kwargs): """post method docstring""" return super(SnippetList, self).post(request, *args, **kwargs) VERSION_PREFIX_URL = r"^versioned/url/v(?P<version>1.0|2.0)/" class VersionedSchemaView(SchemaView): versioning_class = versioning.URLPathVersioning urlpatterns = required_urlpatterns + [ url(VERSION_PREFIX_URL + r"snippets/$", SnippetList.as_view()), url(VERSION_PREFIX_URL + r'swagger(?P<format>.json|.yaml)$', VersionedSchemaView.without_ui(), name='vschema-json'), ]
[ { "point_num": 1, "id": "more_functions_than_classes", "question": "Does this file define more functions than classes?", "answer": false }, { "point_num": 2, "id": "every_function_under_20_lines", "question": "Is every function in this file shorter than 20 lines?", "answer": true...
3
tests/urlconfs/url_versioning.py
johnny-prnd/drf-yasg
import random import torch import torch.nn as nn from models.cnn_layer import CNNLayer from utility.model_parameter import ModelParameter, Configuration class SiameseNeuralNetwork(nn.Module): def __init__(self, config: Configuration, label_count=64, device=torch.device('cpu'), *args, **kwargs): super(SiameseNeuralNetwork, self).__init__() # set parameters self.max_length = config.get_int(ModelParameter.MAX_LENGTH) self.device = device # create and initialize layers self.cnn_layer = CNNLayer(config) self.distance_measure = nn.CosineSimilarity() def distance(self, a, b): return self.distance_measure(a, b) def get_output_dim(self): return self.cnn_layer.get_output_length() def forward(self, sample, previous_classes, positions, previous_sample, sample_pos, *sample_neg, **kwargs): n_negative = len(sample_neg) selected_negative = sample_neg[random.randint(0, n_negative - 1)] return self.compare(sample, sample_pos, mode=kwargs["mode"]), self.compare(sample, selected_negative, mode=kwargs["mode"]) def get_features(self, sample): return self.cnn_layer(sample) def compare(self, sample_1, sample_2, mode="train", **kwargs): encoded_sample_1 = self.cnn_layer(sample_1) encoded_sample_2 = self.cnn_layer(sample_2) return self.distance(encoded_sample_1, encoded_sample_2)
[ { "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
models/siamese_neural_network.py
RobinRojowiec/intent-recognition-in-doctor-patient-interviews
from typing import Callable import pytest from hannah import HannahException from hannah import UnsupportedOperation def dummy_func(exc: Callable[..., None], msg: str, valid: bool) -> None: raise exc(msg=msg, valid=valid) # type: ignore @pytest.mark.parametrize( ("exc", "msg", "valid", "match"), ( ( HannahException, "A new HannahException raised", True, "HannahException", ), ( HannahException, "Another HannahException raised", False, "https://github.com/", ), ( UnsupportedOperation, "A new UnsupportedOperation raised", True, "UnsupportedOperation", ), ( UnsupportedOperation, "Another UnsupportedOperation raised", False, "https://github.com/", ), ), ) def test_hannah_exception( exc: Callable[..., None], msg: str, valid: bool, match: str ) -> None: with pytest.raises(exc, match=match): # type: ignore dummy_func(exc, msg, valid)
[ { "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_return_types_annotated", "question": "Does every function in this file have a return t...
3
tests/test_exceptions.py
xames3/hannah
# Undirected Graph from demo represented as Adjacency List graph = { "a": [("b", 7), ("c", 9), ("f", 14)], "b": [("a", 7), ("c", 10), ("d", 15)], "c": [("a", 9), ("b", 10), ("d", 11), ("f", 2)], "d": [("b", 15), ("c", 11), ("e", 6)], "e": [("d", 6), ("f", 9)], "f": [("a", 14), ("c", 2), ("e", 9)], } def find_vertices(): return graph.keys() def find_edges(): edges = [] for v in graph: for e in graph[v]: edges.append((v, e[0], e[1])) return edges print("Vertices: {}".format(find_vertices())) print("Edges: {}".format(find_edges()))
[ { "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
python-dsa/Section4/graph_adj_list.py
vermuz/mani-professional-notes
def stripQuotes(string): """Strip leading and trailing quotes from a string. Does nothing unless starting and ending quotes are present and the same type (single or double). """ single = string.startswith("'") and string.endswith("'") double = string.startswith('"') and string.endswith('"') if single or double: return string[1:-1] return string def escapeQuotes(string): """Escape single quotes since values will be wrapped in single quotes in the wrap template. """ try: return string.replace("'", "\\'") except AttributeError: # Not a string so return unaltered. return string def fin(path): """Opens file at given path and returns string value. """ return open(path, 'rb').read()
[ { "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
jsinclude/templatetags/pkg/utils.py
cobbdb/jsinclude
class Pessoa: def __init__(self, nome, idade): self._nome = nome self._idade = idade @property def nome(self): return self._nome @property def idade(self): return self._idade class Cliente(Pessoa): def __init__(self, nome, idade): super().__init__(nome, idade) self.conta = None def inserir_conta(self, tipo_conta): self.conta = tipo_conta return
[ { "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
aprendizado/udemy/03_desafio_POO/cliente.py
renatodev95/Python
# Copyright (c) Max-Planck-Institut für Eisenforschung GmbH - Computational Materials Design (CM) Department # Distributed under the terms of "New BSD License", see the LICENSE file. """ Run a job from hdf5. """ from pyiron.base.job.wrapper import job_wrapper_function def register(parser): parser.add_argument( "-d", "--debug", action = "store_true", help = "enable debug mode" # TODO: what's that mean? ) parser.add_argument( "-j", "--job-id", help = "job id to run" ) parser.add_argument( "-p", "--project", help = "directory where the HDF5 file of the job is located" ) parser.add_argument( "-f", "--file-path", help = "path to the HDF5 file" ) parser.add_argument( "-s", "--submit", action = "store_true", help = "submit to queuing system on remote host" ) def main(args): job_wrapper_function( working_directory=args.project, job_id=args.job_id, file_path=args.file_path, debug=args.debug, submit_on_remote=args.submit )
[ { "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
pyiron/cli/wrapper.py
srmnitc/pyiron
import pickle from PyQt5 import QtCore, QtGui, QtWidgets from PyQt5.QtWidgets import ( QWidget, QToolTip, QPushButton, QApplication, QMessageBox, QTableWidget) from .RadioWindow import RadioWindow class WrappedRadioWindow(RadioWindow, QtWidgets.QMainWindow): def __init__(self): super().__init__() self.setupUi(self) self.__build_buttons() self.setWindowTitle('Предобработка данных') self.comboBox.addItems(["Средним/модой (численные/категориальные значения)", "Введенным значением (требуется ввод для каждого столбца отдельно)", "Удаление строк с пропущенными значениями", "Медианной/модой (численные/категориальные значения)" ]) self.settings = {'preprocessing': { 'fillna': 'mean', 'encoding': 'label_encoding', 'scaling': False } } def __build_buttons(self): self.pushButtonNext.clicked.connect(self.next) self.pushButtonBack.clicked.connect(self.back) def back(self): self.hide() self.parent.show() def next(self): value_na = self.comboBox.currentText() if value_na == 'средним/модой (аналогично)': self.settings['preprocessing'] = 'mean' elif value_na == 'заданным значием (требуется ввод для каждого столбца отдельно)': self.settings['preprocessing'] = 'exact_value' elif value_na == 'откидывание строк с пропущенными значениями': self.settings['preprocessing'] = 'dropna' else: self.settings['preprocessing'] = 'median' with open('settings.py', 'rb') as f: data = pickle.load(f) data['MODULE_SETTINGS'].update(self.settings) with open('settings.py', 'wb') as f: pickle.dump(data, f) self.hide() self.child.show()
[ { "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
SmartMedApp/GUI/apps/PredictionApp/WrappedRadioWindow.py
vovochkab/SmartMed
# by Kami Bigdely # Docstrings and blank lines class OnBoardTemperatureSensor: VOLTAGE_TO_TEMP_FACTOR = 5.6 def __init__(self): pass def read_voltage(self): return 2.7 def get_temperature(self): return self.read_voltage() * OnBoardTemperatureSensor.VOLTAGE_TO_TEMP_FACTOR # [celcius] class CarbonMonoxideSensor: VOLTAGE_TO_CO_FACTOR = 0.048 def __init__(self, temperature_sensor): self.on_board_temp_sensor = temperature_sensor if not self.on_board_temp_sensor: self.on_board_temp_sensor = OnBoardTemperatureSensor() def get_carbon_monoxide_level(self): sensor_voltage = self.read_sensor_voltage() self.carbon_monoxide = CarbonMonoxideSensor.convert_voltage_to_carbon_monoxide_level(sensor_voltage, self.on_board_temp_sensor.get_temperature()) return self.carbon_monoxide def read_sensor_voltage(self): # In real life, it should read from hardware. return 2.3 def convert_voltage_to_carbon_monoxide_level(voltage, temperature): return voltage * CarbonMonoxideSensor.VOLTAGE_TO_CO_FACTOR * temperature class DisplayUnit: def __init__(self): self.string = '' def display(self,msg): print(msg) class CarbonMonoxideDevice(): def __init__(self, co_sensor, display_unit): self.carbonMonoxideSensor = co_sensor self.display_unit = display_unit def Display(self): msg = 'Carbon Monoxide Level is : ' + str(self.carbonMonoxideSensor.get_carbon_monoxide_level()) self.display_unit.display(msg) if __name__ == "__main__": temp_sensor = OnBoardTemperatureSensor() co_sensor = CarbonMonoxideSensor(temp_sensor) display_unit = DisplayUnit() co_device = CarbonMonoxideDevice(co_sensor, display_unit) co_device.Display()
[ { "point_num": 1, "id": "every_class_has_docstring", "question": "Does every class 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 self/cls)...
3
lab/refactoring-pep8/docstrings_blank_lines.py
stark276/SPD-2.31-Testing-and-Architecture1
#!/usr/bin/env python # -*- coding: utf-8 -*- import simplejson as json from alipay.aop.api.constant.ParamConstants import * class ContentPrizeInfoModel(object): def __init__(self): self._prize_id = None self._prize_logo = None self._prize_name = None @property def prize_id(self): return self._prize_id @prize_id.setter def prize_id(self, value): self._prize_id = value @property def prize_logo(self): return self._prize_logo @prize_logo.setter def prize_logo(self, value): self._prize_logo = value @property def prize_name(self): return self._prize_name @prize_name.setter def prize_name(self, value): self._prize_name = value def to_alipay_dict(self): params = dict() if self.prize_id: if hasattr(self.prize_id, 'to_alipay_dict'): params['prize_id'] = self.prize_id.to_alipay_dict() else: params['prize_id'] = self.prize_id if self.prize_logo: if hasattr(self.prize_logo, 'to_alipay_dict'): params['prize_logo'] = self.prize_logo.to_alipay_dict() else: params['prize_logo'] = self.prize_logo if self.prize_name: if hasattr(self.prize_name, 'to_alipay_dict'): params['prize_name'] = self.prize_name.to_alipay_dict() else: params['prize_name'] = self.prize_name return params @staticmethod def from_alipay_dict(d): if not d: return None o = ContentPrizeInfoModel() if 'prize_id' in d: o.prize_id = d['prize_id'] if 'prize_logo' in d: o.prize_logo = d['prize_logo'] if 'prize_name' in d: o.prize_name = d['prize_name'] return o
[ { "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
alipay/aop/api/domain/ContentPrizeInfoModel.py
articuly/alipay-sdk-python-all
import click from . import __version__ from .cli_commands import create_cluster, upload, upload_and_update from .configure import configure def print_version(ctx, param, value): if not value or ctx.resilient_parsing: return click.echo('Version {}'.format(__version__)) ctx.exit() @click.group() @click.option('--version', '-v', is_flag=True, callback=print_version, help=__version__) def cli(version): pass cli.add_command(configure) cli.add_command(create_cluster) cli.add_command(upload) cli.add_command(upload_and_update)
[ { "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
stork/cli.py
ShopRunner/apparate
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """The Chi2 distribution class.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow.contrib.distributions.python.ops import gamma from tensorflow.python.framework import ops from tensorflow.python.ops import math_ops class Chi2(gamma.Gamma): """The Chi2 distribution with degrees of freedom df. The PDF of this distribution is: ```pdf(x) = (x^(df/2 - 1)e^(-x/2))/(2^(k/2)Gamma(k/2)), x > 0``` Note that the Chi2 distribution is a special case of the Gamma distribution, with Chi2(df) = Gamma(df/2, 1/2). """ def __init__(self, df, name="Chi2"): with ops.op_scope([df], name, "init"): df = ops.convert_to_tensor(df) self._df = df super(Chi2, self).__init__(alpha=df / 2, beta=math_ops.cast(0.5, dtype=df.dtype)) @property def df(self): return self._df
[ { "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
tensorflow/contrib/distributions/python/ops/chi2.py
breandan/tensorflow
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. import torch import logging from .lr_scheduler import WarmupMultiStepLR def make_optimizer(cfg, model): logger = logging.getLogger("fcos_core.trainer") params = [] for key, value in model.named_parameters(): if not value.requires_grad: continue lr = cfg.SOLVER.BASE_LR weight_decay = cfg.SOLVER.WEIGHT_DECAY if "bias" in key: lr = cfg.SOLVER.BASE_LR * cfg.SOLVER.BIAS_LR_FACTOR weight_decay = cfg.SOLVER.WEIGHT_DECAY_BIAS if key.endswith(".offset.weight") or key.endswith(".offset.bias"): logger.info("set lr factor of {} as {}".format( key, cfg.SOLVER.DCONV_OFFSETS_LR_FACTOR )) lr *= cfg.SOLVER.DCONV_OFFSETS_LR_FACTOR params += [{"params": [value], "lr": lr, "weight_decay": weight_decay}] optimizer = torch.optim.SGD(params, lr, momentum=cfg.SOLVER.MOMENTUM) if cfg.SOLVER.ADAM: optimizer = torch.optim.Adam(params) return optimizer def make_lr_scheduler(cfg, optimizer): return WarmupMultiStepLR( optimizer, cfg.SOLVER.STEPS, cfg.SOLVER.GAMMA, warmup_factor=cfg.SOLVER.WARMUP_FACTOR, warmup_iters=cfg.SOLVER.WARMUP_ITERS, warmup_method=cfg.SOLVER.WARMUP_METHOD, )
[ { "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
fcos_core/solver/build.py
CityU-AIM-Group/SFPolypDA
#!/usr/bin/env python # -*- coding: utf-8 -*- import json from alipay.aop.api.response.AlipayResponse import AlipayResponse class AlipaySocialGiftOrderRefundResponse(AlipayResponse): def __init__(self): super(AlipaySocialGiftOrderRefundResponse, self).__init__() self._order_id = None @property def order_id(self): return self._order_id @order_id.setter def order_id(self, value): self._order_id = value def parse_response_content(self, response_content): response = super(AlipaySocialGiftOrderRefundResponse, self).parse_response_content(response_content) if 'order_id' in response: self.order_id = response['order_id']
[ { "point_num": 1, "id": "more_functions_than_classes", "question": "Does this file define more functions than classes?", "answer": true }, { "point_num": 2, "id": "every_function_has_docstring", "question": "Does every function in this file have a docstring?", "answer": false }...
3
alipay/aop/api/response/AlipaySocialGiftOrderRefundResponse.py
snowxmas/alipay-sdk-python-all
import logging from logging.handlers import RotatingFileHandler from flask import Flask, session from flask_session import Session from flask_sqlalchemy import SQLAlchemy from flask_wtf import CSRFProtect from flask_wtf.csrf import generate_csrf from redis import StrictRedis from config import config # 初始化db from info.utils.common import do_index_class db = SQLAlchemy() redis_store = None # type: StrictRedis def setup_log(config_name): """配置日志""" # 设置日志的记录等级 logging.basicConfig(level=config[config_name].LOG_LEVEL) # 创建日志记录器,指明日志保存的路径/每个日志文件的最大大小,保存的日志文件个数上限 file_log_handler = RotatingFileHandler("logs/log",maxBytes=1024*1024*100,backupCount=10) # 创建日志记录的格式 日志等级 输入日志信息的文件名 行数 日志信息 formatter = logging.Formatter("%(levelname)s %(filename)s:%(lineno)d %(message)s") # 为刚创建的日志记录器设置日志记录格式 file_log_handler.setFormatter(formatter) # 为全局的日志工具对象添加日志记录器 logging.getLogger().addHandler(file_log_handler) def create_app(config_name): # 配置项目日志 setup_log(config_name) app = Flask(__name__) app.config.from_object(config[config_name]) # 初始化一个sqlALchemy对象 db.init_app(app) # 创建redis存储对象 global redis_store redis_store = StrictRedis(host=config[config_name].REDIS_HOST,port=config[config_name].REDIS_PORT,decode_responses=True) # 开启CSRF保护 CSRFProtect(app) # 设置session保存指定位置 Session(app) # 将自己定义的过滤器添加到app中 app.add_template_filter(do_index_class,"index_class") @app.after_request def after_request(response): # 生成随机的csrf_token csrf_token = generate_csrf() # 设置cookie response.set_cookie("csrf_token",csrf_token) return response # 将蓝图注册到app里 from info.modules.index import index_blu app.register_blueprint(index_blu) from info.modules.passport import passport_blu app.register_blueprint(passport_blu) # 切记一定要返回一个app,否则创建不成功 return app
[ { "point_num": 1, "id": "has_nested_function_def", "question": "Does this file contain any function defined inside another function?", "answer": true }, { "point_num": 2, "id": "no_function_exceeds_5_params", "question": "Does every function in this file take 5 or fewer parameters (e...
3
info/__init__.py
Alison67/NewsWebsite
# B. Сбалансированное дерево # ID успешной посылки 66593272 class Node: def __init__(self, value, left=None, right=None): self.value = value self.right = right self.left = left def height(root): if root is None: return 0 return max(height(root.left), height(root.right)) + 1 def solution(root): if root is None: return True left_height = height(root.left) right_height = height(root.right) if ((abs(left_height - right_height) <= 1) and solution(root.left) is True and solution(root.right) is True): return True return False def test(): node1 = Node(1) node2 = Node(-5) node3 = Node(3, node1, node2) node4 = Node(10) node5 = Node(2, node3, node4) assert solution(node5)
[ { "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
tree/b_my_solution.py
master-cim/algorithm
import sys import os import argparse import json import numpy as np sys.path.append(os.path.join(os.path.dirname(__file__), '..', '..', 'lib')) import inputparser import clustermaker def write_ssms(variants, outfn): _stringify = lambda A: ','.join([str(V) for V in A]) mu_r = 0.999 cols = ('id', 'gene', 'a', 'd', 'mu_r', 'mu_v') with open(outfn, 'w') as outf: print(*cols, sep='\t', file=outf) for V in variants.values(): assert len(set(V['omega_v'])) == 1 variant = { 'id': 's%s' % int(V['id'][1:]), 'gene': V['name'], 'a': _stringify(V['ref_reads']), 'd': _stringify(V['total_reads']), 'mu_r': mu_r, 'mu_v': np.mean(1 - V['omega_v']), } print(*[variant[K] for K in cols], sep='\t', file=outf) def write_params(sampnames, outfn): with open(outfn, 'w') as outf: json.dump({'samples': sampnames}, outf) def main(): parser = argparse.ArgumentParser( description='LOL HI THERE', formatter_class=argparse.ArgumentDefaultsHelpFormatter ) parser.add_argument('--use-supervars', dest='use_supervars', action='store_true') parser.add_argument('ssm_fn') parser.add_argument('params_fn') parser.add_argument('pwgs_ssm_fn') parser.add_argument('pwgs_params_fn') args = parser.parse_args() variants = inputparser.load_ssms(args.ssm_fn) params = inputparser.load_params(args.params_fn) if args.use_supervars: variants = clustermaker.make_cluster_supervars(params['clusters'], variants) write_ssms(variants, args.pwgs_ssm_fn) write_params(params['samples'], args.pwgs_params_fn) 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
comparison/pwgs/convert_inputs.py
J-Moravec/pairtree
import torch as th import torch.nn as nn import torch.nn.functional as F import numpy as np class PointLikeMixer(nn.Module): def __init__(self, args): super(PointLikeMixer, self).__init__() self.args = args self.n_agents = args.n_agents self.n_groups = args.mixing_group_dim self.state_dim = int(np.prod(args.state_shape)) self.embed_dim = args.mixing_embed_dim self.group_dim = args.mixing_group_dim self.hyper_w_1 = nn.Linear(self.state_dim, self.embed_dim * self.n_groups) self.hyper_w_final = nn.Linear(self.state_dim, self.embed_dim) # State dependent bias for hidden layer self.hyper_b_1 = nn.Linear(self.state_dim, self.embed_dim) # V(s) instead of a bias for the last layers self.V = nn.Sequential(nn.Linear(self.state_dim, self.embed_dim), nn.ReLU(), nn.Linear(self.embed_dim, 1)) def forward(self, agent_qs, states): bs = agent_qs.size(0) states = states.reshape(-1, self.state_dim) agent_qs = agent_qs.view(-1, self.group_dim, self.n_agents) group_qs = agent_qs.sum(dim=2).view(-1, 1, self.group_dim) # First layer w1 = th.abs(self.hyper_w_1(states)) b1 = self.hyper_b_1(states) w1 = w1.view(-1, self.n_groups, self.embed_dim) b1 = b1.view(-1, 1, self.embed_dim) hidden = F.elu(th.bmm(group_qs, w1) + b1) # Second layer w_final = th.abs(self.hyper_w_final(states)) w_final = w_final.view(-1, self.embed_dim, 1) # State-dependent bias v = self.V(states).view(-1, 1, 1) # Compute final output y = th.bmm(hidden, w_final) + v # Reshape and return q_tot = y.view(bs, -1, 1) return q_tot
[ { "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
src/modules/mixers/point_like.py
wjh720/pymarl
# This file was automatically generated by SWIG (http://www.swig.org). # Version 1.3.31 # # Don't modify this file, modify the SWIG interface instead. # This file is compatible with both classic and new-style classes. import _sequencer_osx import new new_instancemethod = new.instancemethod try: _swig_property = property except NameError: pass # Python < 2.2 doesn't have 'property'. def _swig_setattr_nondynamic(self, class_type, name, value, static=1): if name == "thisown": return self.this.own(value) if name == "this": if type(value).__name__ == "PySwigObject": self.__dict__[name] = value return method = class_type.__swig_setmethods__.get(name, None) if method: return method(self, value) if (not static) or hasattr(self, name): self.__dict__[name] = value else: raise AttributeError("You cannot add attributes to %s" % self) def _swig_setattr(self, class_type, name, value): return _swig_setattr_nondynamic(self, class_type, name, value, 0) def _swig_getattr(self, class_type, name): if name == "thisown": return self.this.own() method = class_type.__swig_getmethods__.get(name, None) if method: return method(self) raise AttributeError(name) def _swig_repr(self): try: strthis = "proxy of " + self.this.__repr__() except: strthis = "" return "<%s.%s; %s >" % ( self.__class__.__module__, self.__class__.__name__, strthis, ) import types try: _object = object _newclass = 1 except AttributeError: class _object: pass _newclass = 0 del types _MIDIGetNumberOfDevices = _sequencer_osx._MIDIGetNumberOfDevices _MIDIClientCreate = _sequencer_osx._MIDIClientCreate _MIDIClientDispose = _sequencer_osx._MIDIClientDispose _MIDISourceCreate = _sequencer_osx._MIDISourceCreate _MIDIOutputPortCreate = _sequencer_osx._MIDIOutputPortCreate _MIDIPortConnectSource = _sequencer_osx._MIDIPortConnectSource
[ { "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
src/sequencer_osx/sequencer_osx.py
NFJones/python-midi
import pandas as pd def cols_choice (df, include): return df.select_dtypes(include=include).columns.to_list() def cols_header (data_records): if (len(data_records) == 0): return [] return [{'name': v, 'id': v} for v in data_records[0].keys()]
[ { "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
helpers/cols.py
ijlyttle/reactivity-demo-dash
"""Status bar widget on the viewer MainWindow""" from typing import TYPE_CHECKING from qtpy.QtCore import Qt from qtpy.QtWidgets import QLabel, QStatusBar from ...utils.translations import trans from ..dialogs.activity_dialog import ActivityToggleItem if TYPE_CHECKING: from ..qt_main_window import _QtMainWindow class ViewerStatusBar(QStatusBar): def __init__(self, parent: '_QtMainWindow') -> None: super().__init__(parent=parent) self.showMessage(trans._('Ready')) self._help = QLabel('') self.addPermanentWidget(self._help) self._activity_item = ActivityToggleItem() self._activity_item._activityBtn.clicked.connect( self._toggle_activity_dock ) # FIXME: feels weird to set this here. parent._activity_dialog._toggleButton = self._activity_item self.addPermanentWidget(self._activity_item) def setHelpText(self, text: str) -> None: self._help.setText(text) def _toggle_activity_dock(self, visible: bool): par: _QtMainWindow = self.parent() if visible: par._activity_dialog.show() par._activity_dialog.raise_() self._activity_item._activityBtn.setArrowType(Qt.DownArrow) else: par._activity_dialog.hide() self._activity_item._activityBtn.setArrowType(Qt.UpArrow)
[ { "point_num": 1, "id": "all_function_names_snake_case", "question": "Are all function names in this file written in snake_case?", "answer": false }, { "point_num": 2, "id": "has_multiple_inheritance", "question": "Does any class in this file use multiple inheritance?", "answer":...
3
napari/_qt/widgets/qt_viewer_status_bar.py
kolibril13/napari
from .exceptions import WrongInputException class S3Trigger(): """Get information from a S3 trigger record. Args: record (dic): trigger record. Exceptions: WrongInputException """ def __init__(self, record): self.__record = record try: self.__bucket = self.__record['s3']['bucket']['name'] key = self.__record['s3']['object']['key'] self.__key = key.replace('+', ' ') self.__event = self.__record['eventName'] self.__timestamp = self.__record['eventTime'] except Exception: raise WrongInputException('S3 record') @property def bucket(self): return self.__bucket @property def key(self): return self.__key @property def event(self): return self.__event @property def timestamp(self): return self.__timestamp
[ { "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
awstriggers/s3triggers.py
JevyanJ/awstriggers
# coding: utf-8 """ Kubernetes No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) OpenAPI spec version: v1.9.3 Generated by: https://github.com/swagger-api/swagger-codegen.git """ from __future__ import absolute_import import os import sys import unittest import kubernetes.client from kubernetes.client.rest import ApiException from kubernetes.client.models.v1_node_config_source import V1NodeConfigSource class TestV1NodeConfigSource(unittest.TestCase): """ V1NodeConfigSource unit test stubs """ def setUp(self): pass def tearDown(self): pass def testV1NodeConfigSource(self): """ Test V1NodeConfigSource """ # FIXME: construct object with mandatory attributes with example values #model = kubernetes.client.models.v1_node_config_source.V1NodeConfigSource() pass if __name__ == '__main__': unittest.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": "has_multiple_inheritance", "question": "Does any class in this file use multiple inheritance?", "answer": false ...
3
kubernetes/test/test_v1_node_config_source.py
kevingessner/python
class TokenBox(object): def __init__(self, url, username, password, margin = 10, request_now = False): self.URL = url self.Username = username self.Password = password self.Token = None self.Expiration = 0 self.Encoded = None self.Margin = margin if request_now: self.renewIfNeeded() def renewIfNeeded(self): need_to_renew = self.Token is None or time.time() > self.Expiration - self.Margin if need_to_renew: from .rfc2617 import digest_client status, body = digest_client(self.URL, self.Username, self.Password) if status/100 == 2: encoded = body.strip() t = SignedToken.decode(encoded) self.Token = t self.Encoded = encoded self.Expiration = t.expiration else: raise SignedTokenAuthoriztionError(body) @property def token(self): self.renewIfNeeded() return self.Encoded
[ { "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
auth/token_box.py
ivmfnal/dm_common
# Pyrogram - Telegram MTProto API Client Library for Python # Copyright (C) 2017-2020 Dan <https://github.com/delivrance> # # This file is part of Pyrogram. # # Pyrogram is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published # by the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Pyrogram is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with Pyrogram. If not, see <http://www.gnu.org/licenses/>. from io import BytesIO from pyrogram.raw.core.primitives import Int, Long, Int128, Int256, Bool, Bytes, String, Double, Vector from pyrogram.raw.core import TLObject from pyrogram import raw from typing import List, Union, Any # # # # # # # # # # # # # # # # # # # # # # # # # !!! WARNING !!! # # This is a generated file! # # All changes made in this file will be lost! # # # # # # # # # # # # # # # # # # # # # # # # # class GetDialogUnreadMarks(TLObject): # type: ignore """Telegram API method. Details: - Layer: ``117`` - ID: ``0x22e24e22`` **No parameters required.** Returns: List of :obj:`DialogPeer <pyrogram.raw.base.DialogPeer>` """ __slots__: List[str] = [] ID = 0x22e24e22 QUALNAME = "functions.messages.GetDialogUnreadMarks" def __init__(self) -> None: pass @staticmethod def read(data: BytesIO, *args: Any) -> "GetDialogUnreadMarks": # No flags return GetDialogUnreadMarks() def write(self) -> bytes: data = BytesIO() data.write(Int(self.ID, False)) # No flags return data.getvalue()
[ { "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
venv/Lib/site-packages/pyrogram/raw/functions/messages/get_dialog_unread_marks.py
iamgeorgiy/heroku-userbot
from js_analyzer import JsMethod import logging log = logging.getLogger('JsClass') class JsClass: def __init__(self, data: object): self.name = data.id.name log.info('Found class %s' % self.name) self.methods = [] log.debug('Searching for methods...') self.find_methods(data.body) self.attributes = [] log.debug('Searching for attributes...') self.find_attributes() if len(self.attributes) > 0: log.debug( 'Found attributes:\n\n%s\n' % (', '.join(attribute.name for attribute in self.attributes)) ) def find_methods(self, data: object) -> None: for method_data in data.body: if method_data.type == 'MethodDefinition': self.methods.append(JsMethod(method_data)) def find_attributes(self) -> None: for method in self.methods: for attribute in method.find_attributes(): self.attributes.append(attribute) def to_dict(self) -> dict: return { 'name': self.name, 'attributes': [ attribute.to_dict() for attribute in self.attributes ], 'methods': [ method.to_dict() for method in self.methods ] }
[ { "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
src/js_analyzer/js_class.py
cmw278/BCDE321_uml_generator
from typing import Awaitable, Callable from fastapi.exceptions import HTTPException from fastapi.param_functions import Depends from fastapi.security import HTTPBasic, HTTPBasicCredentials from fastapi_integration.current_user_resolvers import CurrentUserResolverFactory from fastapi_integration.users.models import User, convert_private_user_to_user from fastapi_integration.users.repositories import ( UserNotFoundByLoginException, UserRepositoryFactory, ) from galo_ioc import add_factory, get_factory __all__ = [ "load", ] def load() -> None: user_repository_factory = get_factory(UserRepositoryFactory) user_repository = user_repository_factory() security = HTTPBasic() async def resolve_current_user(credentials: HTTPBasicCredentials = Depends(security)) -> User: try: private_user = await user_repository.get_by_login(credentials.username) except UserNotFoundByLoginException: raise HTTPException(status_code=401, detail="Invalid username or password") from None if not private_user.password == credentials.password: raise HTTPException(status_code=401, detail="Invalid username or password") return convert_private_user_to_user(private_user) class CurrentUserResolverFactoryImpl(CurrentUserResolverFactory): def __call__(self) -> Callable[..., Awaitable[User]]: return resolve_current_user add_factory(CurrentUserResolverFactory, CurrentUserResolverFactoryImpl())
[ { "point_num": 1, "id": "all_function_names_snake_case", "question": "Are all function names in this file written in snake_case?", "answer": true }, { "point_num": 2, "id": "more_functions_than_classes", "question": "Does this file define more functions than classes?", "answer": ...
3
examples/fastapi_integration/src/fastapi_integration/current_user_resolvers/basic_auth.py
maximsakhno/galo-ioc
from typing import Union import math AbstractText = Union[int, bytes] def byte_length(i: int) -> int: """Returns the minimal amount of bytes needed to represent unsigned integer `i`.""" # we need to add 1 to correct the fact that a byte can only go up to 255, instead of 256: # i.e math.log(0x100, 0x100) = 1 but needs 2 bytes return math.ceil(math.log(i + 1, 0x100)) def bit_length(i: int) -> int: """Returns the minimal amount of bits needed to represent unsigned integer `i`.""" return math.ceil(math.log(i + 1, 2)) def int_to_bytes(i: int, length: int=-1) -> bytes: """Converts integer to a MSB-first byte sequence using the least amount of bytes possible""" return i.to_bytes(byte_length(i) if length == -1 else length, "big") def bytes_to_int(b: bytes) -> int: """Converts MSB-first byte sequence to an integer""" return int.from_bytes(b, "big")
[ { "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
pws/asymmetric/rsa/helpers.py
pqlx/pws-crypto
""" Functions providing access to file data for unit tests and tutorials. Preferred way to import the module is via the import syntax: import pseudo_dojo.data as pdj_data """ from __future__ import print_function, division, unicode_literals, absolute_import import os from pseudo_dojo.core.pseudos import dojopseudo_from_file, DojoTable __all__ = [ "pseudo", "pseudos", #"ref_file", #"ref_files", ] dirpath = os.path.dirname(__file__) def pseudopath(filename): """Returns the absolute pathname of a pseudo.""" return os.path.join(dirpath, filename) def pseudo(filename): """Returns a `Pseudo` object.""" return dojopseudo_from_file(os.path.join(dirpath, filename)) def pseudos(*filenames): """Returns a PseudoTable constructed from the input filenames located in tests/data/pseudos.""" return DojoTable([dojopseudo_from_file(os.path.join(dirpath, f)) for f in filenames])
[ { "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
pseudo_dojo/data/__init__.py
henriquemiranda/pseudo_dojo
import time from Data.parameters import Data from reuse_func import GetData class District_names(): def __init__(self,driver): self.driver = driver def test_districtlist(self): self.p = GetData() self.driver.find_element_by_xpath(Data.hyper_link).click() self.p.page_loading(self.driver) Districts = self.driver.find_elements_by_xpath(Data.sc_choosedist) self.p.page_loading(self.driver) count = len(Districts)-1 return count
[ { "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/src/SI/MAP/check_with_districts_from_select_box.py
JalajaTR/cQube
import torch import torch.nn as nn import torch.nn.functional as F from layers import ImplicitGraph from torch.nn import Parameter from utils import get_spectral_rad, SparseDropout import torch.sparse as sparse from torch_geometric.nn import global_add_pool class IGNN(nn.Module): def __init__(self, nfeat, nhid, nclass, num_node, dropout, kappa=0.9, adj_orig=None): super(IGNN, self).__init__() self.adj = None self.adj_rho = None self.adj_orig = adj_orig #three layers and two MLP self.ig1 = ImplicitGraph(nfeat, nhid, num_node, kappa) self.ig2 = ImplicitGraph(nhid, nhid, num_node, kappa) self.ig3 = ImplicitGraph(nhid, nhid, num_node, kappa) self.dropout = dropout self.X_0 = None self.V_0 = nn.Linear(nhid, nhid) self.V_1 = nn.Linear(nhid, nclass) def forward(self, features, adj, batch): ''' if adj is not self.adj: self.adj = adj self.adj_rho = get_spectral_rad(adj) ''' self.adj_rho = 1 x = features #three layers and two MLP x = self.ig1(self.X_0, adj, x, F.relu, self.adj_rho, A_orig=self.adj_orig) x = self.ig2(self.X_0, adj, x, F.relu, self.adj_rho, A_orig=self.adj_orig) x = self.ig3(self.X_0, adj, x, F.relu, self.adj_rho, A_orig=self.adj_orig).T x = global_add_pool(x, batch) x = F.relu(self.V_0(x)) x = F.dropout(x, self.dropout, training=self.training) x = self.V_1(x) return F.log_softmax(x, dim=1)
[ { "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
graphclassification/models.py
makinarocks/IGNN
# Time: O(n^2) # Space: O(1) class Solution(object): def triangleNumber(self, nums): """ :type nums: List[int] :rtype: int """ result = 0 nums.sort() for i in reversed(xrange(2, len(nums))): left, right = 0, i-1 while left < right: if nums[left]+nums[right] > nums[i]: result += right-left right -= 1 else: left += 1 return result # Time: O(n^2) # Space: O(1) class Solution2(object): def triangleNumber(self, nums): """ :type nums: List[int] :rtype: int """ result = 0 nums.sort() for i in xrange(len(nums)-2): if nums[i] == 0: continue k = i+2 for j in xrange(i+1, len(nums)-1): while k < len(nums) and nums[i] + nums[j] > nums[k]: k += 1 result += k-j-1 return result
[ { "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
Algo and DSA/LeetCode-Solutions-master/Python/valid-triangle-number.py
Sourav692/FAANG-Interview-Preparation
import unittest import os from parsons import CivisClient, Table # from . import scratch_creds @unittest.skipIf(not os.environ.get('LIVE_TEST'), 'Skipping because not running live test') class TestCivisClient(unittest.TestCase): def setUp(self): self.civis = CivisClient() # Create a schema, create a table, create a view setup_sql = """ drop schema if exists test_parsons cascade; create schema test_parsons; """ self.lst_dicts = [{'first': 'Bob', 'last': 'Smith'}] self.tbl = Table(self.lst_dicts) self.civis.query(setup_sql) def tearDown(self): # Drop the view, the table and the schema teardown_sql = """ drop schema if exists test_parsons cascade; """ self.civis.query(teardown_sql) def test_table_import_query(self): # Test that a good table imports correctly self.civis.table_import(self.tbl, 'test_parsons.test_table') def test_query(self): # Test that queries match self.civis.table_import(self.tbl, 'test_parsons.test_table') tbl = self.civis.query("SELECT COUNT(*) FROM test_parsons.test_table") self.assertEqual(tbl[0]['count'], '1') def test_to_civis(self): # Test that the to_civis() method works too self.tbl.to_civis('test_parsons.test_table')
[ { "point_num": 1, "id": "has_multiple_inheritance", "question": "Does any class in this file use multiple inheritance?", "answer": false }, { "point_num": 2, "id": "all_function_names_snake_case", "question": "Are all function names in this file written in snake_case?", "answer":...
3
test/test_civis.py
Tomiiwa/parsons
# License: BSD Style. from ...utils import verbose from ..utils import _data_path, _get_version, _version_doc @verbose def data_path(path=None, force_update=False, update_path=True, download=True, verbose=None): """ Get path to local copy of the kiloword dataset. This is the dataset from [1]_. Parameters ---------- path : None | str Location of where to look for the kiloword data storing location. If None, the environment variable or config parameter MNE_DATASETS_KILOWORD_PATH is used. If it doesn't exist, the "mne-python/examples" directory is used. If the kiloword dataset is not found under the given path (e.g., as "mne-python/examples/MNE-kiloword-data"), the data will be automatically downloaded to the specified folder. force_update : bool Force update of the dataset even if a local copy exists. update_path : bool | None If True, set the MNE_DATASETS_KILOWORD_PATH in mne-python config to the given path. If None, the user is prompted. verbose : bool, str, int, or None If not None, override default verbose level (see mne.verbose). Returns ------- path : list of str Local path to the given data file. This path is contained inside a list of length one, for compatibility. References ---------- .. [1] Dufau, S., Grainger, J., Midgley, KJ., Holcomb, PJ. A thousand words are worth a picture: Snapshots of printed-word processing in an event-related potential megastudy. Psychological science, 2015 """ return _data_path(path=path, force_update=force_update, update_path=update_path, name='kiloword', download=download) def get_version(): """Get dataset version.""" return _get_version('kiloword') get_version.__doc__ = _version_doc.format(name='kiloword')
[ { "point_num": 1, "id": "has_nested_function_def", "question": "Does this file contain any function defined inside another function?", "answer": false }, { "point_num": 2, "id": "all_params_annotated", "question": "Does every function parameter in this file have a type annotation (ex...
3
mne/datasets/kiloword/kiloword.py
DraganaMana/mne-python