source
string
points
list
n_points
int64
path
string
repo
string
import sys import os import shutil def exit_cli(print_func, message): print_func("%s" % message) sys.exit(0) def display_file(file_name): """ Open given file with default user program. """ if sys.platform.startswith("linux"): os.system("xdg-open %s" % file_name) elif sys.platform.startswith("darwin"): os.system("open %s" % file_name) def remove_dir(directory): for filename in os.listdir(directory): file_path = os.path.join(directory, filename) try: if os.path.isfile(file_path) or os.path.islink(file_path): os.unlink(file_path) elif os.path.isdir(file_path): shutil.rmtree(file_path) except Exception as e: print("Failed to delete %s. Reason: %s" % (file_path, e)) exit_cli(print, "")
[ { "point_num": 1, "id": "no_function_exceeds_5_params", "question": "Does every function in this file take 5 or fewer parameters (excluding self/cls)?", "answer": true }, { "point_num": 2, "id": "every_function_has_docstring", "question": "Does every function in this file have a docs...
3
felicette/utils/sys_utils.py
blac-siren/felicette
"""Blueprint for HacsRepositoryThemes.""" # pylint: disable=too-many-instance-attributes,invalid-name,broad-except,access-member-before-definition import logging from .hacsrepositorybase import HacsRepositoryBase from ..hacsbase.exceptions import HacsRequirement _LOGGER = logging.getLogger("custom_components.hacs.repository") class HacsRepositoryThemes(HacsRepositoryBase): """ Set up a HacsRepositoryThemes object. repository_name(str): The full name of a repository (example: awesome-dev/awesome-repo) """ def __init__(self, repository_name: str, repositoryobject=None): """Initialize a HacsRepositoryThemes object.""" super().__init__() self.repository = repositoryobject self.repository_name = repository_name self.repository_type = "theme" self.manifest_content = None self.name = repository_name.split("/")[-1] async def update(self): """Run update tasks.""" if await self.comperson2_update(): return await self.set_repository_content() async def set_repository_content(self): """Set repository content attributes.""" contentfiles = [] if self.content_path is None: self.content_objects = await self.repository.get_contents( "themes", self.ref ) self.content_path = self.content_objects[0].path self.name = self.content_objects[0].name.replace(".yaml", "") if not isinstance(self.content_objects, list): raise HacsRequirement("Repository structure does not meet the requirements") for filename in self.content_objects: contentfiles.append(filename.name) if contentfiles: self.content_files = contentfiles
[ { "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
custom_components/hacs/repositories/hacsrepositorytheme.py
sjabby/home-assistant-conf
# -*- coding: utf-8 -*- from qcloudsdkcore.request import Request class BgpipQueryResourcesRequest(Request): def __init__(self): super(BgpipQueryResourcesRequest, self).__init__( 'bgpip', 'qcloudcliV1', 'BgpipQueryResources', 'bgpip.api.qcloud.com') def get_region(self): return self.get_params().get('region') def set_region(self, region): self.add_param('region', region) def get_resourceIds(self): return self.get_params().get('resourceIds') def set_resourceIds(self, resourceIds): self.add_param('resourceIds', resourceIds)
[ { "point_num": 1, "id": "all_function_names_snake_case", "question": "Are all function names in this file written in snake_case?", "answer": false }, { "point_num": 2, "id": "every_function_has_docstring", "question": "Does every function in this file have a docstring?", "answer"...
3
qcloudsdkbgpip/BgpipQueryResourcesRequest.py
f3n9/qcloudcli
# # 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 __future__ import print_function import collections import sys from twitter.common import app from apache.aurora.client.base import die def make_commands_str(commands): commands.sort() if len(commands) == 1: return str(commands[0]) elif len(commands) == 2: return '%s (or %s)' % (str(commands[0]), str(commands[1])) else: return '%s (or any of: %s)' % (str(commands[0]), ' '.join(map(str, commands[1:]))) def generate_full_usage(): docs_to_commands = collections.defaultdict(list) for (command, doc) in app.get_commands_and_docstrings(): if doc is not None: docs_to_commands[doc].append(command) def make_docstring(item): (doc_text, commands) = item def format_line(line): return ' %s\n' % line.lstrip() stripped = ''.join(map(format_line, doc_text.splitlines())) return '%s\n%s' % (make_commands_str(commands), stripped) usage = sorted(map(make_docstring, docs_to_commands.items())) return 'Available commands:\n\n' + '\n'.join(usage) @app.command(name='help') def help_command(args): """usage: help [subcommand] Prints help for using the aurora client, or one of its specific subcommands. """ if not args: print(generate_full_usage()) sys.exit(0) if len(args) > 1: die('Please specify at most one subcommand.') subcmd = args[0] if subcmd in app.get_commands(): app.command_parser(subcmd).print_help() else: print('Subcommand %s not found.' % subcmd) sys.exit(1)
[ { "point_num": 1, "id": "every_function_has_docstring", "question": "Does every function in this file have a docstring?", "answer": false }, { "point_num": 2, "id": "no_function_exceeds_5_params", "question": "Does every function in this file take 5 or fewer parameters (excluding sel...
3
src/main/python/apache/aurora/client/commands/help.py
zmanji/incubator-aurora
import numpy as np from qtrader.utils.numpy import eps def _mu_p(w: np.ndarray, r: np.ndarray) -> float: """Portfolio Returns.""" return np.dot(w.T, r) def _sigma_p(w: np.ndarray, Sigma: np.ndarray) -> float: """Portoflio Variance""" return np.dot(np.dot(w.T, Sigma), w) def _trans_costs(w: np.ndarray, w0: np.ndarray, coef: float) -> float: """Transaction Costs.""" return np.sum(np.abs(w0 - w)) * coef def risk_aversion(w: np.ndarray, mu: np.ndarray, Sigma: np.ndarray, w0: np.ndarray, alpha: float, beta: float) -> float: """Risk Aversion with Transaction Costs.""" assert Sigma.shape[0] == Sigma.shape[1] assert mu.shape[0] == Sigma.shape[0] assert w.shape == w0.shape # mean - alpha * variance - transaction_costs return - (_mu_p(w, mu) - alpha * _sigma_p(w, Sigma) - _trans_costs(w, w0, beta)) def sharpe_ratio(w: np.ndarray, mu: np.ndarray, Sigma: np.ndarray, w0: np.ndarray, beta: float) -> float: """Sharpe Ratio with Transaction Costs.""" assert Sigma.shape[0] == Sigma.shape[1] assert mu.shape[0] == Sigma.shape[0] assert w.shape == w0.shape # mean - alpha * variance - transaction_costs return - ((_mu_p(w, mu) - _trans_costs(w, w0, beta)) / (_sigma_p(w, Sigma) + eps))
[ { "point_num": 1, "id": "every_function_has_docstring", "question": "Does every function in this file have a docstring?", "answer": true }, { "point_num": 2, "id": "all_params_annotated", "question": "Does every function parameter in this file have a type annotation (excluding self/c...
4
qtrader/agents/pretrainer/objectives.py
aaron8tang/qtrader
from elasticsearch import Elasticsearch, helpers import os class ElasticSearch: def __init__(self, index): es_host = os.environ['es_hostname'] es_port = os.environ['es_port'] if es_host is None: exit('You need to export Elasticsearch hostname') if es_port is None: exit('You need to export Elasticsearch port number') self.es = Elasticsearch([{'host': es_host, 'port': es_port}]) self.index = index def delete_index(self): if self.exists(): self._result = self.es.indices.delete(self.index) return self def exists(self): return self.es.indices.exists(self.index) def create_index(self): self._result= self.es.indices.create(self.index) return self def add_bulk(self, data, vtype): actions = [] for item in data: item_data = { "_index" : self.index, "_type" : vtype, "_source": item, } actions.append(item_data) return helpers.bulk(self.es, actions, index=self.index)
[ { "point_num": 1, "id": "has_multiple_inheritance", "question": "Does any class in this file use multiple inheritance?", "answer": false }, { "point_num": 2, "id": "no_function_exceeds_5_params", "question": "Does every function in this file take 5 or fewer parameters (excluding self...
3
Elastic_Search.py
duckwed/attack-to-elk
""" __new__()方法, 对象创建的过程, 1- new方法返回一个对象 2- init利用new返回的对象进行属性的添加 """ class Person(object): # 监听创建一个实例对象的过程,需要返回一个对象赋值给xiaoming # new中不return的话,那么久不会执行init方法 def __new__(cls, *args, **kwargs): print("new") print((object.__new__(cls))) return object.__new__(cls) # 构造方法,当执行init方法的时候对象**已经创建成功**,剩下的是将属性添加到对象中 def __init__(self, name): print("init") self.name = name # 类的toString方法 # def __str__(self): # return "我的名字是: %s" % self.name # 监听引用计数为0的时候,python会执行del方法 def __del__(self): print("再见") # xioaming的地址和new中return的obj的地址一样,说明new中返回的obj就是xiaoming xiaoming = Person("小明") print(xiaoming) print("=" * 28) """ python的单例模式,需要使用到new关键方法 1- 保证返回的对象是同一个,在new中修改 2- 保证对象的属性只能赋值一次,在init方法中修改 3- 一般单例模式中的包含静态方法, 类似于Tools.XX, 不需要创建多个对象来调用同一个静态方法 """ class Student(object): # 定义一个类属型保存实例对象 __instance = None # 类属型保证实例属性只能被赋值一次 __is_first = True # s1,s2要保证使用一份内存, 需要new的时候返回同一个对象 def __new__(cls, *args, **kwargs): if cls.__instance is None: cls.__instance = object.__new__(cls) return cls.__instance def __init__(self, name, age): if self.__is_first: self.name = name self.age = age self.__is_first = False # 静态方法 @staticmethod def add_num(a, b): return a + b s1 = Student("小明", 25) s2 = Student("小红", 28) print(s1) print(s2) print(s1.name) print(s2.name)
[ { "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
00Python/day11/basic02.py
HaoZhang95/PythonAndMachineLearning
# 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 oslo_config import cfg from magnum.i18n import _ cinder_group = cfg.OptGroup( name='cinder', title='Options for the Cinder configuration') cinder_client_group = cfg.OptGroup( name='cinder_client', title='Options for the Cinder client') cinder_opts = [ cfg.StrOpt('default_docker_volume_type', help=_('The default docker volume_type to use for volumes ' 'used for docker storage. To use the cinder volumes ' 'for docker storage, you need to select a default ' 'value.'))] cinder_client_opts = [ cfg.StrOpt('region_name', help=_('Region in Identity service catalog to use for ' 'communication with the OpenStack service.'))] def register_opts(conf): conf.register_group(cinder_group) conf.register_group(cinder_client_group) conf.register_opts(cinder_opts, group=cinder_group) conf.register_opts(cinder_client_opts, group=cinder_client_group) def list_opts(): return { cinder_group: cinder_opts, cinder_client_group: cinder_client_opts }
[ { "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
magnum/conf/cinder.py
mail2nsrajesh/magnum
from collections import namedtuple Prediction = namedtuple('Prediction', 'label confidence') Face = namedtuple('Face', 'top_prediction bb all_predictions') BoundingBox = namedtuple('BoundingBox', 'left top right bottom') def top_prediction(idx_to_class, probs): top_label = probs.argmax() return Prediction(label=idx_to_class[top_label], confidence=probs[top_label]) def to_predictions(idx_to_class, probs): return [Prediction(label=idx_to_class[i], confidence=prob) for i, prob in enumerate(probs)] class FaceRecogniser: def __init__(self, feature_extractor, classifier, idx_to_class): self.feature_extractor = feature_extractor self.classifier = classifier self.idx_to_class = idx_to_class def recognise_faces(self, img): bbs, embeddings = self.feature_extractor(img) if bbs is None: # if no faces are detected return [] predictions = self.classifier.predict_proba(embeddings) return [ Face( top_prediction=top_prediction(self.idx_to_class, probs), bb=BoundingBox(left=bb[0], top=bb[1], right=bb[2], bottom=bb[3]), all_predictions=to_predictions(self.idx_to_class, probs) ) for bb, probs in zip(bbs, predictions) ] def __call__(self, img): return self.recognise_faces(img)
[ { "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
face_recognition/face_recogniser.py
jagannath-sahoo/face-recognition-
from json import JSONEncoder import json from iip import Serializer import MyConnMachineIn class MyConnMachineInSerializer(Serializer): """JSON transport serializer for MyConnMachineIn. Generated by: EASy-Producer.""" class MyConnMachineInEncoder(JSONEncoder): """JSON encoder class for MyConnMachineIn. Generated by: EASy-Producer.""" def default(self, o): """Provides access to the attributes in o. Parameters: - o -- the object to serialize Returns: dict the attributes """ return o.__dict__ def readFrom(data: bytes) -> MyConnMachineIn: """Turns bytes into an object. Parameters: - data -- the data bytes Returns: object the deserialized object """ result = MyConnMachineIn() result.__dict__ = json.loads(data) return result def writeTo(source: MyConnMachineIn) -> bytes: """Turns an object into bytes. Parameters: - source -- the object Returns: bytes the serialized data bytes """ return MyConnMachineInEncoder().encode(employee).encode("UTF-8")
[ { "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
Plugins/EASy-Producer/ScenariosTest/testdata/real/IIP-Ecosphere/nov21/expected/SerializerConfig1/MyAppExample/src/main/python/MyConnMachineInSerializer.py
SSEHUB/EASyProducer
import ocdskingfisherprocess.cli.commands.base import ocdskingfisherprocess.database from ocdskingfisherprocess.transform import TRANSFORM_TYPE_UPGRADE_1_0_TO_1_1 class NewTransformUpgrade10To11CLICommand(ocdskingfisherprocess.cli.commands.base.CLICommand): command = 'new-transform-upgrade-1-0-to-1-1' def configure_subparser(self, subparser): self.configure_subparser_for_selecting_existing_collection(subparser) def run_command(self, args): self.run_command_for_selecting_existing_collection(args) if self.collection.deleted_at: print("That collection is deleted!") return id = self.database.get_collection_id( self.collection.source_id, self.collection.data_version, self.collection.sample, transform_from_collection_id=self.collection.database_id, transform_type=TRANSFORM_TYPE_UPGRADE_1_0_TO_1_1) if id: print("Already exists! The ID is {}".format(id)) return id = self.database.get_or_create_collection_id(self.collection.source_id, self.collection.data_version, self.collection.sample, transform_from_collection_id=self.collection.database_id, transform_type=TRANSFORM_TYPE_UPGRADE_1_0_TO_1_1) print("Created! The ID is {}".format(id)) print("Now run transform-collection with that 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
ocdskingfisherprocess/cli/commands/new_transform_upgrade_1_0_to_1_1.py
matiasSanabria/kingfisher-process
from services.game_service import GameService from test.mocks.mock_objects import MockEndgameService def test_play_works_with_no_hand(default_user_data): service = GameService(default_user_data, MockEndgameService()) response = service.play() assert response is not None assert len(service.hand()) == 2 def test_busted(default_user_data, some_busted_hand): default_user_data.hand = some_busted_hand service = GameService(default_user_data, MockEndgameService()) response = service.play() assert response == "EndGameService"
[ { "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
test/services_tests/test_game_service.py
rhsu/slackjack
# logcall.py from functools import wraps def logged(func): # Idea: Give me a function, I'll put logging # around it print('Adding logging to', func.__name__) @wraps(func) def wrapper(*args, **kwargs): print('You called', func.__name__) return func(*args, **kwargs) return wrapper
[ { "point_num": 1, "id": "has_nested_function_def", "question": "Does this file contain any function defined inside another function?", "answer": true }, { "point_num": 2, "id": "all_return_types_annotated", "question": "Does every function in this file have a return type annotation?"...
3
pythonprog/code/12/12.2/logcall.py
davidyshuang/python3
#!/usr/bin/env python import rospy import datetime from pibot import srv def get_cpu_temp(): file = open("/sys/class/thermal/thermal_zone0/temp") temp = float(file.read()) / 1000.0 file.close() return temp def handle_system_server(request): response = srv.systemResponse() now = datetime.datetime.now() response.second = now.second response.minute = now.minute response.hour = now.hour response.day = now.day response.month = now.month response.year = now.year response.cpu_temp = get_cpu_temp() return response def init_system_server(): rospy.init_node('system') s = rospy.Service('srv_system', srv.system, handle_system_server) rospy.loginfo('srv_system initialized') if __name__ == '__main__': init_system_server() rospy.spin()
[ { "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
src/srv_system.py
psby233/PiBot
# Licensed under a 3-clause BSD style license - see LICENSE.rst # -*- coding: utf-8 -*- import io import pytest from astropy import units asdf = pytest.importorskip('asdf', minversion='2.0.0') from asdf.tests import helpers def roundtrip_quantity(yaml, quantity): buff = helpers.yaml_to_asdf(yaml) with asdf.AsdfFile.open(buff) as ff: assert (ff.tree['quantity'] == quantity).all() buff2 = io.BytesIO() ff.write_to(buff2) buff2.seek(0) with asdf.AsdfFile.open(buff2) as ff: assert (ff.tree['quantity'] == quantity).all() def test_value_scalar(tmpdir): testval = 2.71828 testunit = units.kpc yaml = """ quantity: !unit/quantity-1.1.0 value: {} unit: {} """.format(testval, testunit) quantity = units.Quantity(testval, unit=testunit) roundtrip_quantity(yaml, quantity) def test_value_array(tmpdir): testval = [3.14159] testunit = units.kg yaml = """ quantity: !unit/quantity-1.1.0 value: !core/ndarray-1.0.0 {} unit: {} """.format(testval, testunit) quantity = units.Quantity(testval, unit=testunit) roundtrip_quantity(yaml, quantity) def test_value_multiarray(tmpdir): testval = [x*2.3081 for x in range(10)] testunit = units.ampere yaml = """ quantity: !unit/quantity-1.1.0 value: !core/ndarray-1.0.0 {} unit: {} """.format(testval, testunit) quantity = units.Quantity(testval, unit=testunit) roundtrip_quantity(yaml, quantity) def test_value_ndarray(tmpdir): from numpy import array, float64 testval = [[1,2,3],[4,5,6]] testunit = units.km yaml = """ quantity: !unit/quantity-1.1.0 value: !core/ndarray-1.0.0 datatype: float64 data: {} unit: {} """.format(testval, testunit) data = array(testval, float64) quantity = units.Quantity(data, unit=testunit) roundtrip_quantity(yaml, quantity)
[ { "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
astropy/io/misc/asdf/tags/unit/tests/test_quantity.py
rkiman/astropy
from urllib.parse import quote_plus as url_quoteplus from urllib.parse import urlsplit from selenium.webdriver.common.by import By as WebBy from selenium.webdriver.support.ui import Select as WebSelect def allow_flash(driver, url): def _base_url(url): if url.find("://") == -1: url = "http://{}".format(url) urls = urlsplit(url) return "{}://{}".format(urls.scheme, urls.netloc) def _shadow_root(driver, element): return driver.execute_script("return arguments[0].shadowRoot", element) base_url = _base_url(url) driver.get("chrome://settings/content/siteDetails?site={}".format(url_quoteplus(base_url))) root1 = driver.find_element(WebBy.TAG_NAME, "settings-ui") shadow_root1 = _shadow_root(driver, root1) root2 = shadow_root1.find_element(WebBy.ID, "container") root3 = root2.find_element(WebBy.ID, "main") shadow_root3 = _shadow_root(driver, root3) root4 = shadow_root3.find_element(WebBy.CLASS_NAME, "showing-subpage") shadow_root4 = _shadow_root(driver, root4) root5 = shadow_root4.find_element(WebBy.ID, "advancedPage") root6 = root5.find_element(WebBy.TAG_NAME, "settings-privacy-page") shadow_root6 = _shadow_root(driver, root6) root7 = shadow_root6.find_element(WebBy.ID, "pages") root8 = root7.find_element(WebBy.TAG_NAME, "settings-subpage") root9 = root8.find_element(WebBy.TAG_NAME, "site-details") shadow_root9 = _shadow_root(driver, root9) root10 = shadow_root9.find_element(WebBy.ID, "plugins") # Flash shadow_root10 = _shadow_root(driver, root10) root11 = shadow_root10.find_element(WebBy.ID, "permission") WebSelect(root11).select_by_value("allow")
[ { "point_num": 1, "id": "all_function_names_snake_case", "question": "Are all function names in this file written in snake_case?", "answer": true }, { "point_num": 2, "id": "no_function_exceeds_5_params", "question": "Does every function in this file take 5 or fewer parameters (exclu...
3
utils/allow_flash.py
TestOpsFeng/selenium_framework
import math from utils.solution_base import SolutionBase class Solution(SolutionBase): def solve(self, part_num: int): self.test_runner(part_num) func = getattr(self, f"part{part_num}") result = func(self.data) return result def test_runner(self, part_num): test_inputs = self.get_test_input() test_results = self.get_test_result(part_num) test_counter = 1 func = getattr(self, f"part{part_num}") for i, r in zip(test_inputs, test_results): if func(i) == int(r[0]): print(f"test {test_counter} passed") else: print(f"test {test_counter} NOT passed") test_counter += 1 print() def part1(self, data): estimate_time = int(data[0]) bus_ids = list(map(int, filter(lambda item: item != "x", data[1].split(",")))) times = [i * math.ceil(estimate_time / i) - estimate_time for i in bus_ids] return (min_time := min(times)) * bus_ids[times.index(min_time)] def part2(self, data): # use chinese remainder theorem bus_schedules = data[1].split(",") mods = {int(bus_id): (int(bus_id) - idx) % int(bus_id) for idx, bus_id in enumerate(bus_schedules) if bus_id != "x"} mx = list(mods.keys()) vx = list(mods.values()) multiply = math.prod(mx) Mx = [(multiply // item) for item in mx] tx = [] for idx, val in enumerate(mx): t = 0 while 1: t += 1 if (t * Mx[idx]) % val == 1: break tx += [t] result = sum([vx[i] * tx[i] * Mx[i] for i in range(len(mx))]) return result % multiply
[ { "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
solutions/day13.py
nitekat1124/advent-of-code-2020
# Copyright 2019-2022 Simon Zigelli # # 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 asyncio from django.utils import timezone GLOBAL_TIMEOUT = {} class Timeout: def __init__(self, callback=None): self._task = None self.count = 1 self.start_time = timezone.localtime(timezone.now()) if callback is not None: self._task = asyncio.create_task(callback) def cancel(self): if self._task is not None: self._task.cancel() def set_timeout(self, callback): self.cancel() self._task = asyncio.create_task(callback)
[ { "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
app/stage/timeout.py
zigellsn/JWConfStage
from . import SentenceEvaluator from typing import Iterable class SequentialEvaluator(SentenceEvaluator): """ This evaluator allows that multiple sub-evaluators are passed. When the model is evaluated, the data is passed sequentially to all sub-evaluators. All scores are passed to 'main_score_function', which derives one final score value """ def __init__(self, evaluators: Iterable[SentenceEvaluator], main_score_function = lambda scores: scores[-1]): self.evaluators = evaluators self.main_score_function = main_score_function def __call__(self, model, output_path: str = None, epoch: int = -1, steps: int = -1) -> float: scores = [] for evaluator in self.evaluators: scores.append(evaluator(model, output_path, epoch, steps)) return self.main_score_function(scores)
[ { "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
sentence_transformers/evaluation/SequentialEvaluator.py
dd-dos/sentence-transformers
# Code generated by lark_sdk_gen. DO NOT EDIT. from pylark.lark_request import RawRequestReq, _new_method_option from pylark import lark_type, lark_type_sheet, lark_type_approval import attr import typing import io @attr.s class GetDriveFolderChildrenReq(object): types: typing.List[str] = attr.ib( factory=lambda: [], metadata={"req_type": "query", "key": "types"} ) # 需要查询的文件类型,默认返回所有 children;types 可多选,可选类型有 doc、sheet、file、folder 。如 url?types=folder&types=sheet folder_token: str = attr.ib( default="", metadata={"req_type": "path", "key": "folderToken"} ) # 文件夹的 token,获取方式见 [概述](https://open.feishu.cn/document/ukTMukTMukTM/uUDN04SN0QjL1QDN/files/guide/introduction) @attr.s class GetDriveFolderChildrenRespChildren(object): token: str = attr.ib( default="", metadata={"req_type": "json", "key": "token"} ) # 文件的 token name: str = attr.ib( default="", metadata={"req_type": "json", "key": "name"} ) # 文件的标题 type: str = attr.ib( default="", metadata={"req_type": "json", "key": "type"} ) # 文件的类型 @attr.s class GetDriveFolderChildrenResp(object): parent_token: str = attr.ib( default="", metadata={"req_type": "json", "key": "parentToken"} ) # 文件夹的 token children: map[string] * GetDriveFolderChildrenRespChildren = attr.ib( factory=lambda: map[string] * GetDriveFolderChildrenRespChildren(), metadata={"req_type": "json", "key": "children"}, ) # 文件夹的下的文件 def _gen_get_drive_folder_children_req(request, options) -> RawRequestReq: return RawRequestReq( dataclass=GetDriveFolderChildrenResp, scope="Drive", api="GetDriveFolderChildren", method="GET", url="https://open.feishu.cn/open-apis/drive/explorer/v2/folder/:folderToken/children", body=request, method_option=_new_method_option(options), need_tenant_access_token=True, need_user_access_token=True, )
[ { "point_num": 1, "id": "more_functions_than_classes", "question": "Does this file define more functions than classes?", "answer": false }, { "point_num": 2, "id": "has_multiple_inheritance", "question": "Does any class in this file use multiple inheritance?", "answer": false }...
3
pylark/api_service_drive_folder_children_get.py
chyroc/pylark
import glob,os,re,shutil,tempfile from functools import reduce def sorted_number_split(html_base, assetdir, ext): assetfiles = glob.glob(f"{html_base}{assetdir}/*.{ext}") filenames = map(os.path.basename, assetfiles) numberfiles = filter(lambda line: re.match(re.compile(f"[0-9]+\.{ext}"), line), filenames) numberstrs = map(lambda line: re.sub(re.compile(f"\.{ext}"), "", line), numberfiles) numbers = map(int, numberstrs) return list(sorted(numbers)) def convert_line(line, assetdir, assetfile, ext, assetnumbers, include_orgname): if re.search(f"{assetdir}/{assetfile}.{ext}", line): converted_line = reduce(lambda accu, num: accu + line.replace(f"{assetdir}/{assetfile}.{ext}", f"{assetdir}/{num}.{ext}"), assetnumbers, "") if include_orgname: converted_line += line else: converted_line = line return converted_line def split_asset_line(sourcefile, html_base, assetdir, assetfile, ext, include_orgname): with open(sourcefile) as fr: lines = fr.readlines() assetnumbers = sorted_number_split(html_base, assetdir, ext) converted_lines = reduce(lambda accu, line: accu + convert_line(line, assetdir, assetfile, ext, assetnumbers, include_orgname), lines, "") with open(sourcefile, 'w') as fw: fw.write(converted_lines) return if __name__ == '__main__': import sys args = sys.argv if len(args) < 6 or len(args) > 7: pass else: sourcefile = args[1] # "./script.html.erb" html_base = args[2] # "../webapp/priv/static" assetdir = args[3] # "/assets/js/admin" assetfile = args[4] # "admin" ext = args[5] # "js" if len(args) == 6: include_orgname = True else: include_orgname = bool(args[6]) split_asset_line(sourcefile, html_base, assetdir, assetfile, ext, include_orgname)
[ { "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
split_asset_line.py
kay1759/split_asset_line
# Copyright 2017 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests for clif.testing.python.t10.""" from absl.testing import absltest from clif.testing.python import t10 class T10Test(absltest.TestCase): def testImportedClass(self): k = t10.CreateK() self.assertTrue(k.Int1) def testDerivedClass(self): a = t10.A() self.assertEqual(t10.A.C, 1) self.assertEqual(a.C, 1) self.assertEqual(str(a), 'A') if __name__ == '__main__': absltest.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_nested_function_def", "question": "Does this file contain any function defined inside another function?", "ans...
3
clif/testing/python/t10_test.py
wangxf123456/clif
from __future__ import absolute_import from django.conf import settings import ujson from zproject.backends import password_auth_enabled, dev_auth_enabled, google_auth_enabled, github_auth_enabled def add_settings(request): realm = request.user.realm if hasattr(request.user, "realm") else None return { # We use the not_voyager variable name so that templates # will render even if the appropriate context is not provided # to the template 'not_voyager': not settings.VOYAGER, 'zulip_com': settings.ZULIP_COM, 'custom_logo_url': settings.CUSTOM_LOGO_URL, 'register_link_disabled': settings.REGISTER_LINK_DISABLED, 'show_oss_announcement': settings.SHOW_OSS_ANNOUNCEMENT, 'zulip_admin': settings.ZULIP_ADMINISTRATOR, 'login_url': settings.HOME_NOT_LOGGED_IN, 'only_sso': settings.ONLY_SSO, 'external_api_path': settings.EXTERNAL_API_PATH, 'external_api_uri': settings.EXTERNAL_API_URI, 'external_uri_scheme': settings.EXTERNAL_URI_SCHEME, 'api_site_required': settings.EXTERNAL_API_PATH != "api.zulip.com", 'email_integration_enabled': settings.EMAIL_GATEWAY_BOT != "", 'email_gateway_example': settings.EMAIL_GATEWAY_EXAMPLE, 'open_realm_creation': settings.OPEN_REALM_CREATION, 'password_auth_enabled': password_auth_enabled(realm), 'dev_auth_enabled': dev_auth_enabled(), 'google_auth_enabled': google_auth_enabled(), 'github_auth_enabled': github_auth_enabled(), 'development_environment': settings.DEVELOPMENT, } def add_metrics(request): return { 'dropboxAppKey': settings.DROPBOX_APP_KEY }
[ { "point_num": 1, "id": "every_function_has_docstring", "question": "Does every function in this file have a docstring?", "answer": false }, { "point_num": 2, "id": "every_function_under_20_lines", "question": "Is every function in this file shorter than 20 lines?", "answer": fal...
3
zerver/context_processors.py
yicongwu/zulip
import sys import os _force_color = None def set_force_color(force_color): global _force_color _force_color = force_color def support_color(): if _force_color is not None: return _force_color if not sys.stdout.isatty(): return False if os.name == 'posix': return True if os.name == 'nt': try: #os.system('') #enable VT100 Escape Sequence for WINDOWS 10 Ver. 1607 import ctypes kernel32 = ctypes.windll.kernel32 kernel32.SetConsoleMode(kernel32.GetStdHandle(-11), 7) return True except Exception: return False return False def print_color(str, color, **kargs): if support_color(): print(color + str + bcolors.ENDC, **kargs) else: print(str, **kargs) class bcolors: HEADER = '\033[95m' OKBLUE = '\033[94m' OKGREEN = '\033[92m' WARNING = '\033[93m' FAIL = '\033[91m' ENDC = '\033[0m' BOLD = '\033[1m' UNDERLINE = '\033[4m'
[ { "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
libra/cli/color.py
MaslDi/libra-client
# Time: O(n) # Space: O(1) import collections class Solution(object): def majorityElement(self, nums): """ :type nums: List[int] :rtype: int """ idx, cnt = 0, 1 for i in xrange(1, len(nums)): if nums[idx] == nums[i]: cnt += 1 else: cnt -= 1 if cnt == 0: idx = i cnt = 1 return nums[idx] def majorityElement2(self, nums): """ :type nums: List[int] :rtype: int """ return sorted(collections.Counter(nums).items(), key=lambda a: a[1], reverse=True)[0][0] def majorityElement3(self, nums): """ :type nums: List[int] :rtype: int """ return collections.Counter(nums).most_common(1)[0][0]
[ { "point_num": 1, "id": "has_multiple_inheritance", "question": "Does any class in this file use multiple inheritance?", "answer": false }, { "point_num": 2, "id": "no_function_exceeds_5_params", "question": "Does every function in this file take 5 or fewer parameters (excluding self...
3
Python/majority-element.py
black-shadows/LeetCode-Solutions
from reamber.quaver.lists.notes import QuaHoldList from tests.test.qua.test_fixture import qua_map def test_type(qua_map): assert isinstance(qua_map.holds, QuaHoldList) def test_df_names(qua_map): assert {'offset', 'column', 'length', 'key_sounds'}, set(qua_map.holds.df.columns) def test_to_yaml(qua_map): assert set(qua_map.holds.to_yaml()[0].keys()) == {'StartTime', 'Lane', 'KeySounds', 'EndTime'}
[ { "point_num": 1, "id": "every_function_has_docstring", "question": "Does every function in this file have a docstring?", "answer": false }, { "point_num": 2, "id": "no_function_exceeds_5_params", "question": "Does every function in this file take 5 or fewer parameters (excluding sel...
3
tests/test/qua/test_hold_list.py
Eve-ning/reamber_base_py
from django.db import models # models from other Apps from account.models import User # python packages import datetime # ------------------------- COURSE MODEL ----------------------------------------- class Course(models.Model): course_name = models.CharField("course name", max_length=60) course_code = models.IntegerField("course code") section_number = models.SmallIntegerField("section number") year = models.SmallIntegerField("year of realization") semester_choices = ( ('S', 'Spring'), ('F', 'Fall'), ) semester = models.CharField("semester of realization", max_length = 1, choices = semester_choices) professors = models.ManyToManyField(User) students = models.ManyToManyField(User, related_name="students") def __str__(self): return "{} {}{}".format(self.course_name, self.year, self.semester) def is_active(self): "Returns whether the course is active." if self.year >= datetime.datetime.now().year: # realization year >= current year if self.semester == 'S': month = 6 else: month = 12 if month >= datetime.datetime.now().month: # realization month >= current month return True return False # ------------------------- TEAM MODEL ----------------------------------------- class Team(models.Model): # Primary Key is the auto-generated ID team_name = models.CharField("team name", max_length=60) course = models.ForeignKey(Course, on_delete = models.CASCADE) # a Course object student = models.ManyToManyField(User) # a querySet of User objects def __str__(self): return self.team_name
[ { "point_num": 1, "id": "every_class_has_docstring", "question": "Does every class in this file have a docstring?", "answer": false }, { "point_num": 2, "id": "has_multiple_inheritance", "question": "Does any class in this file use multiple inheritance?", "answer": false }, {...
3
registration/models.py
sravanireddy1102/peerevaluationsystem
import os import shutil from webpack.conf import settings def write_file(file_name, content): with open(file_name, 'w') as _file: _file.write(content) def read_file(file_name): with open(file_name, 'r') as _file: return _file.read() def clean_output_root(): # Clean out any files generated from previous test runs if os.path.exists(settings.OUTPUT_ROOT): shutil.rmtree(settings.OUTPUT_ROOT)
[ { "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
tests/utils.py
markfinger/python-webpack
#!/usr/bin/env python # Copyright 2014 The Swarming Authors. All rights reserved. # Use of this source code is governed by the Apache v2.0 license that can be # found in the LICENSE file. import logging import os import sys import tempfile import shutil import unittest import re # Import this first before manipulating sys.path to ensure it can load fine. import logging_utils ROOT_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) sys.path.insert(0, ROOT_DIR) import test_env test_env.setup_test_env() from depot_tools import auto_stub _LOG_HEADER = r'^%s \d\d\d\d-\d\d-\d\d \d\d:\d\d:\d\d\.\d\d\d: ' % os.getpid() class TestLoggingUtils(auto_stub.TestCase): def test_Capture(self): root = logging.RootLogger(logging.DEBUG) with logging_utils.CaptureLogs('foo', root) as log: root.debug('foo') result = log.read() self.assertTrue(re.match(_LOG_HEADER + 'DEBUG foo\n$', result), result) def test_prepare_logging(self): root = logging.RootLogger(logging.DEBUG) tmp_dir = tempfile.mkdtemp(prefix='logging_utils_test') try: filepath = os.path.join(tmp_dir, 'test.log') logging_utils.prepare_logging(filepath, root) root.debug('foo') with open(filepath, 'rb') as f: result = f.read() finally: shutil.rmtree(tmp_dir) # It'd be nice to figure out a way to ensure it's properly in UTC but it's # tricky to do reliably. self.assertTrue(re.match(_LOG_HEADER + 'DEBUG foo\n$', result), result) if __name__ == '__main__': unittest.main()
[ { "point_num": 1, "id": "has_multiple_inheritance", "question": "Does any class in this file use multiple inheritance?", "answer": false }, { "point_num": 2, "id": "more_functions_than_classes", "question": "Does this file define more functions than classes?", "answer": true },...
3
appengine/swarming/swarming_bot/logging_utils_test.py
pombreda/swarming
import json def process_data(data): member_dict = {} def process_post(post): if 'comments' in post: for comment in post['comments']['data']: commenter_id = comment['from']['id'] if commenter_id not in member_dict: member_dict[commenter_id] = comment['from'] member_dict[commenter_id]['comment_count'] = 1 member_dict[commenter_id]['like_count'] = comment['like_count'] else: member_dict[commenter_id]['comment_count'] += 1 member_dict[commenter_id]['like_count'] += comment['like_count'] process_post(comment) for post in data: process_post(post) activity_dict = {} for member_id in member_dict: member = member_dict[member_id] activity_score = 0 if 'comment_count' in member: activity_score += member['comment_count'] if 'like_count' in member: activity_score += 2 * member['like_count'] activity_dict[member['id']] = { 'facebook_id': member_id, 'activity_score': activity_score, 'name': member['name'], 'like_count': member['like_count'], 'comment_count': member['comment_count'], } return activity_dict def top_k_active_members(data, k): members_list = [value for (key, value) in data.items()] members_list.sort(key=lambda x: x['activity_score'], reverse=True) return members_list[:k] def read_files(files): combined_data = [] for file in files: with open('./data/' + file + '.json') as data_file: data = json.load(data_file) combined_data.extend(data['data']) return combined_data def process(): combined_data = read_files(['2015-05-04', '2015-05-05', '2015-05-06', '2015-05-07', '2015-05-08', '2015-05-09', '2015-05-10']) activity_dict = process_data(combined_data) active_members = top_k_active_members(activity_dict, 50) open('./leaderboard/may.json', 'w').write(json.dumps(active_members)) process()
[ { "point_num": 1, "id": "all_params_annotated", "question": "Does every function parameter in this file have a type annotation (excluding self/cls)?", "answer": false }, { "point_num": 2, "id": "has_nested_function_def", "question": "Does this file contain any function defined inside...
3
process-whispers.py
yangshun/nuswhispers-leaderboard
# -*- coding: utf-8 -*- """ Created on Thu Nov 12 22:03:22 2020 @author: kelli """ from binarytodmx import * import unittest import filecmp class TestDMX(unittest.TestCase): def test_volcano(self): """ test with frame data in np array from volcano.sc2 uses rc2 tools to read 'volcano.sc2' and store in array """ volcano = rc2.RC2('volcano.sc2') volcanoFrames = volcano.read() volcanoTest = DMX(volcanoFrames, 0, 1466, 1) volcanoTest.write('VolcanoTest.bin') self.assertTrue(filecmp.cmp('VolcanoTest.bin', 'volcano.sc2')) def test_userinput(self): """tests user input and function supplying random data, seeded from t """ # start time = 0s, end time = 10s, increment .5s test = DMX(testValues, 0, 10, .5) test.write('RandomChannels.bin') file = userInput() self.assertTrue(filecmp.cmp(file, 'RandomChannels.bin')) if __name__ == '__main__': unittest.main()
[ { "point_num": 1, "id": "has_multiple_inheritance", "question": "Does any class in this file use multiple inheritance?", "answer": false }, { "point_num": 2, "id": "every_function_under_20_lines", "question": "Is every function in this file shorter than 20 lines?", "answer": true...
3
binarytodmx_test.py
me701/project-1-kellim521
import logging from troposphere.events import Rule, Target from buildlib.helpers.client_helper import ClientHelper class EventsHelper(object): def __init__(self, template, project, session=None): self.client = ClientHelper.get_client('events', session) self.project = project self.template = template def create_cron_rule(self, schedule_expression, targets, state='ENABLED', name_prefix='', **kwargs): return self.template.add_resource(Rule( '{0}Rule'.format(name_prefix), State=state, Targets=targets, ScheduleExpression=schedule_expression, **kwargs )) def create_target(self, arn, target_id, name_prefix=''): return Target( '{0}Target'.format(name_prefix), Arn=arn, Id=target_id )
[ { "point_num": 1, "id": "no_function_exceeds_5_params", "question": "Does every function in this file take 5 or fewer parameters (excluding self/cls)?", "answer": true }, { "point_num": 2, "id": "more_functions_than_classes", "question": "Does this file define more functions than cla...
3
buildlib/helpers/events.py
ForwardLine/backup-nanny
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def __init__(self, head: ListNode): """ @param head The linked list's head. Note that the head is guaranteed to be not null, so it contains at least one node. """ self.head = head def getRandom(self) -> int: """ Returns a random node's value. """ node = self.head cnt = 0 import random while node: if cnt == 0: pick = node cnt += 1 else: cnt += 1 if random.randint(1, cnt) == 1: pick = node node = node.next return pick.val # Your Solution object will be instantiated and called as such: # obj = Solution(head) # param_1 = obj.getRandom()
[ { "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
LeetCodeSolutions/LeetCode_0382.py
lih627/python-algorithm-templates
import arcade class MyGame(arcade.Window): def __init__(self, width, height, title, bg_color): super().__init__(width, height, title) arcade.set_background_color(bg_color) self.width = width self.height = height self.x = 0 self.y = 0 self.velocity = 1 self.radius = 30 def reverse(self): self.velocity *= -1 def on_draw(self): arcade.start_render() arcade.draw_circle_filled(self.x, self.y, 30, arcade.color.RED) def animate(self, delta_time): self.x += self.velocity * delta_time # Did the circle hit the right side of the screen while moving right? is_at_right = self.x > self.width - self.radius is_moving_right = self.velocity > 0 if is_at_right and is_moving_right: self.reverse() # Same for left edge is_at_left = self.x < self.radius is_moving_left = self.velocity < 0 if is_at_left and is_moving_left: self.reverse() def on_key_press(self, key, modifiers): if key == arcade.key.LEFT or key == arcade.key.RIGHT: self.reverse() elif key == arcade.key.UP: self.y += 10 elif key == arcade.key.DOWN: self.y -= 10 def main(): game = MyGame(600, 600, 'Drawing Example', arcade.color.WHEAT) game.x = 1 game.velocity = 200 arcade.run() if __name__ == '__main__': main()
[ { "point_num": 1, "id": "more_functions_than_classes", "question": "Does this file define more functions than classes?", "answer": true }, { "point_num": 2, "id": "all_function_names_snake_case", "question": "Are all function names in this file written in snake_case?", "answer": ...
3
up_direction/game.py
ramalho/arcade_tutorial
from django.db import models from django.urls import reverse from nautobot.core.models import BaseModel from nautobot.extras.utils import extras_features from nautobot.extras.models import ObjectChange from nautobot.utilities.utils import serialize_object @extras_features("graphql") class DummyModel(BaseModel): name = models.CharField(max_length=20, help_text="The name of this Dummy.") number = models.IntegerField(default=100, help_text="The number of this Dummy.") csv_headers = ["name", "number"] class Meta: ordering = ["name"] def __str__(self): return f"{self.name} - {self.number}" def get_absolute_url(self): return reverse("plugins:dummy_plugin:dummymodel", kwargs={"pk": self.pk}) def to_objectchange(self, action): return ObjectChange( changed_object=self, object_repr=str(self), action=action, # related_object=self.virtual_machine, object_data=serialize_object(self), ) def to_csv(self): return ( self.name, self.number, ) class AnotherDummyModel(BaseModel): name = models.CharField(max_length=20) number = models.IntegerField(default=100) class Meta: ordering = ["name"]
[ { "point_num": 1, "id": "more_functions_than_classes", "question": "Does this file define more functions than classes?", "answer": false }, { "point_num": 2, "id": "every_class_has_docstring", "question": "Does every class in this file have a docstring?", "answer": false }, {...
3
examples/dummy_plugin/dummy_plugin/models.py
jfach/nautobot
#!/usr/bin/env py.test # -*- coding: utf-8 -*- __author__ = "Varun Nayyar <nayyarv@gmail.com>" import numpy as np import pytest import NN.layerversions.layers4 as layer def test_fc(): l1 = layer.FullyConnected(5, 10) x = np.ones((100, 5)) y, c = l1.forward(x) assert y.shape == (100, 10) assert np.all(c == x) def test_tanh(): l = layer.Tanh() x = np.ones((100, 5)) y, c = l.forward(x) assert y.shape == (100, 5) assert np.all(c == y) @pytest.fixture() def optim(): return layer.sgd_optimiser(0.01) def test_back_fc(optim): l1 = layer.FullyConnected(5, 10) x = np.ones((100, 5)) dldy = np.random.randn(100, 10) dldx = l1.backward(dldy, x, optim) assert dldx.shape == (100, 5) def test_back_tanh(): l1 = layer.Tanh() x = np.random.randn(100, 5) dldy = np.random.randn(100, 5) dldx = l1.backward(dldy, np.tanh(x), optim) assert dldx.shape == (100, 5) def test_network(): from NN.loss import MSELoss x = np.random.randn(100, 10) y = np.random.randn(100, 3) net = layer.Network( layer.FullyConnected(10, 20), layer.Tanh(), layer.FullyConnected(20, 3), layer.Tanh() ) mse = MSELoss() layer.train(net, (x, y), 10) yhat, _ = net.forward(x) initloss = mse.loss(y, yhat) layer.train(net, (x, y), 10) yhat, _ = net.forward(x) finloss = mse.loss(yhat, y) assert initloss > finloss
[ { "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": "all_function_names_snake_case", "question": "Are all function names in this file written in snake_case?", "ans...
3
tests/test_layers4.py
nayyarv/CodeANet
import tensorflow as tf # from tensorflow.python.framework.ops import disable_eager_execution # disable_eager_execution() from tensorflow.keras import backend as K def jaccard_tensorflow(y_true, y_pred): """Jaccard score of Tensor in tensorflow for graph mode. """ intersection = tf.sets.intersection(y_true[None:], y_pred[None:]) intersection = tf.sparse.to_dense(intersection)[0] union = tf.sets.union(y_true[None:], y_pred[None:]) union = tf.sparse.to_dense(union)[0] return float(len(intersection) / len(union)) def jaccard_tensorflow_eager(y_true, y_pred): """Jaccard score with built-in function in tensorflow in eager mode. """ set1 = set(y_true.numpy()) set2 = set(y_pred.numpy()) return float((len(set1.intersection(set2))) / (len(set1.union(set2)))) def jaccard_from_keras_cont(y_true, y_pred): """Jaccard score for keras. Taken directly from https://github.com/keras-team/keras-contrib/blob/master/keras_contrib/losses/jaccard.py """ intersection = K.sum(K.abs(y_true * y_pred), axis=-1) sum_ = K.sum(K.abs(y_true) + K.abs(y_pred), axis=-1) jac = (intersection) / (sum_ - intersection) return (1 - jac)
[ { "point_num": 1, "id": "every_function_has_docstring", "question": "Does every function in this file have a docstring?", "answer": true }, { "point_num": 2, "id": "no_function_exceeds_5_params", "question": "Does every function in this file take 5 or fewer parameters (excluding self...
3
metric.py
rangsimanketkaew/learning-to-smell
from django.contrib import admin from adminsortable2.admin import SortableInlineAdminMixin from places.models import Place, Image class ImageInline(SortableInlineAdminMixin, admin.TabularInline): model = Image readonly_fields = ["image_preview"] fields = ("image_file", "image_preview", "image_order") @admin.register(Place) class PlaceAdmin(admin.ModelAdmin): list_display = ("title",) inlines = [ ImageInline, ] @admin.register(Image) class ImageAdmin(admin.ModelAdmin): def image_preview(self, obj): return obj.image_preview readonly_fields = ["image_preview"] fields = ("image_file", "image_preview", "image_order") image_preview.short_description = "Image Preview" image_preview.allow_tags = True
[ { "point_num": 1, "id": "has_multiple_inheritance", "question": "Does any class in this file use multiple inheritance?", "answer": true }, { "point_num": 2, "id": "more_functions_than_classes", "question": "Does this file define more functions than classes?", "answer": false },...
3
where_to_go/places/admin.py
delphython/where-to-go
#!/usr/bin/env python3 # Copyright (c) 2015-2017 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test p2p mempool message. Test that nodes are disconnected if they send mempool messages when bloom filters are not enabled. """ from test_framework.mininode import * from test_framework.test_framework import BitchainTestFramework from test_framework.util import * class P2PMempoolTests(BitchainTestFramework): def set_test_params(self): self.setup_clean_chain = True self.num_nodes = 1 self.extra_args = [["-peerbloomfilters=0"]] def run_test(self): # Add a p2p connection self.nodes[0].add_p2p_connection(P2PInterface()) network_thread_start() self.nodes[0].p2p.wait_for_verack() #request mempool self.nodes[0].p2p.send_message(msg_mempool()) self.nodes[0].p2p.wait_for_disconnect() #mininode must be disconnected at this point assert_equal(len(self.nodes[0].getpeerinfo()), 0) if __name__ == '__main__': P2PMempoolTests().main()
[ { "point_num": 1, "id": "has_multiple_inheritance", "question": "Does any class in this file use multiple inheritance?", "answer": false }, { "point_num": 2, "id": "more_functions_than_classes", "question": "Does this file define more functions than classes?", "answer": true },...
3
test/functional/p2p_mempool.py
Pirontechv/Bitchain
""" This module defines the user model and associated functions """ from werkzeug.security import generate_password_hash from .base_models import BaseModels class UserModel(BaseModels): """ This class encapsulates the functions of the user model """ def __init__(self): """Initializes database""" super().__init__('users') def check_exist(self, key, value): """ Function to check for similar email or username already registered """ query = """SELECT * FROM users WHERE {} = '{}';""".format(key, value) self.cur.execute(query) result = self.cur.fetchall() return len(result) > 0 def find(self, value): """ Function to find a particular user and return data about them """ query = """SELECT user_id,firstname,lastname,email,username,password FROM users WHERE username = '{}';""".format(value) self.cur.execute(query) result = self.cur.fetchone() print(result) return result def create_user(self, user): """Function to create a new user""" password = generate_password_hash(user['password']) query = """INSERT INTO users (firstname,lastname,othername,email,phone_number,username,password)\ VALUES ('{}','{}','{}','{}','{}','{}','{}')\ RETURNING user_id,firstname,lastname,email,phone_number,username ;""".format(user['firstname'], user['lastname'], user['othername'], user['email'], user['phone_number'], user['username'], password) self.cur.execute(query) self.connect.commit() result = self.cur.fetchone() return result
[ { "point_num": 1, "id": "no_function_exceeds_5_params", "question": "Does every function in this file take 5 or fewer parameters (excluding self/cls)?", "answer": true }, { "point_num": 2, "id": "all_params_annotated", "question": "Does every function parameter in this file have a ty...
3
app/api/v2/models/user_models.py
erick-maina/Questioner_API
import json from pkg_resources import resource_filename def load_resource(name): with open(resource_filename('ffmpeg_db', name)) as f: return json.load(f) def ext_to_codecs_json(): return load_resource('data/ext-to-codecs.json') def codec_info_json(): return load_resource('data/codec-info.json')
[ { "point_num": 1, "id": "has_nested_function_def", "question": "Does this file contain any function defined inside another function?", "answer": false }, { "point_num": 2, "id": "all_function_names_snake_case", "question": "Are all function names in this file written in snake_case?",...
3
ffmpeg_db/ffmpeg_db.py
audo-ai/ffmpeg-db
# encoding: utf-8 """ Test process execution and IO redirection. """ __docformat__ = "restructuredtext en" #----------------------------------------------------------------------------- # Copyright (C) 2008-2009 The IPython Development Team # # Distributed under the terms of the BSD License. The full license is # in the file COPYING, distributed as part of this software. #----------------------------------------------------------------------------- from cStringIO import StringIO from time import sleep import sys from IPython.frontend.process import PipedProcess from IPython.testing import decorators as testdec def test_capture_out(): """ A simple test to see if we can execute a process and get the output. """ s = StringIO() p = PipedProcess('echo 1', out_callback=s.write, ) p.start() p.join() result = s.getvalue().rstrip() assert result == '1' def test_io(): """ Checks that we can send characters on stdin to the process. """ s = StringIO() p = PipedProcess(sys.executable + ' -c "a = raw_input(); print a"', out_callback=s.write, ) p.start() test_string = '12345\n' while not hasattr(p, 'process'): sleep(0.1) p.process.stdin.write(test_string) p.join() result = s.getvalue() assert result == test_string @testdec.skip_win32 def test_kill(): """ Check that we can kill a process, and its subprocess. """ s = StringIO() p = PipedProcess(sys.executable + ' -c "a = raw_input();"', out_callback=s.write, ) p.start() while not hasattr(p, 'process'): sleep(0.1) p.process.kill() assert p.process.poll() is not None if __name__ == '__main__': test_capture_out() test_io() test_kill()
[ { "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
IPython/deathrow/oldfrontend/tests/test_process.py
adgaudio/ipython
import secrets import boto3 import moto import pytest from helpers import bulk_delete_dynamo_items, delete_dynamo_item @pytest.fixture def client(): with moto.mock_dynamodb2(): yield boto3.resource("dynamodb", region_name="eu-west-1").meta.client def test_can_delete_single_item(client): client.create_table( TableName="my-table", KeySchema=[{"AttributeName": "id", "KeyType": "HASH"}], AttributeDefinitions=[{"AttributeName": "id", "AttributeType": "N"}], ) for i in range(5): client.put_item( TableName="my-table", Item={"id": i, "value": secrets.token_bytes()} ) # We've written 5 items to the table assert len(client.scan(TableName="my-table")["Items"]) == 5 # After we delete a single item, there are four items in the table delete_dynamo_item(client, table_name="my-table", key={"id": 4}) assert len(client.scan(TableName="my-table")["Items"]) == 4 actual_items = {item["id"] for item in client.scan(TableName="my-table")["Items"]} assert actual_items == {0, 1, 2, 3} def test_can_delete_multiple_items(client): client.create_table( TableName="my-table", KeySchema=[{"AttributeName": "id", "KeyType": "HASH"}], AttributeDefinitions=[{"AttributeName": "id", "AttributeType": "N"}], ) for i in range(50): client.put_item( TableName="my-table", Item={"id": i, "value": secrets.token_bytes()} ) # We've written 50 items to the table assert len(client.scan(TableName="my-table")["Items"]) == 50 # We can delete up to 25 items in a single batch, so delete more than 25 bulk_delete_dynamo_items( client, table_name="my-table", keys=[{"id": i} for i in range(30)] ) # 50 - 30 = 20 assert len(client.scan(TableName="my-table")["Items"]) == 20 actual_items = {item["id"] for item in client.scan(TableName="my-table")["Items"]} assert actual_items == set(range(30, 50))
[ { "point_num": 1, "id": "all_function_names_snake_case", "question": "Are all function names in this file written in snake_case?", "answer": true }, { "point_num": 2, "id": "has_nested_function_def", "question": "Does this file contain any function defined inside another function?", ...
3
scripts/tests/test_dynamo.py
h4l/storage-service
from typing import Union from asphalt.core import Context from asphalt.serialization.api import Serializer from asphalt.serialization.serializers.json import JSONSerializer from motor.motor_asyncio import AsyncIOMotorClient from typeguard import check_argument_types from asphalt.feedreader.api import FeedStateStore class MongoDBStore(FeedStateStore): """ Stores feed states in a MongoDB database. :param client: a Redis client :param serializer: a serializer or the resource name of one (creates a new JSONSerializer if none is specified) :param db: database to store the states in :param collection: name of the collection in the database """ def __init__(self, client: Union[str, AsyncIOMotorClient] = 'default', serializer: Union[str, Serializer] = None, db: str = 'asphalt', collection: str = 'feed_states'): assert check_argument_types() self.client = client self.serializer = serializer or JSONSerializer() self.db = db self.collection_name = collection self.collection = None async def start(self, ctx: Context): if isinstance(self.serializer, str): self.serializer = await ctx.request_resource(Serializer, self.serializer) if isinstance(self.client, str): self.client = await ctx.request_resource(AsyncIOMotorClient, self.client) self.collection = self.client[self.db][self.collection_name] await self.collection.create_index('feed_id') async def store_state(self, feed_id: str, state) -> None: serialized = self.serializer.serialize(state) document = dict(feed_id=feed_id, state=serialized) await self.collection.find_one_and_replace({'feed_id': feed_id}, document, upsert=True) async def load_state(self, feed_id: str): document = await self.collection.find_one({'feed_id': feed_id}, {'state': True}) return self.serializer.deserialize(document['state']) if document else None
[ { "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
asphalt/feedreader/stores/mongodb.py
asphalt-framework/asphalt-feedreader
# # Copyright (C) 2019 Databricks, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import os import pandas as pd from databricks.koalas.testing.utils import ComparisonTestBase, compare_both class EtlTest(ComparisonTestBase): @property def pdf(self): test_dir = os.path.dirname(os.path.realpath(__file__)) return pd.read_csv('%s/../../../data/sample_stocks.csv' % test_dir) @compare_both def test_etl(self, df): df1 = df.loc[:, 'Symbol Date Open High Low Close'.split()] yield df1 df2 = df1.sort_values(by=["Symbol", "Date"]) yield df2 df3 = df2.groupby(by="Symbol").agg({ 'Open': 'first', 'High': 'max', 'Low': 'min', 'Close': 'last' }) yield df3 df4 = df2.copy() df4.loc[:, 'signal_1'] = df4.Close - df4.Open df4.loc[:, 'signal_2'] = df4.High - df4.Low # df4.loc[:, 'signal_3'] = (df4.signal_2 - df4.signal_2.mean()) / df4.signal_2.std() yield df4 df5 = df4.loc[df4.signal_1 > 0, ['Symbol', 'Date']] yield df5 df6 = df4.loc[df4.signal_2 > 0, ['Symbol', 'Date']] yield df6 # df7 = df4.loc[df4.signal_3 > 0, ['Symbol', 'Date']] # yield df7
[ { "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
databricks/koalas/tests/test_etl.py
WeichenXu123/koalas
from starlette.status import HTTP_200_OK, HTTP_403_FORBIDDEN from starlite import RouteHandler, create_test_client, get from starlite.exceptions import PermissionDeniedException from starlite.request import Request async def local_guard(_: Request, route_handler: RouteHandler) -> None: if not route_handler.opt or not route_handler.opt.get("allow_all"): raise PermissionDeniedException("local") def app_guard(request: Request, _: RouteHandler) -> None: if not request.headers.get("Authorization"): raise PermissionDeniedException("app") @get(path="/secret", guards=[local_guard]) def my_router_handler() -> None: ... client = create_test_client(guards=[app_guard], route_handlers=[my_router_handler]) def test_guards(): response = client.get("/secret") assert response.status_code == HTTP_403_FORBIDDEN assert response.json().get("detail") == "app" response = client.get("/secret", headers={"Authorization": "yes"}) assert response.status_code == HTTP_403_FORBIDDEN assert response.json().get("detail") == "local" my_router_handler.opt["allow_all"] = True response = client.get("/secret", headers={"Authorization": "yes"}) assert response.status_code == HTTP_200_OK
[ { "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
tests/test_guards.py
JonasKs/starlite
import sanitize_sheet import pytest def test_check_info(): info = ['abcdef'] assert(sanitize_sheet.check_sampleNames(info)) info = ['abcdefghijklmnopqrstuvwxy1234'] with pytest.raises(Exception): sanitize_sheet.check_info(info) def test_check_for_sequence(): assert(sanitize_sheet.check_for_sequence([float('nan')])) assert(sanitize_sheet.check_for_sequence(['filename.seq'])) with pytest.raises(Exception): sanitize_sheet.check_for_sequence(['ACDEFGHIIH']) def test_proposalNum(): proposalNums = ['123456'] assert(sanitize_sheet.check_proposalNum(proposalNums)) proposalNums = ['su123456'] with pytest.raises(Exception): sanitize_sheet.check_proposalNum(proposalNums)
[ { "point_num": 1, "id": "all_function_names_snake_case", "question": "Are all function names in this file written in snake_case?", "answer": false }, { "point_num": 2, "id": "every_function_has_docstring", "question": "Does every function in this file have a docstring?", "answer"...
3
test_sanitize_sheet.py
RobertSchaffer1/lsdc
# Copyright 2021 Huawei Technologies Co., Ltd # # 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. # ============================================================================== """ feedforward neural network """ import mindspore.nn as nn from mindelec.architecture import get_activation, LinearBlock class FFNN(nn.Cell): """ Full-connect networks. Args: input_dim (int): the input dimensions. output_dim (int): the output dimensions. hidden_layer (int): number of hidden layers. activation (str or Cell): activation functions. """ def __init__(self, input_dim, output_dim, hidden_layer=64, activation="sin"): super(FFNN, self).__init__() self.activation = get_activation(activation) self.fc1 = LinearBlock(input_dim, hidden_layer) self.fc2 = LinearBlock(hidden_layer, hidden_layer) self.fc3 = LinearBlock(hidden_layer, hidden_layer) self.fc4 = LinearBlock(hidden_layer, hidden_layer) self.fc5 = LinearBlock(hidden_layer, output_dim) def construct(self, *inputs): """fc network""" x = inputs[0] out = self.fc1(x) out = self.activation(out) out = self.fc2(out) out = self.activation(out) out = self.fc3(out) out = self.activation(out) out = self.fc4(out) out = self.activation(out) out = self.fc5(out) return out
[ { "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
MindElec/examples/physics_driven/frequency_domain_maxwell/src/model.py
mindspore-ai/mindscience
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # 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 uuid from keystoneclient.tests.v3 import utils from keystoneclient.v3 import domains class DomainTests(utils.TestCase, utils.CrudTests): def setUp(self): super(DomainTests, self).setUp() self.key = 'domain' self.collection_key = 'domains' self.model = domains.Domain self.manager = self.client.domains def new_ref(self, **kwargs): kwargs = super(DomainTests, self).new_ref(**kwargs) kwargs.setdefault('enabled', True) kwargs.setdefault('name', uuid.uuid4().hex) return kwargs
[ { "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
keystoneclient/tests/v3/test_domains.py
citrix-openstack-build/python-keystoneclient
import datetime from django.db import models from django.utils import timezone class Question(models.Model): question_text = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') def __str__(self): return self.question_text def was_published_recently(self): now = timezone.now() return now - datetime.timedelta(days=1) <= self.pub_date <= now was_published_recently.admin_order_field = 'pub_date' was_published_recently.boolean = True was_published_recently.short_description = 'Published recently?' class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0) def __str__(self): return self.choice_text
[ { "point_num": 1, "id": "all_function_names_snake_case", "question": "Are all function names in this file written in snake_case?", "answer": true }, { "point_num": 2, "id": "has_multiple_inheritance", "question": "Does any class in this file use multiple inheritance?", "answer": ...
3
mysite/polls/models.py
3ng7n33r/DjangoTutorial
# -------------------------- # UFSC - CTC - INE - INE5603 # Exercício Processa Números # -------------------------- # Classe responsável por verificar se lista não possui números repetidos. from view.paineis.painel_abstrato import PainelAbstrato from model.processa_numeros import sem_repeticoes class PainelSemRepeticoes(PainelAbstrato): def __init__(self): super().__init__('Sem Repetições') def interaja(self): numeros = self._leiaints() if sem_repeticoes(numeros): msg = 'A lista {} não possui números repetidos.'.format(numeros) else: msg = 'A lista {} possui números repetidos.'.format(numeros) print(msg)
[ { "point_num": 1, "id": "has_multiple_inheritance", "question": "Does any class in this file use multiple inheritance?", "answer": false }, { "point_num": 2, "id": "every_function_has_docstring", "question": "Does every function in this file have a docstring?", "answer": false ...
3
tarefas-poo/lista-02/processa-numeros/view/paineis/painel_sem_repeticoes.py
victoriaduarte/POO_UFSC
import boto3 from datetime import datetime, timedelta from os import environ from src.functions.csv_dump import send_sql rds_client = boto3.client("rds-data") ddb_resource = boto3.resource("dynamodb") shub_table = ddb_resource.Table(environ.get("TABLE_SHUB")) shub_index = environ.get("SHUB_INDEX") db_name = environ.get("DB_NAME") db_table = environ.get("DB_TABLE") db_cluster_arn = environ.get("DB_CLUSTER_ARN") db_secret_arn = environ.get("DB_SECRET_ARN") pipeline_version = environ.get("PIPELINE_VERSION") def handler(event, context): days_ago = [] for day in range(1,8): date = (datetime.now() - timedelta(day)).strftime("%Y-%m-%d") days_ago.append(date) print(f"Offloading fixtures from '{days_ago[-1]}' to '{days_ago[0]}'") for day in days_ago: fixtures = get_day_fixtures(day) print(f"Updating '{len(fixtures)}' fixtures on '{day}' into aurora ...") for fixture in fixtures: update_sql = f"update {db_table} set gameFtScore = :fts where gameID = :id" update_params = [ {"name": "id", "value":{"stringValue": fixture["fixture_id"]}}, {"name": "fts", "value":{"stringValue": fixture["ft_score"]}} ] response = send_sql(db_name, db_secret_arn, db_cluster_arn, update_sql, update_params) if response: print(f"Updated '{day}' fixture id: '{fixture['fixture_id']}'") return { "query_dates": days_ago, "pipeline_version": pipeline_version } def get_day_fixtures(date): day_fixtures = shub_table.query( IndexName=shub_index, KeyConditionExpression="play_date = :date and ft_score > :fts", ExpressionAttributeValues={ ":date": date, ":fts": "-" }, ProjectionExpression="fixture_id, ft_score" ) return day_fixtures["Items"]
[ { "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/functions/fixtures_offload.py
Gilbertly/kickoffai-sls-dataml
import configparser import unittest import adform class AuthorizeTestCase(unittest.TestCase): def setUp(self): config = configparser.ConfigParser() config.read('config.ini') self.client_id = config['DEFAULT']['CLIENT_ID'] self.client_secret = config['DEFAULT']['CLIENT_SECRET'] def test_token_repr_is_str(self): token = adform.auth.Authorize(self.client_id, self.client_secret) self.assertIsInstance(repr(token), str) def test_raise_auth_exception(self): with self.assertRaises(adform.exceptions.AuthorizeError): self.client_id += 'XXX' adform.auth.Authorize(self.client_id, self.client_secret) if __name__ == '__main__': unittest.main()
[ { "point_num": 1, "id": "more_functions_than_classes", "question": "Does this file define more functions than classes?", "answer": true }, { "point_num": 2, "id": "every_function_has_docstring", "question": "Does every function in this file have a docstring?", "answer": false }...
3
tests/test_authorize.py
dutkiewicz/adform-api
# -*- coding: utf-8 -*- import sys from PyQt5.QtWidgets import QApplication, QWidget from PyQt5.QtGui import QPainter, QBrush, QPen from PyQt5.Qt import QColor class MyWindow(QWidget): def __init__(self, parent=None, title=None, size=(640, 480)): super().__init__() self.resize(*size) self.setWindowTitle(title) self.setStyleSheet("background-color : white;"); self.show() def paintEvent(self, QPaintEvent): # Graphics Update qp = QPainter(self) # Draw Circle dia = 100 centerX, centerY = 100, 100 qp.setPen(QColor(0,0,0)) qp.setBrush(QColor(112,146,190)) qp.drawEllipse(centerX - dia/2, centerY - dia/2, dia, dia) def Main(): app = QApplication(sys.argv) w = MyWindow(title="PyQt5 Window Simple", size=(200, 200)) sys.exit(app.exec_()) if __name__=="__main__": Main()
[ { "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
Simple/qtTest.py
Chachay/Python-GUI-Toolkits-Comparison
from recipe_scrapers.purelypope import PurelyPope from tests import ScraperTest class TestPurelyPopeScraper(ScraperTest): scraper_class = PurelyPope def test_host(self): self.assertEqual("purelypope.com", self.harvester_class.host()) def test_canonical_url(self): self.assertEqual( "https://purelypope.com/sweet-chili-brussel-sprouts/", self.harvester_class.canonical_url(), ) def test_title(self): self.assertEqual(self.harvester_class.title(), "Sweet Chili Brussel Sprouts") def test_yields(self): self.assertEqual("4 serving(s)", self.harvester_class.yields()) def test_image(self): self.assertEqual( "https://purelypope.com/wp-content/uploads/2020/05/IMG_5412-1-150x150.jpg", self.harvester_class.image(), ) def test_ingredients(self): self.assertCountEqual( [ "2 cups brussel sprouts, stems removed & cut in half", "2 tbsp coconut aminos", "1 tbsp sriracha", "1/2 tbsp maple syrup", "1 tsp sesame oil", "Everything bagel seasoning or sesame seeds, to top", ], self.harvester_class.ingredients(), ) def test_instructions(self): return self.assertEqual( "Instructions\n\nBrussel Sprout Time!\n\nPreheat oven to 350 degrees.\nWhisk the sauce (coconut aminos, sriracha, maple syrup & sesame oil) together in a large bowl.\nToss in brussel sprouts and coat mixture evenly over the brussels.\nRoast for 30 minutes.\nTurn oven to broil for 2-3 minutes to crisp (watch carefully to not burn.)\nTop with everything or sesame seeds.", self.harvester_class.instructions(), )
[ { "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/test_purelypope.py
mathiazom/recipe-scrapers
import pook import pytest import requests def test_json_operator(should): with pook.use(): pook.get('foo.com', reply=200, response_json={'foo': 'bar'}) res = requests.get('http://foo.com') res | should.have.json.equal.to({'foo': 'bar'}) with pytest.raises(AssertionError): res | should.have.body('foo') def test_json_complex(should): json = { 'foo': { 'foo': 123, 'bar': [ {'baz': True} ] }, 'bar': [1, 2, 3], 'baz': { 'foo': False } } with pook.use(): pook.get('foo.com', reply=200, response_json=json) res = requests.get('http://foo.com') res | should.have.json.equal.to(json) def test_json_chained_operators(should): json = { 'foo': { 'foo': 123, 'bar': [ {'baz': True} ] }, 'bar': [1, 2, 3], 'baz': { 'foo': False } } with pook.use(): pook.get('foo.com', reply=200, response_json=json) res = requests.get('http://foo.com') res | should.have.json.key('foo') > should.be.a('dict') res | should.have.json.key('foo').that.should.be.a('dict')
[ { "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
tests/operators/json_body_test.py
angelneo/http
from __future__ import unicode_literals from django.db import models from django.conf import settings from .player import Player from django.core.urlresolvers import reverse Q = models.Q class Game(models.Model): name = models.CharField(max_length=128, db_index=True) product_key = models.CharField(max_length=32, unique=True) class Meta: app_label = 'gge_proxy_manager' def __unicode__(self): return self.name class Kingdom(models.Model): name = models.CharField(max_length=128, null=True, default=None, blank=True) kid = models.SmallIntegerField(db_index=True) visual_key = models.CharField(max_length=8, default="-") game = models.ForeignKey(Game, db_index=True, null=True, default=None, blank=True) class Meta: app_label = 'gge_proxy_manager' def __unicode__(self): if not self.name: return "(unknown)" return self.name class Confederation(models.Model): name = models.CharField(max_length=128) owner = models.ForeignKey(settings.AUTH_USER_MODEL) slug = models.SlugField(max_length=128) logo = models.FileField(null=True, blank=True, default=None, upload_to='confederation_logos/') description = models.TextField(null=True, blank=True, default=None) class Meta: app_label = 'gge_proxy_manager' def __unicode__(self): return self.name def get_absolute_url(self): return reverse("intern:confederation_dashboard", kwargs={"slug": self.slug}) def get_members(self): return Player.objects.filter(alliance__confederation=self).order_by('alliance_rank', '-level')
[ { "point_num": 1, "id": "more_functions_than_classes", "question": "Does this file define more functions than classes?", "answer": false }, { "point_num": 2, "id": "has_nested_function_def", "question": "Does this file contain any function defined inside another function?", "answ...
3
gge_proxy_manager/models/common.py
mrcrgl/gge-storage
''' Link or unlink a prexisting functionapp with a static webapp. Also known as "Bring your own Functions." ''' from ... pyaz_utils import _call_az def link(function_resource_id, name, resource_group, force=None): ''' Link an Azure Function to a static webapp. Also known as "Bring your own Functions." Only one Azure Functions app is available to a single static web app. Static webapp SKU must be "Standard" Required Parameters: - function_resource_id -- Resource ID of the functionapp to link. Can be retrieved with 'az functionapp --query id' - name -- Name of the static site - resource_group -- Name of resource group. You can configure the default group using `az configure --defaults group=<name>` Optional Parameters: - force -- Force the function link even if the function is already linked to a static webapp. May be needed if the function was previously linked to a static webapp. ''' return _call_az("az staticwebapp functions link", locals()) def unlink(name, resource_group): ''' Unlink an Azure Function from a static webapp Required Parameters: - name -- Name of the static site - resource_group -- Name of resource group. You can configure the default group using `az configure --defaults group=<name>` ''' return _call_az("az staticwebapp functions unlink", locals()) def show(name, resource_group): ''' Show details on the Azure Function linked to a static webapp Required Parameters: - name -- Name of the static site - resource_group -- Name of resource group. You can configure the default group using `az configure --defaults group=<name>` ''' return _call_az("az staticwebapp functions show", locals())
[ { "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
pyaz/staticwebapp/functions/__init__.py
py-az-cli/py-az-cli
from rest_framework import status from django.contrib.auth import get_user_model from rest_framework.reverse import reverse from .basetest import BaseTestCase User = get_user_model() signup_url = reverse("authentication:signup") login_url = reverse("authentication:login") class UserApiTestCase(BaseTestCase): def test_login_user(self): # Test user login self.login_response = self.client.post( login_url, self.login_data, format="json") self.assertEqual(self.login_response.status_code, status.HTTP_200_OK) login_token = self.login_response.data['token'] self.assertEqual( self.login_response.data, {"email": "daniel@test.com", "username": "daniel", "token": login_token} ) def test_get_user_email(self): """ Test model method to get user's email """ self.email = self.login_data["user"]["email"] email = self.email.__str__() self.assertIn(email, "daniel@test.com")
[ { "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
authors/apps/authentication/tests/test_login.py
andela/ah-backend-thanos
from transmute_core.exceptions import NoSerializerFound class SerializerSet(object): """ composes multiple serializers, delegating commands to one that can handle the desired content type. SerializerSet implements a dict-like interface. Retrieving serializers is done by get the content type item: .. code-block:: python serializers["application/json"] """ def __init__(self, serializer_list): self.serializers = serializer_list assert len(self.serializers) > 0, "at least one serializer should be passed!" def _get_serializer_for_type(self, content_type): for serializer in self.serializers: if serializer.can_handle(content_type): return serializer raise NoSerializerFound( "unable to find serializer for " + str(content_type) + " in: " + str(self.serializers) ) def __getitem__(self, content_type): """ from a given content type, returns the appropriate serializer. the list of serializers are interated, from first added to last, and returns the one who's can_handle returns true. """ return self._get_serializer_for_type(content_type) def keys(self): """ return a list of the content types this set supports. this is not a complete list: serializers can accept more than one content type. However, it is a good representation of the class of content types supported. """ return_value = [] for s in self.serializers: return_value += s.content_type return return_value @property def default(self): return self.serializers[0]
[ { "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
transmute_core/contenttype_serializers/serializer_set.py
yunstanford/transmute-core
import argparse import os from liquidcss.workspace import WorkSpace from liquidcss.settings import Settings, Messages from liquidcss.utils import display_output """ Command: liquidcss init Description: Initializes the WorkSpace. Optional Arguments: [--reset -r] : Resets the WorkSpace. [--hard, -hr] : Resets the WorkSpace even if files are deployed. """ workspace = WorkSpace(base_dir = os.getcwd()) settings = Settings(workspace = workspace) def init(): to_console = [] if settings.reset: if settings.hard: workspace.reset() return [*to_console, Messages.workspace_reset] deployed = workspace.files_deployed if deployed: return [*to_console, Messages.files_are_deployed.format(deployed)] workspace.reset() return [*to_console, Messages.workspace_reset] if workspace.base.exists: return [*to_console, Messages.workspace_exists] workspace.init() return [*to_console, Messages.workspace_created] def main(args): parser = argparse.ArgumentParser( prog="liquid init", description="Initializes the WorkSpace.", ) parser.add_argument( "--reset", "-r", action='store_true', help="Resets the WorkSpace.", ) parser.add_argument( "--hard", "-hr", action='store_true', help="Resets the WorkSpace even if files are deployed.", ) parsed_args = parser.parse_args(args) if parsed_args.hard and not parsed_args.reset: parser.error("[--hard] can not be passed in without [--reset -r]") settings.register_from_kwargs(**vars(parsed_args)) to_console = init() display_output(to_console)
[ { "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
liquidcss/commands/init.py
saradzhyanartur/liquidcss
# -*- coding: utf-8 -*- """ Test Composite Map """ import os import pytest import numpy as np import astropy.units as u from astropy.coordinates import SkyCoord import matplotlib.pyplot as plt import sunpy import sunpy.map import sunpy.coordinates import sunpy.data.test from sunpy.tests.helpers import figure_test from sunpy.map import compositemap testpath = sunpy.data.test.rootdir @pytest.fixture def aia171_test_map(): return sunpy.map.Map(os.path.join(testpath, 'aia_171_level1.fits')) @pytest.fixture def heliographic_test_map(): return sunpy.map.Map(os.path.join(testpath, 'heliographic_phase_map.fits.gz')) @pytest.fixture def composite_test_map(): return sunpy.map.Map(aia171_test_map, heliographic_test_map, composite = True) @pytest.fixture def composite_test_map(): return sunpy.map.Map(aia171_test_map, heliographic_test_map, composite=True) @figure_test def test_plot_composite_map(composite_test_map): composite_test_map.plot() @figure_test def test_plot_composite_map_linewidths(composite_test_map): composite_test_map.plot(linewidths=4) @figure_test def test_plot_composite_map_linewidths(composite_test_map): composite_test_map.plot(linewidths=4)
[ { "point_num": 1, "id": "all_function_names_snake_case", "question": "Are all function names in this file written in snake_case?", "answer": true }, { "point_num": 2, "id": "all_params_annotated", "question": "Does every function parameter in this file have a type annotation (excludi...
3
sunpy/map/tests/test_compositemap.py
Swapnil99007/sunpy
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode': """ Time Complexity: O(log N) Average O(N) Worst Space Complexity: O(log N) Average O(N) Worst """ return self.search(root, p.val, q.val) def search(self, root, min_val, max_val): if not root: return None if min_val < root.val and max_val < root.val: # left return self.search(root.left, min_val, max_val) if min_val > root.val and max_val > root.val: # right return self.search(root.right, min_val, max_val) return root
[ { "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
235-lowest-common-ancestor-of-a-binary-search-tree/235-lowest-common-ancestor-of-a-binary-search-tree.py
jurayev/data-structures-algorithms-solutions
import numpy as np import numpy.random as nr from plaidrl.exploration_strategies.base import RawExplorationStrategy class OUStrategy(RawExplorationStrategy): """ This strategy implements the Ornstein-Uhlenbeck process, which adds time-correlated noise to the actions taken by the deterministic policy. The OU process satisfies the following stochastic differential equation: dxt = theta*(mu - xt)*dt + sigma*dWt where Wt denotes the Wiener process Based on the rllab implementation. """ def __init__( self, action_space, mu=0, theta=0.15, max_sigma=0.3, min_sigma=None, decay_period=100000, ): if min_sigma is None: min_sigma = max_sigma self.mu = mu self.theta = theta self.sigma = max_sigma self._max_sigma = max_sigma if min_sigma is None: min_sigma = max_sigma self._min_sigma = min_sigma self._decay_period = decay_period self.dim = np.prod(action_space.low.shape) self.low = action_space.low self.high = action_space.high self.state = np.ones(self.dim) * self.mu self.reset() def reset(self): self.state = np.ones(self.dim) * self.mu def evolve_state(self): x = self.state dx = self.theta * (self.mu - x) + self.sigma * nr.randn(len(x)) self.state = x + dx return self.state def get_action_from_raw_action(self, action, t=0, **kwargs): ou_state = self.evolve_state() self.sigma = self._max_sigma - (self._max_sigma - self._min_sigma) * min( 1.0, t * 1.0 / self._decay_period ) return np.clip(action + ou_state, self.low, self.high)
[ { "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
plaidrl/exploration_strategies/ou_strategy.py
charliec443/plaid-rl
# Adopted from # https://github.com/pytorch/fairseq/blob/master/fairseq/distributed_utils.py import pickle import torch MAX_SIZE_LIMIT = 65533 BYTE_SIZE = 256 def enc_obj2bytes(obj, max_size=4094): """ Encode Python objects to PyTorch byte tensors """ assert max_size <= MAX_SIZE_LIMIT byte_tensor = torch.zeros(max_size, dtype=torch.uint8) obj_enc = pickle.dumps(obj) obj_size = len(obj_enc) if obj_size > max_size: raise Exception( 'objects too large: object size {}, max size {}'.format( obj_size, max_size ) ) byte_tensor[0] = obj_size // 256 byte_tensor[1] = obj_size % 256 byte_tensor[2:2+obj_size] = torch.ByteTensor(list(obj_enc)) return byte_tensor def dec_bytes2obj(byte_tensor, max_size=4094): """ Decode PyTorch byte tensors to Python objects """ assert max_size <= MAX_SIZE_LIMIT obj_size = byte_tensor[0].item() * 256 + byte_tensor[1].item() obj_enc = bytes(byte_tensor[2:2+obj_size].tolist()) obj = pickle.loads(obj_enc) return obj if __name__ == '__main__': test_obj = [1, '2', {3: 4}, [5]] test_obj_bytes = enc_obj2bytes(test_obj) test_obj_dec = dec_bytes2obj(test_obj_bytes) print(test_obj_dec == test_obj)
[ { "point_num": 1, "id": "every_function_has_docstring", "question": "Does every function in this file have a docstring?", "answer": true }, { "point_num": 2, "id": "all_params_annotated", "question": "Does every function parameter in this file have a type annotation (excluding self/c...
3
pythia/utils/objects_to_byte_tensor.py
caodoanh2001/uit-mmf
from .component.appearance import color from .component.geometry import sigma from .primitive import Primitive class BaseNeRF(Primitive): def __init__(self, multires=10, multires_views=4, netdepth=8, netwidth=256) -> None: self.geometry = sigma.Sigma(multires, netdepth, netwidth, netwidth, [4]) self.appearance = color.Color(multires_views, netwidth, netwidth//2) pass def query_sigma(self, xyzs): return self.geometry.forward(xyzs) def query_color(self, geo_features, views): return self.appearance.forward(geo_features, views) def to(self, device): self.appearance.to(device) self.geometry.to(device) def parameters(self): return list(self.geometry.parameters()) + list(self.appearance.parameters()) def export(self): return { 'geometry': self.geometry.state_dict(), 'appearance': self.appearance.state_dict() } def load(self, state_dict): self.geometry.load_state_dict(state_dict['geometry']) self.appearance.load_state_dict(state_dict['appearance'])
[ { "point_num": 1, "id": "all_function_names_snake_case", "question": "Are all function names in this file written in snake_case?", "answer": true }, { "point_num": 2, "id": "no_function_exceeds_5_params", "question": "Does every function in this file take 5 or fewer parameters (exclu...
3
python_api/primitive/base_nerf.py
openNGP/openNGP
# -*- coding: utf-8 -*- ''' ____ ___ ____________ ___ ___ ____ _________________ / __ \/ _ | / __/ _/ __/ / _ \/ _ \/ __ \__ / / __/ ___/_ __/ / /_/ / __ |_\ \_/ /_\ \ / ___/ , _/ /_/ / // / _// /__ / / \____/_/ |_/___/___/___/ /_/ /_/|_|\____/\___/___/\___/ /_/ Operational Aid Source for Infra-Structure Created on 2020. 3. 17.. @author: Hye-Churn Jang, CMBU Specialist in Korea, VMware [jangh@vmware.com] ''' from pygics import Task, Lock, sleep, repose, kill, logInfo lock = Lock() class SportsCar(Task): def __init__(self, name, start_sec): Task.__init__(self, tick=1, delay=start_sec) # every 1 sec run task self.name = name self.start() def __run__(self): lock.on() logInfo('{} run faster more than others.'.format(self.name)) lock.off() repose() class Ferrari(SportsCar): def __init__(self): SportsCar.__init__(self, 'Ferrari', 0) # start after 0 sec class Lamborghini(SportsCar): def __init__(self): SportsCar.__init__(self, 'Lamborghini', 2) # start after 2 sec class Porsche(SportsCar): def __init__(self): SportsCar.__init__(self, 'Porsche', 4) # start after 4 sec f = Ferrari() l = Lamborghini() p = Porsche() sleep(6) f.stop() # stop Ferrari sleep(3) kill(l) # kill Lamborghini sleep(3) p.stop() # stop Porsche
[ { "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
sample/race_tasks.py
HyechurnJang/pygics
import jinja2 from honcho.export.base import BaseExport from honcho.export.base import File class Export(BaseExport): def get_template_loader(self): return jinja2.PackageLoader(__name__, 'templates/supervisord') def render(self, processes, context): context['processes'] = processes filename = "{0}.conf".format(context['app']) template = self.get_template('supervisord.conf') return [File(filename, template.render(context))]
[ { "point_num": 1, "id": "every_function_under_20_lines", "question": "Is every function in this file shorter than 20 lines?", "answer": true }, { "point_num": 2, "id": "has_multiple_inheritance", "question": "Does any class in this file use multiple inheritance?", "answer": false...
3
honcho/export/supervisord.py
mchristen-astranis/honcho
import os from xml.etree.ElementInclude import include from flask import Flask from .db import mongo def create_app(test_config=None): # create and configure the app app = Flask(__name__, instance_relative_config=True) app.config.from_mapping( SECRET_KEY='testing', ) if test_config is None: # load the instance config, if it exists, when not testing app.config.from_pyfile('config.py', silent=True) else: # load the test config if passed in app.config.from_mapping(test_config) # ensure the instance folder exists try: os.makedirs(app.instance_path) except OSError: pass # a simple page that says hello @app.route('/hello') def hello(): return 'Hello, World!' mongo.init_app(app) from . import auth app.register_blueprint(auth.bp) 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": "every_function_has_docstring", "question": "Does every function in this file have a docstring?", "answ...
3
bcMathSociety/flaskr/__init__.py
kennywang01/BCMS
import asyncio import httpx import time import zeep from zeep.transports import AsyncTransport def run_async(): print("async example") print("=============") result = [] def handle_future(future): result.extend(future.result()) loop = asyncio.get_event_loop() client = zeep.AsyncClient("http://localhost:8000/?wsdl") tasks = [ client.service.slow_request("request-1"), # takes 1 sec client.service.slow_request("request-2"), # takes 1 sec ] future = asyncio.gather(*tasks, return_exceptions=True) result = [] future.add_done_callback(handle_future) st = time.time() loop.run_until_complete(future) loop.run_until_complete(client.transport.aclose()) print("time: %.2f" % (time.time() - st)) print("result: %s", result) print("") return future def run_sync(): print("sync example") print("============") transport = zeep.Transport(cache=None) client = zeep.Client("http://localhost:8000/?wsdl", transport=transport) st = time.time() result = [ client.service.slow_request("request-1"), # takes 1 sec client.service.slow_request("request-2"), # takes 1 sec ] print("Time: %.2f" % (time.time() - st)) print("result: %s", result) print("\n") return result if __name__ == "__main__": print("") #asyncio.run(run_async()) run_async() run_sync()
[ { "point_num": 1, "id": "every_function_under_20_lines", "question": "Is every function in this file shorter than 20 lines?", "answer": false }, { "point_num": 2, "id": "every_function_has_docstring", "question": "Does every function in this file have a docstring?", "answer": fal...
3
examples/async_client.py
vascohenriques/python-zeep
import os import time from click.testing import CliRunner from bin.throne import cli as throne runner = CliRunner() shodan_key = os.getenv('SHODAN_KEY') throne_user = os.getenv('THRONE_USER') throne_pass = os.getenv('THRONE_PASS') def test_throne_setapi(): print("Testing: throne api setapi") response = runner.invoke(throne, ["api", "setapi", "-u", f"{throne_user}", "-p", f"{throne_pass}"]) assert response.exit_code == 0 assert "Successfully set throne API key." in response.output def test_shodan_setapi(): print("Testing: throne shodan setapi") response = runner.invoke(throne, ["shodan", "setapi"], input=f"{shodan_key}") assert response.exit_code == 0 assert "Successfully set Shodan API key." in response.output
[ { "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
tests/create_config.py
throne/throne-cli
from tweepy import TweepError from ultron.actions import Action from ultron.exception.twitterexceptions import InvalidUserException from ultron.helpers.twitter_helper import load_api class FollowUser(Action): def __init__(self, screen_name): self.api = load_api() self.follow_status = False self.screen_name = screen_name def pre_execute(self): pass def execute(self): """ Follows a user. """ try: self.api.create_friendship(screen_name=self.screen_name) except TweepError: raise InvalidUserException self.follow_status = True def post_execute(self): if self.follow_status: print('You have followed ' + self.screen_name)
[ { "point_num": 1, "id": "more_functions_than_classes", "question": "Does this file define more functions than classes?", "answer": true }, { "point_num": 2, "id": "all_function_names_snake_case", "question": "Are all function names in this file written in snake_case?", "answer": ...
3
ultron/actions/twitter/followuser.py
Prakash2403/ultron
from cement import Controller from cement.utils.version import get_version_banner from ..core.version import get_version VERSION_BANNER = """ Add Dependencies and Extensions for Hashicorp Packer %s %s """ % (get_version(), get_version_banner()) class Base(Controller): class Meta: label = 'base' description = 'Add Dependencies and Extensions for Hashicorp Packer' arguments = [ (['-v', '--version'], {'action': 'version', 'version': VERSION_BANNER}), ] def _default(self): """Default action if no sub-command is passed.""" self.app.args.print_help()
[ { "point_num": 1, "id": "more_functions_than_classes", "question": "Does this file define more functions than classes?", "answer": false }, { "point_num": 2, "id": "every_class_has_docstring", "question": "Does every class in this file have a docstring?", "answer": false }, {...
3
removalist/controllers/base.py
convenia/removalist
# -*- coding: utf-8 -*- """ 用数组实现队列queue:用数组实现的队列是顺序队列,主要操作有入队和出队操作。 """ from typing import Optional class DynamicQueue: """ 算法步骤: 1.入队列 (1)判断尾指针大小是否位等于队列存储容量 是 (1.2)判断头指针是否位于队列开头, 是,队列已满,无法插入 否,队列未满,将队列进行前部搬移 a.数据整段往前重新复制搬移 b.将尾指针重新赋值,将头指针指0 否 (2)判断尾指针大小是否等于现有队列的长度 是,直接在队列尾部插入数据 否,在尾指针位置插入数据 尾指针加1 2.出队列 (1)判断头指针和尾指针是否相同 否,找到队列头并返回结果,将头指针后移进行赋值 是,队列已经为空,无法进行删除操作 """ def __init__(self, capacity: int): self._items = [] self._head = 0 self._tail = 0 self._capacity = capacity def enqueue(self, item: str): if self._tail == self._capacity: if self._head == 0: return False self._items[0:self._tail-self._head] = self._items[self._head:self._tail] self._tail -= self._head self._head = 0 if self._tail == len(self._items): self._items.append(item) else: self._items[self._tail] = item self._tail += 1 return True def dequeue(self) -> Optional[str]: if self._head != self._tail: temp = self._items[self._head] self._head += 1 return temp def __repr__(self): return " ".join(item for item in self._items[self._head:self._tail]) if __name__ == '__main__': dynamic_queue = DynamicQueue(10) for i in range(10): dynamic_queue.enqueue(str(i)) print(dynamic_queue) for _ in range(3): dynamic_queue.dequeue() print(dynamic_queue) dynamic_queue.enqueue("7") print(dynamic_queue) dynamic_queue.enqueue("8") print(dynamic_queue)
[ { "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
array_queue.py
KAIKAIZHANG/Algorithm
import pytest def test_home(client, auth): # log in as teacher and see teacher home Page # with list of courses auth.login() response = client.get('/home') assert b'Teacher Home Page' in response.data # course not owned by teacher assert b'ENG 101' in response.data # course owned by teacher assert b'METAL 155' in response.data def test_my_courses(client, auth): # log in as teacher auth.login() # see only courses for this teacher response = client.get('/home/mycourses') # course not owned by teacher assert b'ENG 101' not in response.data # course owned by teacher assert b'METAL 155' in response.data def test_teacher_assignment_grades(client, auth): # log in as a teacher auth.login() #see grades for an assignments response = client.get('/course/2/session/2/assignments/3/grades') #make sure the page shows up assert b'Assignment: 3' in response.data #make sure the data was returned assert b'<td>Test Student</td>' in response.data def test_input_grade(client, auth): #log in as a teacher auth.login() #see grade input for correct assignment response = client.get('/course/2/session/2/assignments/3/input-grade/12') assert b'Assignment: 3' in response.data #make a grade input - redirected to correct place with correct data response = client.post('/course/2/session/2/assignments/3/input-grade/12', data={ 'feedback': 'Very good grade!', 'grade_input': 5 }) #make sure redirecting to correct place assert '/3/grades' in response.headers['Location'] response = client.get('/course/2/session/2/assignments/3/grades') #make sure new data is updated on the page after submission assert b'<td>5.00</td>' in response.data
[ { "point_num": 1, "id": "every_function_under_20_lines", "question": "Is every function in this file shorter than 20 lines?", "answer": true }, { "point_num": 2, "id": "no_function_exceeds_5_params", "question": "Does every function in this file take 5 or fewer parameters (excluding ...
3
tests/test_main.py
jczimmerman/tsct-portal
import sys import time import torch from torch.utils.data import IterableDataset import numpy as np def worker_init_fn(worker_id): '''Helper function to launch each worker's env with a different seed''' gym = __import__('gym') worker_info = torch.utils.data.get_worker_info() ds = worker_info.dataset # np.random.seed(worker_info.seed) np.random.seed(np.random.randint(1212)) args = ds.args args.seed = np.random.randint(1212) ds.env = gym.make(args.env, args=args) ds.env.reset() print('worker rand', worker_id, np.random.randint(1212)) class DeformEnvDataset(IterableDataset): def __init__(self, args): super().__init__() self.args = args print('random_number', np.random.randint(10000)) worker_info = torch.utils.data.get_worker_info() def __iter__(self): worker_info = torch.utils.data.get_worker_info() print('worker_info iter', worker_info) args = self.args args.seed = worker_info.seed return self def __next__(self): print('random_number_iter', np.random.randint(10000)) worker_info = torch.utils.data.get_worker_info() print('worker_info next', worker_info) next_obs, rwd, done, info = self.env.step(np.array([0, 0, 0, 0, 0, 0], dtype=np.float16)) if done: raise StopIteration return next_obs
[ { "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
dedo/internal/datasets.py
Nishantjannu/dedo
class FastqParser(object): """A class for parsing and handling fastQ files. Currently only taking care of the sequences not the quality strings. Only four line entries can be handled """ def entries(self, fastq_fh): """Go line by line though the file and return fastq entries. """ current_header = '' current_sequence = '' # Switch telling if this the first entry virgin = True entry_line_counter = 0 for line in fastq_fh: # For usual headers if line[0] == '@' and virgin is False and entry_line_counter == 4: entry_line_counter = 1 yield(current_header, current_sequence) current_header = line[1:-1] current_sequence = '' # For the very first header of the file elif line[0] == '@' and virgin is True: virgin = False current_header = line[1:-1] entry_line_counter = 1 # For sequence lines else: entry_line_counter += 1 if entry_line_counter == 2: current_sequence = line[:-1] # For the last entry if file was not empty if not (current_header == '' and current_sequence == ''): yield(current_header, current_sequence) def single_entry_file_header(self, fastq_fh): first_line = fastq_fh.readline() header = first_line[1:-1] fastq_fh.seek(0) return header def header_id(self, header): """Return only the id of a fastq header Everything after the first white space is discard. """ return header.split()[0]
[ { "point_num": 1, "id": "no_function_exceeds_5_params", "question": "Does every function in this file take 5 or fewer parameters (excluding self/cls)?", "answer": true }, { "point_num": 2, "id": "every_function_under_20_lines", "question": "Is every function in this file shorter than...
3
reademptionlib/fastq.py
Tillsa/READemption
import time from dataclasses import dataclass import jwt from util.enum_util import EnumBase class Role(EnumBase): USER = "USER" ADMIN = "ADMIN" class Perm(EnumBase): NONE = "NONE" READ_MSG = "READ_MSG" WRITE_MSG = "WRITE_MSG" @dataclass class Identity: user: str role: Role.to_enum() perm_mapping = { Role.USER: [Perm.READ_MSG], Role.ADMIN: [Perm.READ_MSG, Perm.WRITE_MSG], } def has_permission(self, perm: Perm) -> bool: return perm in self.perm_mapping[self.role] class JWTAuthenticator(object): ACCESS_JWT_ALGORITHM = "HS256" @classmethod def dump_access_token(cls, key: str, identity: Identity, exp: int) -> str: current_ts = int(time.time()) return jwt.encode( payload=dict( user=identity.user, role=identity.role, nbf=current_ts - 300, # not before exp=current_ts + exp, ), key=key, algorithm=cls.ACCESS_JWT_ALGORITHM, ) @classmethod def load_access_token(cls, key: str, access_token: str) -> Identity: payload = jwt.decode( jwt=access_token, key=key, algorithms=[cls.ACCESS_JWT_ALGORITHM] ) return Identity(user=payload["user"], role=payload["role"])
[ { "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_return_types_annotated", "question": "Does every function in this file have a return...
3
fastapi_example/util/auth_util.py
pkyosx/fastapi-example
# Problem 142: Perfect Square Collection # https://projecteuler.net/problem=142 memo_i_max = 500 memo = [i**2 for i in range(memo_i_max+1)] # note: contains 0**2 def sq(i): global memo_i_max if i > memo_i_max: for j in range(memo_i_max+1, i+100+1): memo.append(j**2) memo_i_max = i+100 # for tmp in range(memo_i_max+1, i+1): # memo.append(tmp**2) # memo_i_max = i return memo[i] def inc_n(n): while True: yield n n += 1 def main(): for ai in inc_n(4): for bi in range(1, ai): a2, b2 = sq(ai), sq(bi) if (a2-b2)%2==0: x, y = (a2+b2)//2, (a2-b2)//2 di, ci = bi+1, ai-1 d2, c2 = sq(di), sq(ci) while d2 < x < c2: if x-d2 > c2-x: di += 1 d2 = sq(di) elif x-d2 < c2-x: ci -= 1 c2 = sq(ci) elif x-d2 == c2-x: z = (c2-d2)//2 if y+z in memo and y-z in memo: print(x, y, z) return x+y+z else: di += 1 d2 = sq(di) else: print("Boing!") print(main()) # 1006193 x y z (434657, 420968, 150568)
[ { "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
p142.py
yehnan/project_euler_python
from typing import Callable import django from django.http import HttpRequest try: from django.utils.datastructures import CaseInsensitiveMapping except ImportError: from .datastructures import CaseInsensitiveMapping # HttpHeaders copypasted from django 3.0 codebase class HttpHeaders(CaseInsensitiveMapping): HTTP_PREFIX = "HTTP_" # PEP 333 gives two headers which aren't prepended with HTTP_. UNPREFIXED_HEADERS = {"CONTENT_TYPE", "CONTENT_LENGTH"} def __init__(self, environ): headers = {} for header, value in environ.items(): name = self.parse_header_name(header) if name: headers[name] = value super().__init__(headers) def __getitem__(self, key): """Allow header lookup using underscores in place of hyphens.""" return super().__getitem__(key.replace("_", "-")) @classmethod def parse_header_name(cls, header): if header.startswith(cls.HTTP_PREFIX): start = len(cls.HTTP_PREFIX) header = header[start:] elif header not in cls.UNPREFIXED_HEADERS: return None return header.replace("_", "-").title() def get_headers_old(request): return HttpHeaders(request.META) def get_headers_v3(request): return request.headers get_headers: Callable[[HttpRequest], HttpHeaders] if django.VERSION[0] < 3: get_headers = get_headers_old else: get_headers = get_headers_v3
[ { "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
ninja/compatibility/request.py
kmlee78/django-ninja
""" Revision ID: 101b182bd0ce Revises: 3aecef07d21a Create Date: 2020-07-15 15:13:13.020740 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = '101b182bd0ce' down_revision = '3aecef07d21a' branch_labels = None depends_on = None def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.add_column('users', sa.Column('account_type', sa.Text(), nullable=False)) # ### end Alembic commands ### def downgrade(): # ### commands auto generated by Alembic - please adjust! ### op.drop_column('users', 'account_type') # ### end Alembic commands ###
[ { "point_num": 1, "id": "all_return_types_annotated", "question": "Does every function in this file have a return type annotation?", "answer": false }, { "point_num": 2, "id": "has_nested_function_def", "question": "Does this file contain any function defined inside another function?...
3
alembic/versions/101b182bd0ce_.py
seamless-io/seamless-web
import pygame from snake.resources.constants import BLOCK_SIZE, WIDTH, HEIGHT from snake.resources.directions import Direction class Point: def __init__(self, x, y): self.x = x self.y = y self.f = 0 self.g = 0 self.h = 0 self.neighbors = [] self.origin = None def __eq__(self, point): return self.__class__ == point.__class__ and self.x == point.x and self.y == point.y def plot(self, display, color): '''Plots the point with given color and fixed size''' pygame.draw.rect(display, color, pygame.Rect(self.x, self.y, BLOCK_SIZE, BLOCK_SIZE)) def get_direction(self): '''Determine direction in which the snake moves based on initial position''' if self.x == self.origin.x and self.y < self.origin.y: return Direction.UP elif self.x == self.origin.x and self.y > self.origin.y: return Direction.DOWN elif self.x < self.origin.x and self.y == self.origin.y: return Direction.LEFT elif self.x > self.origin.x and self.y == self.origin.y: return Direction.RIGHT def generate_neighbors(self): '''Generates neighbors for point object''' if self.x > 0: self.neighbors.append(Point(self.x - BLOCK_SIZE, self.y)) if self.y > 0: self.neighbors.append(Point(self.x, self.y - BLOCK_SIZE)) if self.x < WIDTH - BLOCK_SIZE: self.neighbors.append(Point(self.x + BLOCK_SIZE, self.y)) if self.y < HEIGHT - BLOCK_SIZE: self.neighbors.append(Point(self.x, self.y + BLOCK_SIZE))
[ { "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
snake/main/point.py
megh-khaire/SnakeAIs
from django.core.urlresolvers import reverse from oscar.core.loading import get_model from oscar.test.testcases import WebTestCase, add_permissions from oscar.test.factories import ( CategoryFactory, PartnerFactory, ProductFactory, ProductAttributeFactory) from hooks.test.factories import ( HookEventFactory, HookFactory ) ProductClass = get_model('catalogue', 'ProductClass') Hook = get_model('hooks', 'Hook') class TestAStaffUser(WebTestCase): is_staff = True def setUp(self): super(TestAStaffUser, self).setUp() self.partner = PartnerFactory() def test_can_create_hook_with_hook_event(self): hookevent = HookEventFactory() hook = HookFactory() product_class = ProductClass.objects.create(name="Book") page = self.get(reverse('hook-create', kwargs={"hook_class_slug": product_class.slug})) form = page.form form["name"] = u'books' form["description"] = u'this is description' form["hookevent_set-0-id"] = hook form["hookevent_set-0-signal_type"] = hookevent.signal_type form["hookevent_set-0-URL"] = hookevent.URL form["hookevent_set-0-extra_headers"] = hookevent.extra_headers response = form.submit(name='action', value='save') assert Hook.objects.count() == 2
[ { "point_num": 1, "id": "every_function_under_20_lines", "question": "Is every function in this file shorter than 20 lines?", "answer": true }, { "point_num": 2, "id": "more_functions_than_classes", "question": "Does this file define more functions than classes?", "answer": true ...
3
tests/functional/dashboard/test_hook.py
cage1016/django-oscar-hooks
# Copyright Pincer 2021-Present # Full MIT License can be found in `LICENSE` at the project root. """sent when a message is deleted in a subscribed text channel""" from __future__ import annotations from typing import TYPE_CHECKING from ..objects.events.message import MessageDeleteEvent from ..utils.conversion import construct_client_dict if TYPE_CHECKING: from typing import List, Tuple from ..core.dispatch import GatewayDispatch async def on_message_delete_middleware( self, payload: GatewayDispatch ) -> Tuple[str, MessageDeleteEvent]: """|coro| Middleware for ``on_message_delete`` event. Parameters ---------- payload : :class:`~pincer.core.dispatch.GatewayDispatch` The data received from the message delete event Returns ------- Tuple[:class:`str`, :class:`~pincer.objects.events.message.MessageDeleteEvent`] ``on_message_delete`` and a ``MessageDeleteEvent`` """ # noqa: E501 return ( "on_message_delete", MessageDeleteEvent.from_dict(construct_client_dict(self, payload.data)) ) def export(): return on_message_delete_middleware
[ { "point_num": 1, "id": "every_function_under_20_lines", "question": "Is every function in this file shorter than 20 lines?", "answer": false }, { "point_num": 2, "id": "every_function_has_docstring", "question": "Does every function in this file have a docstring?", "answer": fal...
3
pincer/middleware/message_delete.py
shivamdurgbuns/Pincer
""" BETA test commands """ # dependancies import asyncio import discord from discord.ext import commands # util from utility.cog.player.player import Player from utility.cog.combat_system.cpu import CPU # characters from utility.cog.character.list import c001_sabimen from utility.cog.character.list import c002_sabimen from utility.cog.character.list import c003_sabimen class Cmd_beta(commands.Cog): def __init__(self, client): self.client = client @commands.group() async def beta(self, ctx): return @beta.command() async def combat(self, ctx, user : discord.Member = None): """ new combat system """ # import from utility.cog.combat_system.combat import Combat from utility.cog.character.getter import Character_getter # init caller = Player(ctx, self.client, ctx.message.author) if(user == None): opponent = CPU() opponent.name = "Test" opponent.avatar = caller.avatar else: opponent = Player(ctx, self.client, user) teams = [ { "owner" : caller, "team" : await caller.team.character() }, { "owner" : opponent, "team" : await opponent.team.character() } ] combat = Combat(self.client, ctx, teams) await combat.run() def setup(client): client.add_cog(Cmd_beta(client))
[ { "point_num": 1, "id": "more_functions_than_classes", "question": "Does this file define more functions than classes?", "answer": true }, { "point_num": 2, "id": "all_params_annotated", "question": "Does every function parameter in this file have a type annotation (excluding self/cl...
3
cog/command/beta.py
DrLarck/DiscordBallZ_
from algorithms.genetic import Genome from collections import namedtuple Thing = namedtuple('Thing', ['name', 'value', 'weight']) first_example = [ Thing('Laptop', 500, 2200), Thing('Headphones', 150, 160), Thing('Coffee Mug', 60, 350), Thing('Notepad', 40, 333), Thing('Water Bottle', 30, 192), ] second_example = [ Thing('Mints', 5, 25), Thing('Socks', 10, 38), Thing('Tissues', 15, 80), Thing('Phone', 500, 200), Thing('Baseball Cap', 100, 70) ] + first_example def generate_things(num: int) -> [Thing]: return [Thing(f"thing{i}", i, i) for i in range(1, num+1)] def fitness(genome: Genome, things: [Thing], weight_limit: int) -> int: if len(genome) != len(things): raise ValueError("genome and things must be of same length") weight = 0 value = 0 for i, thing in enumerate(things): if genome[i] == 1: weight += thing.weight value += thing.value if weight > weight_limit: return 0 return value def from_genome(genome: Genome, things: [Thing]) -> [Thing]: result = [] for i, thing in enumerate(things): if genome[i] == 1: result += [thing] return result def to_string(things: [Thing]): return f"[{', '.join([t.name for t in things])}]" def value(things: [Thing]): return sum([t.value for t in things]) def weight(things: [Thing]): return sum([p.weight for p in things]) def print_stats(things: [Thing]): print(f"Things: {to_string(things)}") print(f"Value {value(things)}") print(f"Weight: {weight(things)}")
[ { "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
problems/knapsack.py
hcchengithub/genetic-algorithms
import cv2 import numpy as np from copy import deepcopy as dp aqua=(255,255,0) marine=(116,139,69) banana=(87,207,277) blue=(255,0,0) almond=(205,235,255) brown=(64,64,255) blue1=(255,245,152) green=(0,100,0) orange=(0,140,255) orchid=(139,34,104) pink=(147,20,255) gold=(0,215,255) gray=(127,127,127) indigo=(130,0,75) colors=[aqua,marine,banana,blue,almond,brown,blue1,green,orange,orchid, pink,gold,gray,indigo] size=0 color=0 def draw(event,x,y,flags,param): global color,colors,img,marker,segment,tmg,size mark=color+1 if event==cv2.EVENT_LBUTTONDOWN: cv2.circle(marker,(x,y),size,mark,-1) cv2.circle(tmg,(x,y),size,colors[color],-1) marker_copy=dp(marker) cv2.watershed(img,marker_copy) segment=np.zeros(img.shape,np.uint8) for i in range(1,len(colors)+1): segment[marker_copy==i]=colors[i-1] def func(x): pass a=0 a=int(input('Enter 1 for VideoCam else 0 ')) if a==1: cap=cv2.VideoCapture(0) if cap.isOpened(): ret,img=cap.read() else: ret=False else: img=cv2.imread('a.jpg') img=cv2.GaussianBlur(img,(1,1),0) cv2.namedWindow('image',cv2.WINDOW_NORMAL) cv2.createTrackbar('color','image',0,len(colors)-1,func) cv2.createTrackbar('size','image',10,200,func) cv2.setMouseCallback('image',draw) marker=np.zeros(img.shape[:2],np.int32) segment=np.zeros(img.shape,np.uint8) tmg=dp(img) if a==1: cap.release() while True: color=cv2.getTrackbarPos('color','image') size=cv2.getTrackbarPos('size','image') cv2.imshow('image',tmg) cv2.imshow('segment',segment) if cv2.waitKey(1)==27: break if cv2.waitKey(1)==ord('p'): print() if cv2.waitKey(1)==ord('c'): tmg=dp(img) marker=np.zeros(img.shape[:2],np.int32) segment=np.zeros(img.shape,np.uint8) color=0 cv2.destroyAllWindows()
[ { "point_num": 1, "id": "no_function_exceeds_5_params", "question": "Does every function in this file take 5 or fewer parameters (excluding self/cls)?", "answer": true }, { "point_num": 2, "id": "every_function_has_docstring", "question": "Does every function in this file have a docs...
3
56_interactive_watershed.py
amit-bohra/Interactive-Image-Segmentation-with-OpenCV-Watershed-Algorithm-in-Python3
from django.db import models from servers.models import Server from django.conf import settings import os import hashlib import string class Share(models.Model): """A share""" server = models.ForeignKey(Server) name = models.CharField(max_length=255) path = models.CharField(max_length=255, help_text='Relative path') def get_full_path(self): """Return the full path of the samba share""" # Remove the first slash path = self.path if self.path[0] != '/' else self.path[1:] return os.path.join(self.server.samba_base_folder, path) def get_username(self): """Return the username to use""" return settings.SAMBA_USER_PREFIX + self.name def get_password(self): """Return the password to use""" return filter(lambda x: x if x in string.ascii_letters + string.digits + '.,-' else '', hashlib.sha512(str(self.pk) + self.name + settings.SAMBA_SECRET_KEY).digest())
[ { "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
samba/models.py
PolyLAN/azimut-gestion
import logging import random from telegram.ext import Updater, CommandHandler, MessageHandler, Filters import urllib.request import json import imdb import os BOT_TOKEN = os.environ.get("BOT_TOKEN") OMDB_API_KEY = '558c75c8' ia = imdb.IMDb() logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO) logger = logging.getLogger(__name__) def start(update, context): update.message.reply_text('Hi! \nWelcome to the *IMDb Bot*. \nSend me the name of any movie or TV show to get its details. \nHappy viewing! \n \nCreated by [Karan Malik](https://karan-malik.github.io)',parse_mode='markdown') def help(update, context): update.message.reply_text('Send me the name of any movie to get its details. \nTry out "Avengers Endgame"') def error(update, context): logger.warning('Update "%s" caused error "%s"', update, context.error) def reply(update, context): movie_name=update.message.text search = ia.search_movie(movie_name) id='tt'+search[0].movieID url= 'http://www.omdbapi.com/?i='+id+'&apikey='+OMDB_API_KEY x=urllib.request.urlopen(url) for line in x: x=line.decode() data=json.loads(x) ans='' ans+='*'+data['Title']+'* ('+data['Year']+')'+'\n\n' ans+='*IMDb Rating*: '+data['imdbRating']+' \n' ans+='*Cast*: '+data['Actors']+'\n' ans+='*Genre*: '+data['Genre']+'\n\n' ans+='*Plot*: '+data['Plot']+'\n' ans+='[.]('+data['Poster']+')' update.message.reply_text(ans,parse_mode='markdown') def main(): updater = Updater(BOT_TOKEN, use_context=True) dp = updater.dispatcher dp.add_handler(CommandHandler("start", start)) dp.add_handler(CommandHandler("help", help)) dp.add_handler(MessageHandler(Filters.text, reply)) dp.add_error_handler(error) updater.start_polling() updater.idle() if __name__ == '__main__': main()
[ { "point_num": 1, "id": "all_function_names_snake_case", "question": "Are all function names in this file written in snake_case?", "answer": true }, { "point_num": 2, "id": "no_function_exceeds_5_params", "question": "Does every function in this file take 5 or fewer parameters (exclu...
3
bot.py
Soebb/IMDb_bot
from behave import * from src.Pages.LoginPage import Login from src.Locators.LoginPage import LoginPage @when('I click link "Forgot your password"') def step_impl(context): context.login_page.click(LoginPage.Login.forgot_link) @step("input my email in window") def step_impl(context): context.login_page.input(LoginPage.Login.forgot_email, context.user.email) @step('click button "Reset password"') def step_impl(context): context.login_page.click(LoginPage.Login.forgot_button) @then('I see "Password reset instructions have been sent to your"') def step_impl(context): context.login_page.driver.find_element_by_css_selector(LoginPage.Login.forgot_description).is_displayed()
[ { "point_num": 1, "id": "all_function_names_snake_case", "question": "Are all function names in this file written in snake_case?", "answer": true }, { "point_num": 2, "id": "no_function_exceeds_5_params", "question": "Does every function in this file take 5 or fewer parameters (exclu...
3
src/features/steps/forgot_password_steps.py
kirasdad/Hacathon18_09
class Enterprise: def __init__(self, name): if len(name.strip()) == 0: raise ValueError("Name must be specified.") self._name = name def get_name(self): return self._name
[ { "point_num": 1, "id": "has_multiple_inheritance", "question": "Does any class in this file use multiple inheritance?", "answer": false }, { "point_num": 2, "id": "has_nested_function_def", "question": "Does this file contain any function defined inside another function?", "answ...
3
structurizr/model/enterprise.py
sixty-north/structurizr-python
from __future__ import absolute_import from rest_framework.response import Response from sentry.api.serializers import serialize from sentry.api.bases import OrganizationEndpoint from sentry.discover.models import DiscoverSavedQuery from sentry import features from sentry.discover.endpoints.bases import DiscoverSavedQueryPermission from sentry.discover.endpoints.serializers import DiscoverSavedQuerySerializer class DiscoverSavedQueriesEndpoint(OrganizationEndpoint): permission_classes = (DiscoverSavedQueryPermission,) def get(self, request, organization): """ List saved queries for organization """ if not features.has("organizations:discover", organization, actor=request.user): return self.respond(status=404) saved_queries = list( DiscoverSavedQuery.objects.filter(organization=organization) .all() .prefetch_related("projects") .order_by("name") ) return Response(serialize(saved_queries), status=200) def post(self, request, organization): """ Create a saved query """ if not features.has("organizations:discover", organization, actor=request.user): return self.respond(status=404) serializer = DiscoverSavedQuerySerializer( data=request.data, context={"organization": organization} ) if not serializer.is_valid(): return Response(serializer.errors, status=400) data = serializer.validated_data model = DiscoverSavedQuery.objects.create( organization=organization, name=data["name"], query=data["query"], created_by=request.user if request.user.is_authenticated() else None, ) model.set_projects(data["project_ids"]) return Response(serialize(model), status=201)
[ { "point_num": 1, "id": "all_params_annotated", "question": "Does every function parameter in this file have a type annotation (excluding self/cls)?", "answer": false }, { "point_num": 2, "id": "has_multiple_inheritance", "question": "Does any class in this file use multiple inherita...
3
src/sentry/discover/endpoints/discover_saved_queries.py
evanspjz/sentry
# from twilio.rest import Client # # Your Account SID from twilio.com/console # account_sid = "AC4100c72954a1f9949fc4700a8d0594bb" # # Your Auth Token from twilio.com/console # auth_token = "e1529115d0f1a57b6b8e6b17644f6087" # client = Client(account_sid, auth_token) # message = client.messages \ # .create( # to="+919930035998", # from_="+19496196487", # body="Hello from Python!") # print(message.sid) def call1(): from twilio.rest import Client # Your Account Sid and Auth Token from twilio.com/console account_sid = 'AC09c050b96951b1bbed41f71ab5f2f472' auth_token = '8630c09dff748daf78bcc1436ba2e34a' client = Client(account_sid, auth_token) message = client.messages \ .create( body="The user wants to connect", from_='+14156896062', to='+918655232275' ) print(message.sid) def call2(): from twilio.rest import Client # Your Account Sid and Auth Token from twilio.com/console account_sid = 'AC09c050b96951b1bbed41f71ab5f2f472' auth_token = '8630c09dff748daf78bcc1436ba2e34a' client = Client(account_sid, auth_token) message = client.messages \ .create( body="The user is requesting a call", from_='+14156896062', to='+918879490461' ) print(message.sid)
[ { "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
silverstrike/views/twilio1.py
JinHash5/ExpenseIt
import random ### Advantage Logic ### def advantage(rollfunc): roll1 = rollfunc roll2 = rollfunc if roll1 > roll2: return roll1 else: return roll2 ### Disadvantage Logic ### def disadvantage(rollfunc): roll1 = rollfunc roll2 = rollfunc if roll1 < roll2: return roll1 else: return roll2 ### Die Rolls ### def rolld4(sides:int=4): return random.randint(1, sides) def rolld6(sides:int=6): return random.randint(1, sides) def rolld8(sides:int=8): return random.randint(1, sides) def rolld10(sides:int=10): return random.randint(1, sides) def rolld12(sides:int=12): return random.randint(1, sides) def rolld20(sides:int=20): return random.randint(1, sides)
[ { "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
DieRolls.py
bwnelb/dnd5e
import uuid from datetime import datetime from django.db import models from django.utils import timezone from .game import Game from .player import Player from .util import generate_code class SupplyCodeManager(models.Manager): def create_supply_code(self, game: Game, value: 5, code: None) -> 'SupplyCode': if code is None or code == '' or self.filter(code=code): code = generate_code(6) # For set of all supply codes, each code must be unique while self.filter(code=code): code = generate_code(6) if type(value) is int: value = int(value) else: value = 5 supply_code = self.model(code=code.upper(), game=game, value=value) supply_code.save() return supply_code class SupplyCode(models.Model): id: uuid = models.UUIDField(primary_key=True, default=uuid.uuid4) game: Game = models.ForeignKey(Game, on_delete=models.CASCADE) code: str = models.CharField(max_length=6, unique=True) value: int = models.IntegerField() point_modifier: int = models.IntegerField(default=0) active: bool = models.BooleanField(default=True) claimed_by: Player = models.ForeignKey(Player, on_delete=models.CASCADE, null=True, blank=True) claimed_at: datetime = models.DateTimeField(null=True, blank=True) created_at: datetime = models.DateTimeField(auto_now_add=True) modified_at: datetime = models.DateTimeField(auto_now=True) objects = SupplyCodeManager() def claim(self, player: Player, point_modifier: int) -> 'SupplyCode': self.claimed_by = player self.claimed_at = timezone.now() self.point_modifier = point_modifier self.save() return self def __str__(self): return self.code
[ { "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
app/models/supply_code.py
uwhvz/uwhvz
# coding: utf-8 """ Kubernetes No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) OpenAPI spec version: v1.11.1 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.v1beta1_network_policy_list import V1beta1NetworkPolicyList class TestV1beta1NetworkPolicyList(unittest.TestCase): """ V1beta1NetworkPolicyList unit test stubs """ def setUp(self): pass def tearDown(self): pass def testV1beta1NetworkPolicyList(self): """ Test V1beta1NetworkPolicyList """ # FIXME: construct object with mandatory attributes with example values #model = kubernetes.client.models.v1beta1_network_policy_list.V1beta1NetworkPolicyList() 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": "all_function_names_snake_case", "question": "Are all function names in this file written in snake_case?", "answer"...
3
kubernetes/test/test_v1beta1_network_policy_list.py
reymont/python
import json import configparser import re import logging from modules.exceptions import SettingsError log = logging.getLogger(__name__) def readjson(jfile): """... just for reading json file and return data :)""" with open(jfile) as descriptor: data = json.load(descriptor) return data def read_ini_to_dict(inifile): """read ini file to parsed dictionary""" log.debug("Reading %s", inifile) return parseINI(readINI(inifile)) def parseINI(inidict): """... just for transform value into right type""" initype = {} for k in inidict.keys(): i = inidict[k].split("#")[0] if i in ["True", "False"]: initype[k] = i == "True" elif re.match("^[0-9]+$", i): initype[k] = int(i) elif re.match("^[0-9]+\.[0-9]+$", i): initype[k] = float(i) else: initype[k] = str(i) return initype def readINI(inifile): """... just for reading .ini file and return data""" config = configparser.ConfigParser() try: config.read(inifile) except configparser.DuplicateOptionError as err: log.error("Error while reading ini file %s", err) raise SettingsError(f"Duplicate Option in Settings File: {err}") from err return config._sections
[ { "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
modules/file_utils.py
Efemache/Mercenaries-Hearthstone-game-bot
# # Copyright (c) 2016-2021 Wind River Systems, Inc. # # SPDX-License-Identifier: Apache-2.0 # from django.utils.translation import ugettext_lazy as _ import horizon from openstack_dashboard.api import base from openstack_dashboard.dashboards.admin import dashboard class SoftwareManagement(horizon.Panel): name = _("Software Management") slug = 'software_management' permissions = ('openstack.services.platform', 'openstack.roles.admin') def allowed(self, context): if not base.is_service_enabled(context['request'], 'platform'): return False elif context['request'].user.services_region == 'SystemController': return False else: return super(SoftwareManagement, self).allowed(context) def nav(self, context): if not base.is_service_enabled(context['request'], 'platform'): return False elif context['request'].user.services_region == 'SystemController': return False else: return True dashboard.Admin.register(SoftwareManagement)
[ { "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
starlingx-dashboard/starlingx-dashboard/starlingx_dashboard/dashboards/admin/software_management/panel.py
starlingx/gui
# -*- coding: utf-8 -*- import unittest from datetime import date from rdcache.ext import RedisCache, RedisPool redis = RedisPool({ "default": { "host": "127.0.0.1", "port": 6379, "password": "", "db": 0, }, }) backend = redis.get('default') cache = RedisCache(backend, touch = True) user_rows = { 'alice': {'username':'alice', 'gender':'F', 'birthday':date(1981,10,10)}, 'bob': {'username':'bob', 'gender':'M', 'birthday':date(1988,9,9)}, 'candy': {'username':'candy', 'gender':'F', 'birthday':date(1983,7,15)}, 'david': {'username':'david', 'gender':'M', 'birthday':date(1992,1,3)}, 'emily': {'username':'eric', 'gender':'M', 'birthday':date(1991,12,25)}, } @cache('user:%s', type = 'hash', time = 60) def read_user(username): return user_rows.get(username) @cache('birthes', type = 'zset', time = 120) def read_birthes(): return [(u, user_rows[u]['birthday']) for u in user_rows.iterkeys()] def get_user(username): user = read_user(username) key = 'user:%s' % username if backend.type(key) == 'hash': user2 = backend.hgetall(key) else: user2 = {} return user, user2 def get_birthes(): birthes = dict(read_birthes()) birthes2 = dict(backend.zrange('birthes', 0, -1, withscores = True)) return birthes, birthes2 class RedisCacheTestCase(unittest.TestCase): """ 单元测试 """ def test_none(self): eric, eric2 = get_user('eric') self.assertEqual(eric, {}) self.assertEqual(eric2, {}) def test_hash(self): candy, candy2 = get_user('candy') self.assertEqual(candy, candy2) def test_zset(self): birthes, birthes2 = get_birthes() self.assertEqual(len(birthes), len(birthes2)) for k, v in birthes.iteritems(): self.assertEqual(v, birthes2.get(k)) if __name__ == '__main__': unittest.main()
[ { "point_num": 1, "id": "has_nested_function_def", "question": "Does this file contain any function defined inside another function?", "answer": false }, { "point_num": 2, "id": "every_function_has_docstring", "question": "Does every function in this file have a docstring?", "ans...
3
tests/test_redis.py
azhai/rdcache
"""Demonstrates partial run when some input data not there. """ from remake import Remake, TaskRule ex8 = Remake() class CannotRun(TaskRule): rule_inputs = {'in1': 'data/inputs/input_not_there.txt'} rule_outputs = {'out': 'data/inputs/ex8_in1.txt'} def rule_run(self): input_text = self.inputs['in1'].read_text() self.outputs['out'].write_text(input_text + '\n') class CanRun1(TaskRule): rule_inputs = CannotRun.rule_outputs rule_outputs = {'out1': 'data/outputs/ex8/out1.txt', 'out2': 'data/outputs/ex8/out2.txt'} def rule_run(self): for o in self.outputs.values(): o.write_text('out') class CanRun2(TaskRule): rule_inputs = {'in': 'data/outputs/ex8/out{i}.txt'} rule_outputs = {'out1': 'data/outputs/ex8/out2.{i}.txt'} var_matrix = {'i': [1, 2]} def rule_run(self): assert len(self.inputs) == len(self.outputs) for i, o in zip(self.inputs.values(), self.outputs.values()): o.write_text('\n'.join([f'f1 {line}' for line in i.read_text().split('\n')[:-1]]) + '\n') if __name__ == '__main__': ex8.finalize()
[ { "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
remake/examples/ex8.py
markmuetz/remake