source
string
points
list
n_points
int64
path
string
repo
string
import os import subprocess import typer from typer.testing import CliRunner from options.autocompletion import tutorial008 as mod runner = CliRunner() app = typer.Typer() app.command()(mod.main) def test_completion(): result = subprocess.run( ["coverage", "run", mod.__file__, " "], stdout=subprocess.PIPE, stderr=subprocess.PIPE, encoding="utf-8", env={ **os.environ, "_TUTORIAL008.PY_COMPLETE": "complete_zsh", "_TYPER_COMPLETE_ARGS": "tutorial008.py --name ", "_TYPER_COMPLETE_TESTING": "True", }, ) assert '"Camila":"The reader of books."' in result.stdout assert '"Carlos":"The writer of scripts."' in result.stdout assert '"Sebastian":"The type hints guy."' in result.stdout assert "['--name']" in result.stderr def test_1(): result = runner.invoke(app, ["--name", "Camila", "--name", "Sebastian"]) assert result.exit_code == 0 assert "Hello Camila" in result.output assert "Hello Sebastian" in result.output def test_script(): result = subprocess.run( ["coverage", "run", mod.__file__, "--help"], stdout=subprocess.PIPE, stderr=subprocess.PIPE, encoding="utf-8", ) assert "Usage" in result.stdout
[ { "point_num": 1, "id": "every_function_under_20_lines", "question": "Is every function in this file shorter than 20 lines?", "answer": true }, { "point_num": 2, "id": "has_nested_function_def", "question": "Does this file contain any function defined inside another function?", "...
3
tests/test_tutorial/test_options/test_completion/test_tutorial008.py
KBoehme/typer
from __future__ import absolute_import, unicode_literals import string from jaraco.text import FoldedCase class IRCFoldedCase(FoldedCase): """ A version of FoldedCase that honors the IRC specification for lowercased strings (RFC 1459). >>> IRCFoldedCase('Foo^').lower() 'foo~' >>> IRCFoldedCase('[this]') == IRCFoldedCase('{THIS}') True >>> IRCFoldedCase().lower() '' """ translation = dict(zip( map(ord, string.ascii_uppercase + r"[]\^"), map(ord, string.ascii_lowercase + r"{}|~"), )) def lower(self): return ( self.translate(self.translation) if self # bypass translate, which returns self else super(IRCFoldedCase, self).lower() ) def lower(str): return IRCFoldedCase(str).lower()
[ { "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
irc/strings.py
EliotNapa/slack_irc_rt_gate
import streamlit as st from utils.constants import NAVIGATION, NAV_VIZ from pages.data_visualization import sidebar_filter def navbar(): st.subheader("Navigation") st.radio("Go to...", options=NAVIGATION, key="page") def show_sidebar(): sidebar = st.sidebar with sidebar: navbar() if st.session_state.page == NAV_VIZ: sidebar_filter()
[ { "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
streamlit/components/sidebar.py
teresaromero/palmer-penguins
#!/usr/bin/env python # coding: utf-8 """ Copyright (C) 2017 Jacksgong(jacksgong.com) 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 okcat.terminalcolor import colorize, allocate_color, BLACK __author__ = 'JacksGong' class Trans: trans_msg_map = None trans_tag_map = None hide_msg_list = None def __init__(self, trans_msg_map, trans_tag_map, hide_msg_list): self.trans_msg_map = trans_msg_map self.trans_tag_map = trans_tag_map self.hide_msg_list = hide_msg_list def trans_msg(self, msg): if self.trans_msg_map is None: return msg for key in self.trans_msg_map: if msg.startswith(key): value = self.trans_msg_map[key] return u'| %s | %s' % (colorize(value, fg=allocate_color(value)), msg) return msg def trans_tag(self, tag, msg): if self.trans_tag_map is None or tag is None: return msg for key in self.trans_tag_map: if key in tag: prefix = self.trans_tag_map[key] return u'%s %s' % (colorize(prefix, bg=allocate_color(prefix)), msg) return msg def hide_msg(self, msg): if self.hide_msg_list is None: return msg if msg.__len__() > 100: return msg for gray_msg in self.hide_msg_list: if msg.startswith(gray_msg): return colorize(msg, fg=BLACK) return msg
[ { "point_num": 1, "id": "no_function_exceeds_5_params", "question": "Does every function in this file take 5 or fewer parameters (excluding self/cls)?", "answer": true }, { "point_num": 2, "id": "more_functions_than_classes", "question": "Does this file define more functions than cla...
3
okcat/trans.py
Ryfthink/okcat
# Manticore Search Client # Copyright (c) 2020-2021, Manticore Software LTD (https://manticoresearch.com) # # All rights reserved import unittest class ParametrizedTestCase(unittest.TestCase): def __init__(self, methodName='runTest', settings=None): super(ParametrizedTestCase, self).__init__(methodName) self.settings = settings @staticmethod def parametrize(testcase_class, settings=None): testloader = unittest.TestLoader() testnames = testloader.getTestCaseNames(testcase_class) suite = unittest.TestSuite() for name in testnames: suite.addTest(testcase_class(name, settings=settings)) return suite
[ { "point_num": 1, "id": "more_functions_than_classes", "question": "Does this file define more functions than classes?", "answer": true }, { "point_num": 2, "id": "has_multiple_inheritance", "question": "Does any class in this file use multiple inheritance?", "answer": false },...
3
test/python/parametrized_test_case.py
vsmid/openapi
# Copyright (C) 2020 Google Inc. # Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file> """ Creator reads Program Proposals Create Date: 2019-07-25 11:55:57.361793 """ # disable Invalid constant name pylint warning for mandatory Alembic variables. # pylint: disable=invalid-name from ggrc.migrations.utils import ( acr_propagation_constants_program_proposals as acr_constants ) from ggrc.migrations.utils import acr_propagation # revision identifiers, used by Alembic. revision = 'f00343450894' down_revision = '91d3ba424a6b' def upgrade(): """Upgrade database schema and/or data, creating a new revision.""" acr_propagation.propagate_roles( acr_constants.GGRC_NEW_ROLES_PROPAGATION, with_update=True ) def downgrade(): """Downgrade database schema and/or data back to the previous revision.""" raise NotImplementedError("Downgrade is not supported")
[ { "point_num": 1, "id": "every_function_under_20_lines", "question": "Is every function in this file shorter than 20 lines?", "answer": true }, { "point_num": 2, "id": "every_function_has_docstring", "question": "Does every function in this file have a docstring?", "answer": true...
3
src/ggrc/migrations/versions/20190725_f00343450894_creator_reads_program_proposals.py
MikalaiMikalalai/ggrc-core
import logging class CoreLogging(object): """simple logging testing and dev""" def __init__(self): self.name = ".simplydomain.log" def start(self, level=logging.INFO): logger = logging.getLogger("simplydomain") logger.setLevel(level) fh = logging.FileHandler(self.name) formatter = logging.Formatter( '%(asctime)s-[%(name)s]-[%(levelname)s]- %(message)s') fh.setFormatter(formatter) logger.addHandler(fh) logger.info("Program started") logging.captureWarnings(True) logger.info("Set Logging Warning Capture: True") def debugmsg(self, message, modulename): try: msg = 'simplydomain.' + str(modulename) logger = logging.getLogger(msg) logger.debug(str(message)) except Exception as e: print(e) def infomsg(self, message, modulename): try: msg = 'simplydomain.' + str(modulename) logger = logging.getLogger(msg) logger.info(str(message)) except Exception as e: print(e) def warningmsg(self, message, modulename): try: msg = 'simplydomain.' + str(modulename) logger = logging.getLogger(msg) logger.warning(str(message)) except Exception as e: print(e)
[ { "point_num": 1, "id": "all_params_annotated", "question": "Does every function parameter in this file have a type annotation (excluding self/cls)?", "answer": false }, { "point_num": 2, "id": "more_functions_than_classes", "question": "Does this file define more functions than clas...
3
simplydomain/src/core_logger.py
SimplySecurity/SimplyDomain-Old
import json import requests from app.settings import TOKEN TELEGRAM_URL_API = 'https://api.telegram.org/bot' def __build_url(method): url = '{}{}/{}'.format(TELEGRAM_URL_API, TOKEN, method) return url def __post(url, body, params=dict()): """ Internal post :param url: :param body: :param params: :return: """ try: headers = {'Content-type': 'application/json'} requests.post(url, data=body, params=params, headers=headers) except Exception as e: print(e) def send_message(message): """ It sends a message to telegram :param message: dict() whith "text" mandatory :return: """ method = 'sendMessage' url = __build_url(method) __post(url, json.dumps(message))
[ { "point_num": 1, "id": "every_function_has_docstring", "question": "Does every function in this file have a docstring?", "answer": false }, { "point_num": 2, "id": "every_function_under_20_lines", "question": "Is every function in this file shorter than 20 lines?", "answer": tru...
3
app/telegram/api.py
mendrugory/monkey-note-bot
#!/usr/bin/env python3 # -*- coding:utf-8 -*- # author: bigfoolliu """ 829. 连续整数求和 给定一个正整数 N,试求有多少组连续正整数满足所有数字之和为 N? 示例 1: 输入: 5 输出: 2 解释: 5 = 5 = 2 + 3,共有两组连续整数([5],[2,3])求和后为 5。 示例 2: 输入: 9 输出: 3 解释: 9 = 9 = 4 + 5 = 2 + 3 + 4 示例 3: 输入: 15 输出: 4 解释: 15 = 15 = 8 + 7 = 4 + 5 + 6 = 1 + 2 + 3 + 4 + 5 middle_ret肯定为有理数,否则不存在 N middle(数字个数) middle_ret(差不多为中间数字或者大1或者小1) 15 1 15 必须有 15 3 5 整除,中间数字为5, 5 >= (3-1)/2, 可以 15 5 3 整除,中间数字为3, 3 >= (5-1)/2, 可以 15 7 2.1xx 非整除,肯定不可以 15 2 7.5 可以 7 + 8 15 4 3.75, 3或者4, 15 6 2.5,2或者3 说明: 1 <= N <= 10 ^ 9 """ import unittest class Solution: def consecutiveNumbersSum(self, N): """ :param N: int :return: """ ret = 1 # 1.从1开始整除,如果可以有连续的结果,那么肯定为奇数或者偶数个整数相加得到 # 2.如果最终结果为奇数个数相加,则中间的整数middle能被整除,且整除结果middle_ret肯定不小于 (middle-1)/2 # 3.如果最终结果为偶数个数相加,则 for i in range(0, ): pass return ret class TestDemo(unittest.TestCase): def setUp(self): self.solution = Solution().consecutiveNumbersSum def test1(self): self.assertEqual(2, self.solution(5)) def test2(self): self.assertEqual(3, self.solution(9)) def test3(self): self.assertEqual(4, self.solution(15)) 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
algorithms/leetcode/contest/83/829.py
bigfoolliu/liu_aistuff
try: from urllib.parse import urljoin except ImportError: from urlparse import urljoin ConnectionRefusedError = OSError import logging import random import requests import tornado import ujson def parse_body(req, **fields): try: data = tornado.escape.json_decode(req.body) except ValueError: data = {} return data def _genrand(values, x=10000): id = random.randint(0, x) while id in values: id = random.randint(0, x) return id def safe_get(path, data=None, cookies=None, proxies=None): try: resp = requests.get(path, data=data, cookies=cookies, proxies=proxies) return ujson.loads(resp.text) except ConnectionRefusedError: return {} except ValueError: logging.critical("route:{}\terror code: {}\t{}".format(path, resp.status_code, resp.text)) raise def safe_post(path, data=None, cookies=None, proxies=None): try: resp = requests.post(path, data=data, cookies=cookies, proxies=proxies) return ujson.loads(resp.text) except ConnectionRefusedError: return {} except ValueError: logging.critical("route:{}\nerror code: {}\t{}".format(path, resp.status_code, resp.text)) raise def safe_post_cookies(path, data=None, cookies=None, proxies=None): try: resp = requests.post(path, data=data, cookies=cookies, proxies=proxies) return ujson.loads(resp.text), resp.cookies except ConnectionRefusedError: return {}, None except ValueError: logging.critical("route:{}\nerror code: {}\t{}".format(path, resp.status_code, resp.text)) raise def construct_path(host, method): return urljoin(host, method)
[ { "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
crowdsource/utils.py
texodus/crowdsource
#!/usr/bin/env python # -*- coding: utf-8 -*- """Simple one dimensional example for a possible user's script.""" import argparse from orion.client import report_results def function(x, y): """Evaluate partial information of a quadratic.""" y = x + y - 34.56789 return 4 * y**2 + 23.4, 8 * y def execute(): """Execute a simple pipeline as an example.""" # 1. Receive inputs as you want parser = argparse.ArgumentParser() parser.add_argument("-x", type=float, required=True) parser.add_argument("-y", type=float, default=0.0) inputs = parser.parse_args() # 2. Perform computations y, dy = function(inputs.x, inputs.y) # 3. Gather and report results results = list() results.append(dict(name="example_objective", type="objective", value=y)) results.append(dict(name="example_gradient", type="gradient", value=[dy])) report_results(results) if __name__ == "__main__": execute()
[ { "point_num": 1, "id": "every_function_has_docstring", "question": "Does every function in this file have a docstring?", "answer": true }, { "point_num": 2, "id": "has_nested_function_def", "question": "Does this file contain any function defined inside another function?", "answ...
3
tests/functional/branching/black_box_with_y.py
satyaog/orion
""" strings and logic related to composing notifications """ HELLO_STATUS = "Hello! I'm Vaccination Notifier" HELLO_MESSAGE = ( "Hello there!\n" "\n" "I'm Vaccination Notifier. This is just a message to let you know I'm running and " "to test our notification configuration. I'll check for changes to your " "vaccination status once every {delay} minutes---unless I crash! Every now and then, " "you should probably check on me to make sure nothing has gone wrong.\n" "\n" "Love,\n" "Vaccination Notifier" ) def hello_message(delay): return (HELLO_STATUS, HELLO_MESSAGE.format(delay=delay)) UPDATE_STATUS = "Vaccination update detected" UPDATE_MESSAGE = ( "Hello there!\n" "\n" "I noticed that your vaccination results page was updated recently. Here's " "a summary of the update:\n" "Health Facility:{facility}\n" "Vaccination Location:{location}\n" "Date:{date}\n" "Time:{time}\n" "\n" "Love,\n" "Vaccination Notifier" ) def update_message(dict): facility = dict['Health Facility:'] location = dict['Vaccination Location:'] date = dict['Date:'] time = dict['Time:'] return (UPDATE_STATUS, UPDATE_MESSAGE.format(facility=facility, location=location, date=date, time=time))
[ { "point_num": 1, "id": "every_function_under_20_lines", "question": "Is every function in this file shorter than 20 lines?", "answer": true }, { "point_num": 2, "id": "has_nested_function_def", "question": "Does this file contain any function defined inside another function?", "...
3
messages.py
Cedric0303/Vaccination-Notifier
import dash_bootstrap_components as dbc from dash import Input, Output, State, html collapses = html.Div( [ dbc.Button( "Toggle left", color="primary", id="left", className="me-1", n_clicks=0, ), dbc.Button( "Toggle right", color="primary", id="right", className="me-1", n_clicks=0, ), dbc.Button("Toggle both", color="primary", id="both", n_clicks=0), dbc.Row( [ dbc.Col( dbc.Collapse( dbc.Card("This is the left card!", body=True), id="left-collapse", is_open=True, ) ), dbc.Col( dbc.Collapse( dbc.Card("This is the right card!", body=True), id="right-collapse", is_open=True, ) ), ], className="mt-3", ), ] ) @app.callback( Output("left-collapse", "is_open"), [Input("left", "n_clicks"), Input("both", "n_clicks")], [State("left-collapse", "is_open")], ) def toggle_left(n_left, n_both, is_open): if n_left or n_both: return not is_open return is_open @app.callback( Output("right-collapse", "is_open"), [Input("right", "n_clicks"), Input("both", "n_clicks")], [State("right-collapse", "is_open")], ) def toggle_left(n_right, n_both, is_open): if n_right or n_both: return not is_open return is_open
[ { "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
docs/components_page/components/collapse/multiple.py
glsdown/dash-bootstrap-components
from ..factor import TableFactor import numpy as np import pandas as pd from itertools import combinations def discrete_entropy(x): def make_factor(data, arguments, leak=1e-9): factor = TableFactor(arguments, list(data.columns)) factor.fit(data) factor.table += leak factor.normalize(*factor.scope, copy=False) return factor arguments = list(x.columns) factor_x = make_factor(x, arguments).normalize(*arguments) prob = factor_x.table.flatten() return -np.sum(prob * np.log(prob)) def discrete_mutual_information(x, y): if x.shape[1] == 0 or y.shape[1] == 0: return 0 def make_factor(data, arguments, leak=1e-9): factor = TableFactor(arguments, list(data.columns)) factor.fit(data) factor.table += leak factor.normalize(*factor.scope, copy=False) return factor xy = pd.concat([x, y], axis=1) arguments = list(xy.columns) factor_x = make_factor(x, arguments) factor_y = make_factor(y, arguments) factor_xy = make_factor(xy, arguments).normalize(*arguments, copy=False) part1 = factor_xy.table.flatten() part2 = (factor_xy / (factor_x * factor_y).normalize(*arguments, copy=False)).table.flatten() result = np.sum(part1 * np.log(part2)) if np.isnan(result): return +np.inf return result def information_matrix(data, mi_estimator=discrete_mutual_information): m = len(data.columns) values = data.values information_matrix = np.zeros((m, m)) for (i, fst), (j, snd) in combinations(enumerate(data.columns), 2): information_matrix[i, j] = information_matrix[j, i] = mi_estimator(data[[fst]], data[[snd]]) return pd.DataFrame(data=dict(zip(data.columns, information_matrix)), index=data.columns)
[ { "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
graphmodels/information/information.py
DLunin/pygraphmodels
#!/usr/bin/env python from actions.action import Action import os import contextlib import re import shutil __author__ = "Ryan Sheffer" __copyright__ = "Copyright 2020, Sheffer Online Services" __credits__ = ["Ryan Sheffer", "VREAL"] class Copy(Action): """ Copy Action An action designed to copy file/s as part of a build process. TODO: Setup wildcard like copying? Take advantage of a copy module with a lot of options. TODO: Have many copying options, like many files in a folder to another folder. Whole dir trees, etc. """ def __init__(self, config, **kwargs): super().__init__(config, **kwargs) self.copy_items = kwargs['copy'] if 'copy' in kwargs else [] def verify(self): if not len(self.copy_items): return 'No items to copy!' for item in self.copy_items: if type(item) is not list or len(item) != 2: return 'Invalid copy item found in copy list!' item[0] = self.replace_tags(item[0]) item[1] = self.replace_tags(item[1]) if not os.path.isfile(item[0]): return 'Copy item ({}) does not exist!'.format(item[0]) return '' def run(self): for item in self.copy_items: with contextlib.suppress(FileNotFoundError): os.unlink(item[1]) os.makedirs(os.path.dirname(item[1]), exist_ok=True) print('Copying {} to {}'.format(item[0], item[1])) shutil.copy2(item[0], item[1]) return True if __name__ == "__main__": class VarClassTest(object): def __init__(self): self.HI2_there = "some\\cool\\path" self.three = "another\\cool\\path" print(Copy.replace_path_sections('hello\\{HI2_there}\\then\\there\\were\\{three}\\bla.exe', VarClassTest())) print(Copy.replace_path_sections('hello\\then\\there\\{not_found}\\three.exe', VarClassTest()))
[ { "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
PyUE4Builder/actions/copy.py
rfsheffer/PyUE4Builder
# -*- coding: utf-8 -*- """Playbook app wrapper for TextBlob (https://github.com/sloria/TextBlob).""" import traceback from tcex import TcEx from textblob import TextBlob def parse_arguments(): """Parse arguments coming into the app.""" tcex.parser.add_argument('--string', help='String', required=True) tcex.parser.add_argument('--n_gram', help='n-gram length', required=False, default="3") return tcex.args def main(): """.""" args = parse_arguments() # read the string from the playbook to get the actual value of the argument string = tcex.playbook.read(args.string) n_gram_number = int(tcex.playbook.read(args.n_gram)) tcex.log.info('String value: {}'.format(string)) tcex.log.info('n-gram number: {}'.format(n_gram_number)) blob = TextBlob(string) tags = dict() for tag in blob.tags: tags[tag[0]] = tag[1] tcex.playbook.create_output('json', blob.json) tcex.playbook.create_output('nGrams', [str(n_gram) for n_gram in blob.ngrams(n=n_gram_number)]) tcex.playbook.create_output('nounPhrases', blob.noun_phrases) tcex.playbook.create_output('npCounts', blob.np_counts[1]) tcex.playbook.create_output('polarity', blob.polarity) tcex.playbook.create_output('sentences', [str(sentence) for sentence in blob.sentences]) tcex.playbook.create_output('subjectivity', blob.subjectivity) tcex.playbook.create_output('tags', tags) tcex.playbook.create_output('tokens', blob.tokens) tcex.playbook.create_output('wordCounts', blob.word_counts[1]) tcex.playbook.create_output('words', blob.words) tcex.exit(0) if __name__ == "__main__": tcex = TcEx() try: # start the app main() except SystemExit: pass except Exception as e: # if there are any strange errors, log it to the logging in the UI err = 'Generic Error. See logs for more details ({}).'.format(e) tcex.log.error(traceback.format_exc()) tcex.message_tc(err) tcex.exit(1)
[ { "point_num": 1, "id": "every_function_has_docstring", "question": "Does every function in this file have a docstring?", "answer": true }, { "point_num": 2, "id": "every_function_under_20_lines", "question": "Is every function in this file shorter than 20 lines?", "answer": fals...
3
apps/TCPB_-_Text_Blob/text_blob/text_blob.py
cvahid/threatconnect-playbooks
import requests class Url: def __init__(self, url): self.url = url def get_url(self): return self.url def set_url(self, url): self.url = url def open_url(self): resp = requests.get(self.url) return resp.text
[ { "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
package/module.py
alexcreek/python-template
''' Copyright (c) 2011-2014, Agora Games, LLC All rights reserved. https://github.com/agoragames/haigha/blob/master/LICENSE.txt ''' from chai import Chai from haigha.frames import heartbeat_frame from haigha.frames.heartbeat_frame import HeartbeatFrame from haigha.frames.frame import Frame class HeartbeatFrameTest(Chai): def test_type(self): assert_equals(8, HeartbeatFrame.type()) def test_parse(self): frame = HeartbeatFrame.parse(42, 'payload') assert_true(isinstance(frame, HeartbeatFrame)) assert_equals(42, frame.channel_id) def test_write_frame(self): w = mock() expect(mock(heartbeat_frame, 'Writer')).args('buffer').returns(w) expect(w.write_octet).args(8).returns(w) expect(w.write_short).args(42).returns(w) expect(w.write_long).args(0).returns(w) expect(w.write_octet).args(0xce) frame = HeartbeatFrame(42) frame.write_frame('buffer')
[ { "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
tests/unit/frames/heartbeat_frame_test.py
simomo/haigha
from sqlalchemy import Column, Integer, String, Enum as PgEnum, Float from enum import Enum from sqlalchemy.orm import relationship from api.utils.db_init import Base class Influence(Enum): bad = "bad" neutral = "neutral" good = "good" class Nutrition(Base): __tablename__ = 'nutrition' id = Column(Integer, primary_key=True, unique=True) # nutrition_id name = Column(String(50), nullable=False, unique=True) amount = Column(String(50), nullable=True) # сделать int или хранить строку с значением и measure influence = Column(PgEnum(Influence)) percent_of_daily_needs = Column(Float, nullable=True) nutrition = relationship("NutritionToIngredient", back_populates="child") recipes = relationship("NutritionToRecipe", back_populates="child") def __repr__(self): return '<Nutrition %r>' % 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": "more_functions_than_classes", "question": "Does this file define more functions than classes?", "answer": false }...
3
api/models/nutrition.py
syth0le/async_cookeat
#!/usr/bin/env python3 # Copyright 2020 The Chromium OS Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import sys import unittest class DummyCliUnittest(unittest.TestCase): def testImportCrosFactory(self): from cros.factory.cli import factory_env # pylint: disable=unused-import def testSysPath(self): self.assertIn('factory/py_pkg', ' '.join(sys.path)) 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": "has_multiple_inheritance", "question": "Does any class in this file use multiple inheritance?", "answ...
3
py/cli/testdata/scripts/dummy_script.py
arccode/factory
# # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. from typing import TYPE_CHECKING, Any, List, Sequence, Union from airflow.models import BaseOperator from airflow.providers.vertica.hooks.vertica import VerticaHook if TYPE_CHECKING: from airflow.utils.context import Context class VerticaOperator(BaseOperator): """ Executes sql code in a specific Vertica database. :param vertica_conn_id: reference to a specific Vertica database :param sql: the SQL code to be executed as a single string, or a list of str (sql statements), or a reference to a template file. Template references are recognized by str ending in '.sql' """ template_fields: Sequence[str] = ('sql',) template_ext: Sequence[str] = ('.sql',) ui_color = '#b4e0ff' def __init__( self, *, sql: Union[str, List[str]], vertica_conn_id: str = 'vertica_default', **kwargs: Any ) -> None: super().__init__(**kwargs) self.vertica_conn_id = vertica_conn_id self.sql = sql def execute(self, context: 'Context') -> None: self.log.info('Executing: %s', self.sql) hook = VerticaHook(vertica_conn_id=self.vertica_conn_id) hook.run(sql=self.sql)
[ { "point_num": 1, "id": "more_functions_than_classes", "question": "Does this file define more functions than classes?", "answer": true }, { "point_num": 2, "id": "has_multiple_inheritance", "question": "Does any class in this file use multiple inheritance?", "answer": false },...
3
airflow/providers/vertica/operators/vertica.py
takuti/airflow
from flask import request from injector import inject from controllers.common.models.CommonModels import CommonModels from controllers.test.models.TestModels import TestModels from infrastructor.IocManager import IocManager from infrastructor.api.ResourceBase import ResourceBase @TestModels.ns.route('/path/<int:value>/<int:value_for_sum>', doc=False) class TestResource(ResourceBase): @inject def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) @TestModels.ns.marshal_with(CommonModels.SuccessModel) def get(self, value, value_for_sum): result = {'sum': value + value_for_sum} return CommonModels.get_response(result=result) @TestModels.ns.route('/query', doc=False) class TestResource(ResourceBase): @inject def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) @TestModels.ns.expect(TestModels.parser, validate=True) @TestModels.ns.marshal_with(CommonModels.SuccessModel) def get(self): data = TestModels.parser.parse_args(request) value = data.get('value') # value_for_sum = data.get('value_for_sum') # This is FileStorage instance # url = do_something_with_file(uploaded_file) result = {'sum': value + value_for_sum} return CommonModels.get_response(result=result) @TestModels.ns.expect(TestModels.sum_model, validate=True) @TestModels.ns.marshal_with(CommonModels.SuccessModel) def post(self): data = IocManager.api.payload value = data.get('value') # value_for_sum = data.get('value_for_sum') # This is FileStorage instance result = {'sum': value + value_for_sum, "test": [{"test": 1}, {"test": 2}]} return CommonModels.get_response(result=result)
[ { "point_num": 1, "id": "more_functions_than_classes", "question": "Does this file define more functions than classes?", "answer": true }, { "point_num": 2, "id": "every_class_has_docstring", "question": "Does every class in this file have a docstring?", "answer": false }, { ...
3
controllers/test/TestController.py
muhammetbolat/pythondataintegrator
from masonite.provider import ServiceProvider from .Javascript import Javascript class JavascriptProvider(ServiceProvider): """Bind Javascript class into the Service Container.""" wsgi = True def boot(self): pass def register(self): self.app.bind("Javascript", Javascript)
[ { "point_num": 1, "id": "has_nested_function_def", "question": "Does this file contain any function defined inside another function?", "answer": false }, { "point_num": 2, "id": "has_multiple_inheritance", "question": "Does any class in this file use multiple inheritance?", "answ...
3
jsonite/JavascriptProvider.py
ChrisByrd14/JSONite
# coding: utf-8 """ No descripton provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) OpenAPI spec version: 2.1.1+01d50e5 Generated by: https://github.com/swagger-api/swagger-codegen.git 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 absolute_import import os import sys import unittest import graylog from graylog.rest import ApiException from graylog.models.loggers_summary import LoggersSummary class TestLoggersSummary(unittest.TestCase): """ LoggersSummary unit test stubs """ def setUp(self): pass def tearDown(self): pass def testLoggersSummary(self): """ Test LoggersSummary """ model = graylog.models.loggers_summary.LoggersSummary() if __name__ == '__main__': unittest.main()
[ { "point_num": 1, "id": "every_function_under_20_lines", "question": "Is every function in this file shorter than 20 lines?", "answer": true }, { "point_num": 2, "id": "more_functions_than_classes", "question": "Does this file define more functions than classes?", "answer": true ...
3
test/test_loggers_summary.py
yumimobi/graylog.py
import misc_tools import random def create_routing(env, first_step='op1'): tasks = { 'op1': misc_tools.make_assembly_step( env=env, run_time=random.gauss(mu=12, sigma=0.5), route_to='op2'), 'op2': { 'location': env['machine_3'], 'worker': env['technician'], 'manned': False, 'setup_time': random.uniform(a=2, b=5), 'run_time': random.gauss(mu=15, sigma=0.25), 'teardown_time': 0, 'transit_time': 1, 'yield': 0.85, 'route_to_pass': 'op3', 'route_to_fail': 'rework' }, 'op3': { 'location': env['common_process'], 'worker': env['technician'], 'manned': True, 'setup_time': random.triangular(low=1, high=4, mode=2), 'run_time': random.gauss(mu=2, sigma=0.5), 'teardown_time': random.uniform(a=1, b=2), 'transit_time': 1, 'route_to': env['part_c_storage'] }, 'rework': { 'location': env['assembly_bench'], 'worker': env['assembler'], 'manned': True, 'setup_time': 0, 'run_time': random.expovariate(lambd=0.5)*15, 'teardown_time': 0, 'transit_time': 1, 'fail_count': 2, 'route_to_pass': 'op2', 'route_to_fail': env['scrap_storage'] } } return misc_tools.make_steps(first_step=first_step, tasks=tasks) def get_bom(env): return { 'part_a': { 'location': env['part_a_kanban'], 'qty': 1 }, 'part_b': { 'location': env['part_b_kanban'], 'qty': 2 } }
[ { "point_num": 1, "id": "any_function_over_40_lines", "question": "Is any function in this file longer than 40 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 self/c...
3
examples/part_c.py
Viasat/salabim_plus
import uuid from django.db import models from django.urls import reverse from core.models import (Authorable, Titleable, TimeStampedModel) class Recipe(Authorable, Titleable, TimeStampedModel): """ Recipe model as of v.1.0. """ CATEGORY = ( ('WS', 'Western'), ('TB', 'Tibetan'), ('NP', 'Nepalese') ) id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) excerpt = models.TextField(max_length=200, blank=True) content = models.TextField(blank=True) image = models.ImageField(upload_to='', default='default.png', blank=True) image_url = models.CharField(max_length=200, blank=True) def __str__(self): return str(self.title) def get_absolute_url(self): return reverse('dashboard:recipe_detail', args=[str(self.id)])
[ { "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
recipes/models.py
asis2016/momo-ristorante-v1
#!/usr/bin/env python3 import unittest from helper import cheat_output #from textreplacer import TextReplacer # Test locally import sys sys.path.append('../textreplacer/') from textreplacer import TextReplacer class TestMarkCase2(unittest.TestCase): def setUp(self): patterns = [ r"^\d+$", r"^<.*>$", r"^\[YEP" ] self.tr = TextReplacer("test2.txt", "UTF-8", patterns) self.str_lst = self.tr.mark() def test_case2_01_marked_content(self): self.assertEqual(self.str_lst[0], "1") self.assertEqual(self.str_lst[1], "2") self.assertEqual(self.str_lst[2], "[YEP thaths good - hey]") self.assertEqual(self.str_lst[3], "<likehtml>") self.assertEqual(self.str_lst[4], "100") self.assertEqual(self.str_lst[5], "<<<<<<ok too>>>>>>") self.assertEqual(self.str_lst[6], "[YEP this counts too") 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_under_20_lines", "question": "Is every function in this file shorter than 20 lines?", "answer": true ...
3
test/test2.py
ghostduck/text_replacer
"""Tests for the utils module.""" from soco.utils import deprecated # Deprecation decorator def test_deprecation(recwarn): @deprecated("0.7") def dummy(args): """My docs.""" pass @deprecated("0.8", "better_function", "0.12") def dummy2(args): """My docs.""" pass assert dummy.__doc__ == "My docs.\n\n .. deprecated:: 0.7\n" assert ( dummy2.__doc__ == "My docs.\n\n .. deprecated:: 0.8\n\n" " Will be removed in version 0.12.\n" " Use `better_function` instead." ) dummy(3) w = recwarn.pop() assert str(w.message) == "Call to deprecated function dummy." dummy2(4) w = recwarn.pop() assert ( str(w.message) == "Call to deprecated function dummy2. Will be " "removed in version 0.12. Use " "better_function instead." ) assert w.filename assert w.lineno
[ { "point_num": 1, "id": "all_params_annotated", "question": "Does every function parameter in this file have a type annotation (excluding self/cls)?", "answer": false }, { "point_num": 2, "id": "every_function_under_20_lines", "question": "Is every function in this file shorter than ...
3
tests/test_utils.py
relevitt/SoCo
# Importing Django Models: from django.contrib import admin # Importing Database Base Models: from social_media_api.model_views_seralizers.reddit_api.reddit_models import RedditPosts, RedditDevApps, RedditDevAppForm, Subreddits, RedditLogs, RedditPipeline from .models.indeed.indeed_models import IndeedJobPosts from .models.youtube.youtube_models import DailyYoutubeChannelStats "<----------Reddit ETL Admin Models---------->" # Creating an admin form for Reddit Developer Applications: class RedditDevAppAdmin(admin.ModelAdmin): # Custom form for secret key pswrd: form = RedditDevAppForm # Preventing the creation of more than one entry (we only need one Dev App): def has_add_permission(self, request): count = RedditDevApps.objects.all().count() if count == 0: return True return False class RedditPipelineAdmin(admin.ModelAdmin): # Preventing the creation of more than one entity (we only need one Pipeline Object): def has_add_permission(self, request): count = RedditPipeline.objects.all().count() if count == 0: return True return False # Registering the Reddit ETL Models to Admin Dashboard: admin.site.register(Subreddits) admin.site.register(RedditPosts) admin.site.register(RedditDevApps, RedditDevAppAdmin) admin.site.register(RedditPipeline, RedditPipelineAdmin) admin.site.register(RedditLogs) # Registering Indeed Models to Admin Dash: admin.site.register(IndeedJobPosts) # Registering Indeed Models to Admin Dash: admin.site.register(DailyYoutubeChannelStats)
[ { "point_num": 1, "id": "every_function_has_docstring", "question": "Does every function in this file have a docstring?", "answer": false }, { "point_num": 2, "id": "every_class_has_docstring", "question": "Does every class in this file have a docstring?", "answer": false }, ...
3
velkozz_web_api/apps/social_media_api/admin.py
velkoz-data-ingestion/velkozz_web_api
"""Jade Tree Email Support. Jade Tree Personal Budgeting Application | jadetree.io Copyright (c) 2020 Asymworks, LLC. All Rights Reserved. """ from flask import current_app from flask_mail import Mail, Message from jadetree.exc import ConfigError mail = Mail() __all__ = ('init_mail', 'mail', 'send_email') def init_mail(app): """Register the Flask-Mail object with the Application.""" if not app.config.get('MAIL_ENABLED', False): app.logger.debug('Skipping mail setup (disabled)') return required_keys = ( 'MAIL_SERVER', 'MAIL_SENDER', 'SITE_ABUSE_MAILBOX', 'SITE_HELP_MAILBOX' ) for k in required_keys: if k not in app.config: raise ConfigError( '{} must be defined in the application configuration' .format(k), config_key=k ) mail.init_app(app) # Add Site Mailboxes to templates app.jinja_env.globals.update( site_abuse_mailbox=app.config['SITE_ABUSE_MAILBOX'], site_help_mailbox=app.config['SITE_HELP_MAILBOX'], ) # Dump Configuration to Debug app.logger.debug( 'Mail Initialized with server %s and sender %s', app.config['MAIL_SERVER'], app.config['MAIL_SENDER'], ) def send_email(subject, recipients, body, html=None, sender=None): """Send an Email Message using Flask-Mail.""" recip_list = [recipients] if isinstance(recipients, str) else recipients if not current_app.config.get('MAIL_ENABLED', False): current_app.logger.debug( 'Skipping send_email({}) to {} (email disabled)'.format( subject, ', '.join(recip_list) ) ) return if sender is None: sender = current_app.config['MAIL_SENDER'] msg = Message(subject, sender=sender, recipients=recip_list) msg.body = body msg.html = html mail.send(msg)
[ { "point_num": 1, "id": "all_params_annotated", "question": "Does every function parameter in this file have a type annotation (excluding self/cls)?", "answer": false }, { "point_num": 2, "id": "every_function_under_20_lines", "question": "Is every function in this file shorter than ...
3
jadetree/mail.py
asymworks/jadetree-backend
import base64 import cloudpickle import quartic_sdk.utilities.constants as Constants from quartic_sdk.core.entities.base import Base from quartic_sdk.model.helpers import ModelUtils class Model(Base): """ The given class refers to the Model entity which is created based upon the Model object returned from the API """ def __init__(self, body_json, api_helper): super().__init__(body_json, api_helper) self.id = self.model_id def __repr__(self): """ Override the method to return the Model with model name """ return f"<{Constants.MODEL_ENTITY}: {self.model_name}>" def model_instance(self, query_params={}): """ Returns the model object saved in the model :param query_params: Dictionary of filter conditions :return: Returns a Model which is subclass of BaseQuarticModel """ response = self.api_helper.call_api(Constants.CMD_MODEL_ENDPOINT, method_type=Constants.API_GET, path_params=[self.model_id], query_params=query_params, body={}) response.raise_for_status() model_string = response.json()['model'] checksum_received = model_string[:32] decoded_model = base64.b64decode(model_string[32:]) assert ModelUtils.get_checksum(model_string[32:].encode()) == checksum_received return cloudpickle.loads(decoded_model)
[ { "point_num": 1, "id": "every_function_under_20_lines", "question": "Is every function in this file shorter than 20 lines?", "answer": true }, { "point_num": 2, "id": "no_function_exceeds_5_params", "question": "Does every function in this file take 5 or fewer parameters (excluding ...
3
quartic_sdk/core/entities/model.py
divyquartic/QuarticSDK
import re from .exceptions import BrandNotFound from .luhn import Luhn from .utils import sanitize BRAND_REGEX = { "banese": r"^(636117|637473|637470|636659|637472)[0-9]{10,12}$", "elo": r"^(401178|401179|431274|438935|451416|457393|457631|457632|504175|627780|636297|636368|(506699|5067[0-6]\d|50677[0-8])|(50900\d|5090[1-9]\d|509[1-9]\d{2})|65003[1-3]|(65003[5-9]|65004\d|65005[0-1])|(65040[5-9]|6504[1-3]\d)|(65048[5-9]|65049\d|6505[0-2]\d|65053[0-8])|(65054[1-9]|6505[5-8]\d|65059[0-8])|(65070\d|65071[0-8])|65072[0-7]|(65090[1-9]|65091\d|650920)|(65165[2-9]|6516[6-7]\d)|(65500\d|65501\d)|(65502[1-9]|6550[3-4]\d|65505[0-8]))[0-9]{10,12}$", # noqa: E501 "diners": r"^3(?:0[0-5]|[68][0-9])[0-9]{11}$", "discover": r"^6(?:011|5[0-9]{2}|4[4-9][0-9]{1}|(22(12[6-9]|1[3-9][0-9]|[2-8][0-9]{2}|9[01][0-9]|92[0-5]$)[0-9]{10}$))[0-9]{12}$", # noqa: E501 "hipercard": r"^(38[0-9]{17}|60[0-9]{14})$", "amex": r"^3[47][0-9]{13}$", "aura": r"^50[0-9]{14,17}$", "mastercard": r"^(5[1-5][0-9]{14}|2221[0-9]{12}|222[2-9][0-9]{12}|22[3-9][0-9]{13}|2[3-6][0-9]{14}|27[01][0-9]{13}|2720[0-9]{12})$", # noqa: E501 "visa": r"^4[0-9]{12}(?:[0-9]{3})?$", } class CreditCard: def __init__(self, number): self.number = sanitize(number) def is_valid(self): return all([len(self.number) in range(13, 19), Luhn.checkdigit(self.number)]) def get_brand(self): for brand, regex in BRAND_REGEX.items(): if re.match(regex, self.number): return brand raise BrandNotFound("Card number does not match any brand")
[ { "point_num": 1, "id": "more_functions_than_classes", "question": "Does this file define more functions than classes?", "answer": true }, { "point_num": 2, "id": "has_multiple_inheritance", "question": "Does any class in this file use multiple inheritance?", "answer": false },...
3
creditcard/card.py
guilhermetavares/python-creditcard
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Introduction à WxPython Illustration de l'interaction entre la manipulation des objets à l'écran et les fonctionnalités du programme. """ import wx class InteractionFrame(wx.Frame): def __init__(self, title, size): super().__init__(None, title=title, size=size) self.panel = wx.Panel(self, size=self.GetClientSize()) choices = ["white", "red", "green", "blue", "yellow"] choose = wx.Choice(self.panel, choices=choices) choose.SetSelection(0) choose.Bind(wx.EVT_CHOICE, self.changeBackColour) choose.Center() def changeBackColour(self, evt): self.panel.SetBackgroundColour(evt.GetString()) class InteractionApp(wx.App): def OnInit(self): frame = InteractionFrame(title='Interaction', size=(250, 200)) frame.Show() return True if __name__ == '__main__': app = InteractionApp() app.MainLoop()
[ { "point_num": 1, "id": "all_params_annotated", "question": "Does every function parameter in this file have a type annotation (excluding self/cls)?", "answer": false }, { "point_num": 2, "id": "every_function_under_20_lines", "question": "Is every function in this file shorter than ...
3
Scripts/009_wxpyhon/script/002_interaction.py
OrangePeelFX/Python-Tutorial
class OverpassError(Exception): """An error during your request occurred. Super class for all Overpass api errors.""" pass class OverpassSyntaxError(OverpassError, ValueError): """The request contains a syntax error.""" def __init__(self, request): self.request = request class TimeoutError(OverpassError): """A request timeout occurred.""" def __init__(self, timeout): self.timeout = timeout class MultipleRequestsError(OverpassError): """You are trying to run multiple requests at the same time.""" pass class ServerLoadError(OverpassError): """The Overpass server is currently under load and declined the request. Try again later or retry with reduced timeout value.""" def __init__(self, timeout): self.timeout = timeout class UnknownOverpassError(OverpassError): """An unknown kind of error happened during the request.""" def __init__(self, message): self.message = message class ServerRuntimeError(OverpassError): """The Overpass server returned a runtime error""" def __init__(self, message): self.message = message
[ { "point_num": 1, "id": "more_functions_than_classes", "question": "Does this file define more functions than classes?", "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
overpass/errors.py
itiboi/overpass-api-python-wrapper
#appModules/totalcmd.py #A part of NonVisual Desktop Access (NVDA) #Copyright (C) 2006-2012 NVDA Contributors #This file is covered by the GNU General Public License. #See the file COPYING for more details. import appModuleHandler from NVDAObjects.IAccessible import IAccessible import speech import controlTypes import ui oldActivePannel=0 class AppModule(appModuleHandler.AppModule): def chooseNVDAObjectOverlayClasses(self, obj, clsList): if obj.windowClassName in ("TMyListBox", "TMyListBox.UnicodeClass"): clsList.insert(0, TCList) class TCList(IAccessible): def event_gainFocus(self): global oldActivePannel if oldActivePannel !=self.windowControlID: oldActivePannel=self.windowControlID obj=self while obj and obj.parent and obj.parent.windowClassName!="TTOTAL_CMD": obj=obj.parent counter=0 while obj and obj.previous and obj.windowClassName!="TPanel": obj=obj.previous if obj.windowClassName!="TDrivePanel": counter+=1 if counter==2: ui.message(_("left")) else: ui.message(_("right")) super(TCList,self).event_gainFocus() def reportFocus(self): if self.name: speakList=[] if controlTypes.State.SELECTED in self.states: speakList.append(controlTypes.State.SELECTED.displayString) speakList.append(self.name.split("\\")[-1]) speech.speakMessage(" ".join(speakList)) else: super(TCList,self).reportFocus()
[ { "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
source/appModules/totalcmd.py
oleguldberg/nvda
import unittest import checksieve class TestIndex(unittest.TestCase): def test_index(self): sieve = ''' # Implement the Internet-Draft cutoff date check assuming the # second Received: field specifies when the message first # entered the local email infrastructure. require ["date", "relational", "index"]; if date :value "gt" :index 2 :zone "-0500" "received" "iso8601" "2007-02-26T09:00:00-05:00" { redirect "aftercutoff@example.org"; } ''' self.assertFalse(checksieve.parse_string(sieve, False)) def test_index_no_require(self): sieve = ''' # Implement the Internet-Draft cutoff date check assuming the # second Received: field specifies when the message first # entered the local email infrastructure. require ["date", "relational"]; if date :value "gt" :index 2 :zone "-0500" "received" "iso8601" "2007-02-26T09:00:00-05:00" { redirect "aftercutoff@example.org"; } ''' self.assertTrue(checksieve.parse_string(sieve, True)) 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_under_20_lines", "question": "Is every function in this file shorter than 20 lines?", ...
3
test/5260/index_test.py
dburkart/check-sieve
import os import pytest from etcetra import EtcdClient, HostPortPair @pytest.fixture def etcd_addr(): env_addr = os.environ.get('BACKEND_ETCD_ADDR') if env_addr is not None: return HostPortPair.parse(env_addr) return HostPortPair.parse('localhost:2379') @pytest.fixture async def etcd(etcd_addr): etcd = EtcdClient(etcd_addr) try: yield etcd finally: async with etcd.connect() as communicator: await communicator.delete_prefix('/test') del etcd
[ { "point_num": 1, "id": "every_function_under_20_lines", "question": "Is every function in this file shorter than 20 lines?", "answer": true }, { "point_num": 2, "id": "every_function_has_docstring", "question": "Does every function in this file have a docstring?", "answer": fals...
3
tests/conftest.py
lablup/etcetra
"""Removed request_uri for slots and repeating slots Revision ID: 449c8b35b869 Revises: 1b81c4cf5a5a Create Date: 2014-03-22 15:50:29.543673 """ # revision identifiers, used by Alembic. revision = '449c8b35b869' down_revision = '1b81c4cf5a5a' from alembic import op import sqlalchemy as sa def upgrade(): op.drop_column("slots", "request_uri") op.drop_column("repeating_slots", "request_uri") def downgrade(): raise NotImplementedError('This application does not support downgrades.')
[ { "point_num": 1, "id": "every_function_has_docstring", "question": "Does every function in this file have a docstring?", "answer": false }, { "point_num": 2, "id": "all_return_types_annotated", "question": "Does every function in this file have a return type annotation?", "answe...
3
flod_booking/alembic/versions/20140322-1550-449c8b35b869_removed_request_uri_for_slots_and_.py
Trondheim-kommune/Bookingbasen
from virgo.parse import parse def test_parse_simple_edge(): s = "a -> b" result = parse(s) assert result is not None assert "a" in result.nodes assert list(result.direct_successors_of("a")) == ["b"] assert list(result.direct_successors_of("b")) == [] def test_parse_simple_edge_with_newline(): s = "a -> b\n" result = parse(s) assert result is not None def test_parse_simple_node_description(): s = "parser = `goyacc parser.y`" result = parse(s) assert result is not None assert "parser" in result.nodes assert result.nodes["parser"] == "goyacc parser.y" def test_parse_simple_node_description_with_blank_line(): s = "\nparser = `goyacc parser.y`" result = parse(s) assert result is not None assert "parser" in result.nodes assert result.nodes["parser"] == "goyacc parser.y" def test_parse_simple_node_description_with_blank_lines(): s = "\n\nparser = `goyacc parser.y`" result = parse(s) assert result is not None assert "parser" in result.nodes assert result.nodes["parser"] == "goyacc parser.y" def test_parse_simple_node_description_with_line_continuation(): s = "\n\nparser = |\n`goyacc parser.y`" result = parse(s) assert result is not None assert "parser" in result.nodes assert result.nodes["parser"] == "goyacc parser.y" def test_parse_simple_node_description_with_line_continuation_in_desc(): s = "\n\nparser = `goyacc |\nparser.y`" result = parse(s) assert result is not None assert "parser" in result.nodes assert result.nodes["parser"] == "goyacc parser.y"
[ { "point_num": 1, "id": "has_nested_function_def", "question": "Does this file contain any function defined inside another function?", "answer": false }, { "point_num": 2, "id": "every_function_under_20_lines", "question": "Is every function in this file shorter than 20 lines?", ...
3
test/test_parse.py
terrykong/pyvirgo
import json import re import spacy import enchant import copy as cp sp = spacy.load('en_core_web_sm') def lemmatize_this(str_word): return sp(str_word)[0] def main(): while True: print("Ingrese la Palabra: ") word = input() word = str(lemmatize_this(word)) try: with open("../Datos/06_words_fixed/stg0/" + word + ".json", "r") as answerJson: wordDic = json.load(answerJson) elems = [[k, v] for k, v in wordDic.items()] elems.sort(key = lambda x: x[1]) rank = len(elems) for i in elems: print(rank, i) rank -=1 except: print("Palabra no encontrada") if __name__ == "__main__": main()
[ { "point_num": 1, "id": "every_function_has_docstring", "question": "Does every function in this file have a docstring?", "answer": false }, { "point_num": 2, "id": "every_function_under_20_lines", "question": "Is every function in this file shorter than 20 lines?", "answer": tru...
3
Demos/Distancias_ocurrencias.py
TheReverseWasp/TBD_TF-IDF_with_Google_Corpus
from twisted.internet.protocol import Protocol from gandyloo import parse class MinesweeperClient(Protocol): '''Represents a connection to a server using twisted's Protocol framework. Created with an event sink, where parsed events (subclasses of gandyloo.message.Response) are fired. Sink should have a method self.response(resp). ''' def __init__(self, event_sink): self.buffer = "" self.hello_received = False self.size = None self.event_sink = event_sink def dataReceived(self, data): self.buffer += data if not self.hello_received: try: resp, self.buffer = parse.parse_start(self.buffer, first=True) except parse.NotReadyError: return # Haven't received enough data yet self.hello_received = True self.size = resp.size self.event_sink.response(resp) try: while True: resp, self.buffer = parse.parse_start(self.buffer, self.size) self.event_sink.response(resp) except parse.NotReadyError: return def command(self, command): self.transport.write(command.render()) def clientConnectionLost(self, connection, reason): self.event_sink.response(message.CloseResp(reason))
[ { "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
gandyloo/connection.py
kazimuth/gandyloo
from django.test import TestCase from task.models import Task, Tag from task.serializers import TaskSerializer from django.conf import settings class TestFullImageUrl(TestCase): def setUp(self) -> None: self.path = '/media/image.png' self.task = Task.objects.create(name='demo', image='/image.png') self.tag = Tag.objects.create(task=self.task, name='demo', image='/image.png') def test_default_image_path(self): result = TaskSerializer(self.task).data path = get_path() + self.path self.assertEqual(result['image'], path) def test_https(self): settings.AIR_DRF_RELATION['USE_SSL'] = True result = TaskSerializer(self.task).data path = get_path() + self.path self.assertEqual(result['image'], path) def test_custom_host(self): settings.AIR_DRF_RELATION['HTTP_HOST'] = 'demo.com' path = get_path() + self.path result = TaskSerializer(self.task).data self.assertEqual(result['image'], path) def test_many_serializer(self): data = TaskSerializer([self.task], many=True).data pass def get_path(): current_settings = settings.AIR_DRF_RELATION host = current_settings.get('HTTP_HOST') use_ssl = current_settings.get('USE_SSL') return f'{"https" if use_ssl else "http"}://{host}'
[ { "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
task/tests.py
bubaley/air-drf-relation
from django import template from django_gravatar.templatetags.gravatar import gravatar_url # Get template.Library instance register = template.Library() # enables the use of the gravatar_url as an assignment tag register.assignment_tag(gravatar_url) @register.simple_tag(takes_context=True) def display_name(context): user = context['user'] full_name = ' '.join([user.first_name, user.last_name]).strip() return full_name if full_name else user.username @register.filter def multiply(value, factor): try: return value * factor except: # noqa pass # noqa return 0
[ { "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
mc2/templatetags/mc2_tags.py
praekeltfoundation/mc2
''' Problem Statement Write a function that takes in a non-empty array of distinct integers and an integer representing a target sum. If any two numbers in the input array sum up to the target sum, the function should return them in an array, in sorted order. If no two numbers sum up to the target sum, the function should return an empty array. Assume that there will be at most one pair of numbers summing up to the target sum. Sample input: [3, 5, -4, 8, 11, 1, -1, 6], 10 Sample output: [-1, 11] ''' def twoNumberSum( array, target_sum ): hash_nums = {} for num in array: potentialmatch = target_sum - num if potentialmatch in hash_nums: return [ potentialmatch, num ] else: hash_nums[num] = True return [] def twoNumberSum2( array, target_sum ): array.sort() left = 0 right = len( array ) - 1 while left < right: current_sum = array[left] + array[right] if current_sum == target_sum: return [ array[left], array[right] ] elif current_sum < target_sum: left = left + 1 elif current_sum > target_sum: right = right - 1 return None print( twoNumberSum([3, 5, -4, 8, 11, 1, -1, 6], 10 )) print( twoNumberSum2( [3, 5, -4, 8, 11, 1, -1, 6], 10 ))
[ { "point_num": 1, "id": "no_function_exceeds_5_params", "question": "Does every function in this file take 5 or fewer parameters (excluding self/cls)?", "answer": true }, { "point_num": 2, "id": "has_nested_function_def", "question": "Does this file contain any function defined insid...
3
codes/01_two_sum.py
harshavl/Brain-Teaser-with-Coding
import abc import typing_extensions as te import dataclasses from databind.core.annotations import fieldinfo, union from databind.json import loads @dataclasses.dataclass class Person: name: str age: te.Annotated[int, fieldinfo(strict=False)] @union() class Plugin(abc.ABC): pass @union.subtype(Plugin) @dataclasses.dataclass class PluginA(Plugin): pass @union.subtype(Plugin, name = 'plugin-b') @dataclasses.dataclass class PluginB(Plugin): value: str def test_loads(): assert loads('42', int) == 42 assert loads('{"name": "John", "age": 20}', Person) == Person('John', 20) assert loads('{"name": "John", "age": "20"}', Person) == Person('John', 20) # Allowed because of fieldinfo(strict=False) assert loads('{"type": "PluginA", "PluginA": {}}', Plugin) == PluginA() assert loads('{"type": "PluginA"}', Plugin, annotations=[union(style=union.Style.flat)]) == PluginA() assert loads('{"type": "plugin-b", "plugin-b": {"value": "foobar"}}', Plugin) == PluginB("foobar") assert loads('{"type": "plugin-b", "value": "foobar"}', Plugin, annotations=[union(style=union.Style.flat)]) == PluginB("foobar")
[ { "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
databind.json/src/test/test_init.py
NiklasRosenstein/databind
from tkinter.filedialog import askopenfilename from tkinter import * import cli import gettext window = Tk() window.title("ofx_to_xlsx") def close_window(): window.destroy() def callback(): ofx = askopenfilename() cli.run(ofx) gettext.install('ofx_to_xlsx') t = gettext.translation('gui_i18n', 'locale', fallback=True) _ = t.gettext frame = Frame(window) frame.pack() w1 = Label (frame,text = _("Select a OFX file to convert it to Excel")) w1.pack() arq = Button (frame, text = _("Select File"), command = callback) arq.pack() sair = Button (frame, text = _("Quit"), command = close_window) sair.pack() window.mainloop() exit()
[ { "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
gui.py
eduardokimmel/ofx_to_xlsx
from time import sleep import os import docker import pytest from docker.types import EndpointSpec, NetworkAttachmentConfig import vault @pytest.fixture(scope="session") def root_path(): yield os.path.dirname(os.path.dirname(__file__)) @pytest.fixture() def vault_service(vault_token): client = docker.from_env() network = client.networks.create(name=f"vault_default", scope="swarm", driver="overlay", attachable=True) vault_ = client.services.create( image="vault:1.4.1", command=["vault", "server", "--dev"], name="vault", env=[f"VAULT_DEV_ROOT_TOKEN_ID={vault_token}", f"VAULT_DEV_LISTEN_ADDRESS=0.0.0.0:8200"], endpoint_spec=EndpointSpec(ports={8200: 8200}), networks=[NetworkAttachmentConfig(target=network.id)] ) while vault_.tasks()[0].get("Status").get("State") != "running": sleep(1) yield vault_ vault_.remove() network.remove() @pytest.fixture() def vault_url(): yield "http://0.0.0.0:8200" @pytest.fixture() def vault_token(): token = "token" os.environ["VAULT_TOKEN"] = token yield token @pytest.fixture() def vault_client(vault_service, vault_url, vault_token): yield vault.get_connection(vault_url)
[ { "point_num": 1, "id": "all_function_names_snake_case", "question": "Are all function names in this file written in snake_case?", "answer": true }, { "point_num": 2, "id": "every_function_under_20_lines", "question": "Is every function in this file shorter than 20 lines?", "answ...
3
tests/conftest.py
procedural-build/vault-swarm
import re def test_phones_on_home_page(app): contact_from_home_page = app.contact.get_contact_list()[0] contact_from_edit_page = app.contact.get_contact_info_from_edit_page(0) assert contact_from_home_page.all_phones_from_home_page == merge_phones_like_on_home_page(contact_from_edit_page) def test_phones_on_contact_view_page(app): contact_from_view_page = app.contact.get_contact__from_view_page(0) contact_from_edit_page = app.contact.get_contact_info_from_edit_page(0) assert contact_from_view_page.homephone == contact_from_edit_page.homephone assert contact_from_view_page.mobilephone == contact_from_edit_page.mobilephone assert contact_from_view_page.workphone == contact_from_edit_page.workphone assert contact_from_view_page.secondaryphone == contact_from_edit_page.secondaryphone def clear(s): return re.sub("[() -]", "", s) def merge_phones_like_on_home_page(contact): return "\n".join(filter(lambda x: x != "", map(lambda x: clear(x), filter(lambda x: x is not None, [contact.homephone, contact.mobilephone, contact.workphone, contact.secondaryphone]))))
[ { "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
test/test_phones.py
bopopescu/python_traning
# -*- coding: utf-8 -*- """ Encapsulate the different transports available to Salt. """ # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import logging # Import Salt libs import salt.utils.versions # Import third party libs from salt.ext import six from salt.ext.six.moves import range log = logging.getLogger(__name__) def iter_transport_opts(opts): """ Yield transport, opts for all master configured transports """ transports = set() for transport, opts_overrides in six.iteritems(opts.get("transport_opts", {})): t_opts = dict(opts) t_opts.update(opts_overrides) t_opts["transport"] = transport transports.add(transport) yield transport, t_opts if opts["transport"] not in transports: yield opts["transport"], opts class MessageClientPool(object): def __init__(self, tgt, opts, args=None, kwargs=None): sock_pool_size = opts["sock_pool_size"] if "sock_pool_size" in opts else 1 if sock_pool_size < 1: log.warning( "sock_pool_size is not correctly set, the option should be " "greater than 0 but is instead %s", sock_pool_size, ) sock_pool_size = 1 if args is None: args = () if kwargs is None: kwargs = {} self.message_clients = [tgt(*args, **kwargs) for _ in range(sock_pool_size)]
[ { "point_num": 1, "id": "more_functions_than_classes", "question": "Does this file define more functions than classes?", "answer": true }, { "point_num": 2, "id": "no_function_exceeds_5_params", "question": "Does every function in this file take 5 or fewer parameters (excluding self/...
3
salt/transport/__init__.py
MeAndTheFirefly/salt
import numpy as np import tensorflow as tf from MLib.Core.layers import LinearLayer, ConvLayer from tensorflow.keras.layers import MaxPooling2D, Flatten from tensorflow.keras import Model class SimpleCNNModel(Model): def __init__(self, num_units): super(SimpleCNNModel, self).__init__() # Define the architecture of the network self.conv1 = ConvLayer(size=[3,3], num_filters=32, gate=tf.nn.relu) self.pool1 = MaxPooling2D(pool_size=[2,2]) self.conv2 = ConvLayer(size=[3,3], num_filters=128, gate=tf.nn.relu) self.pool2 = MaxPooling2D(pool_size=[2,2]) self.conv3 = ConvLayer(size=[3,3], num_filters=256, gate=tf.nn.relu) self.pool3 = MaxPooling2D(pool_size=[2,2]) self.conv4 = ConvLayer(size=[3,3], num_filters=512, gate=tf.nn.relu) self.pool4 = MaxPooling2D(pool_size=[2,2]) self.flat = Flatten() self.hidden = LinearLayer(units=num_units) self.final = LinearLayer(units=10) def call(self, inputs): # First conv-pooling layer x = self.conv1(inputs) x = self.pool1(x) # Second conv-pooling layer x = self.conv2(x) x = self.pool2(x) # Third conv-pooling layer x = self.conv3(x) x = self.pool3(x) # Fourth conv-pooling layer x = self.conv4(x) x = self.pool4(x) # Flatten the array x = self.flat(x) # First fully connected layer z = self.hidden(x) z = tf.nn.relu(z) # Prediction layer x = self.final(z) x = tf.nn.softmax(x) return z, x def main(): return -1 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": "has_multiple_inheritance", "question": "Does any class in this file use multiple inheritance?", "answer": false },...
3
MLib/Models/KerasModels.py
rvegaml/DA_Linear
import keyboard from player_detector import PlayerDetector from drops_detector import DropsDetector from snapshoter import Snapshoter PIC_INTERVAL_SEC = 0.1 PICKUP_BUTTON = 'z' class DropsSnapshoter(Snapshoter): def __init__(self, pipe_connection): super().__init__(pipe_connection, PIC_INTERVAL_SEC) self.drops_detector = DropsDetector(PlayerDetector()) def apply_request_from_pipe(self, split_request): # no need for any other requests here pass def do_each_round(self, pil_img): if self.drops_detector.is_drop_nearby(pil_img): keyboard.press_and_release(PICKUP_BUTTON)
[ { "point_num": 1, "id": "all_function_names_snake_case", "question": "Are all function names in this file written in snake_case?", "answer": true }, { "point_num": 2, "id": "more_functions_than_classes", "question": "Does this file define more functions than classes?", "answer": ...
3
drops_snapshoter.py
TomerMe2/MapleStory-Auto-Pots
#!/usr/bin/env python import os import subprocess import sys from dbusmock import DBusTestCase from lib.config import is_verbose_mode def stop(): DBusTestCase.stop_dbus(DBusTestCase.system_bus_pid) DBusTestCase.stop_dbus(DBusTestCase.session_bus_pid) def start(): log = sys.stdout if is_verbose_mode() else open(os.devnull, 'w') DBusTestCase.start_system_bus() DBusTestCase.spawn_server_template('logind', None, log) DBusTestCase.start_session_bus() DBusTestCase.spawn_server_template('notification_daemon', None, log) if __name__ == '__main__': start() try: subprocess.check_call(sys.argv[1:]) finally: stop()
[ { "point_num": 1, "id": "every_function_has_docstring", "question": "Does every function in this file have a docstring?", "answer": false }, { "point_num": 2, "id": "has_nested_function_def", "question": "Does this file contain any function defined inside another function?", "ans...
3
script/dbus_mock.py
lingxiao-Zhu/electron
# coding: utf-8 """ Kubernetes No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) OpenAPI spec version: v1.13.4 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.apis.auditregistration_api import AuditregistrationApi class TestAuditregistrationApi(unittest.TestCase): """ AuditregistrationApi unit test stubs """ def setUp(self): self.api = kubernetes.client.apis.auditregistration_api.AuditregistrationApi() def tearDown(self): pass def test_get_api_group(self): """ Test case for get_api_group """ pass if __name__ == '__main__': unittest.main()
[ { "point_num": 1, "id": "every_function_under_20_lines", "question": "Is every function in this file shorter than 20 lines?", "answer": true }, { "point_num": 2, "id": "all_function_names_snake_case", "question": "Are all function names in this file written in snake_case?", "answ...
3
kubernetes/test/test_auditregistration_api.py
iamneha/python
import sys import time import forward_messages import helpers try: import config except (ImportError, ModuleNotFoundError): print( "config.py not found. Rename config.example.py to config.py after configuration." ) sys.exit(1) def main(): if config.forward_user: forward_messages.forward(config.forward_user) reddit = helpers.initialize_reddit() participated = set(helpers.load_data("participated")) stats = helpers.load_data("stats") participated = participated.union(get_participants(reddit, stats["last_daily_run"])) helpers.write_data("participated", list(participated)) stats["last_daily_run"] = ( time.time() - 60 ) # to cover accidental gaps due to execution time helpers.write_data("stats", stats) def get_participants(reddit, last_check): participated = set() old_comments = False old_submissions = False for submission in reddit.subreddit(config.target_subreddit).new(limit=None): if submission.created_utc < last_check: old_submissions = True break try: participated.add(submission.author.name) except AttributeError: # More than likely a deleted user pass for comment in reddit.subreddit(config.target_subreddit).comments(limit=None): if comment.created_utc < last_check: old_comments = True break try: participated.add(comment.author.name) except AttributeError: # More than likely a deleted user pass if ( not old_comments or not old_submissions ) and "--ignore-old-comments-warning" not in sys.argv: raise Exception( "Not all old comments were retrieved. Run again with --ignore-old-comments-warning to " "suppress." ) return participated if __name__ == "__main__": main()
[ { "point_num": 1, "id": "every_function_has_docstring", "question": "Does every function in this file have a docstring?", "answer": false }, { "point_num": 2, "id": "has_nested_function_def", "question": "Does this file contain any function defined inside another function?", "ans...
3
daily.py
jarhill0/PrivateSubBot
import numpy as np def get_strehl_from_focal(img, ref_img): '''Get the Strehl ratio from a focal-plane image. Parameters ---------- img : Field or array_like The focal-plane image. ref_img : Field or array_like The reference focal-plane image without aberrations. Returns ------- scalar The Strehl ratio. ''' return img(np.argmax(ref_img)) / ref_img.max() def get_strehl_from_pupil(aperture, ref_aperture): '''Get the Strehl ratio from a pupil-plane electric field. Parameters ---------- aperture : Field or array_like The pupil-plane electric field. ref_aperture : Field or array_like The reference pupil-plane electric field without aberrations. Returns ------- scalar The Strehl ratio. ''' return np.abs(np.sum(aperture) / np.sum(ref_aperture))**2 def get_mean_intensity_in_roi(img, mask): '''Get the mean intensity in a masked region of interest. Parameters ---------- img : Field or array_like The focal-plane image. mask : Field or array_like A binary array describing the region of interest. Returns ------- scalar The mean intensity in the region of interest. ''' return np.mean(img[mask]) def get_mean_raw_contrast(img, mask, ref_img): '''Get the mean raw contrast in a masked region of interest. Parameters ---------- img : Field or array_like The focal-plane image. mask : Field or array_like A binary array describing the region of interest. img_ref : Field or array_like A reference focal-plane image without aberrations. This is used to determine the Strehl ratio. Returns ------- scalar The mean raw contrast in the region of interest. ''' mean_intensity = get_mean_intensity_in_roi(img, mask) strehl = get_strehl_from_focal(img, ref_img) return mean_intensity / strehl
[ { "point_num": 1, "id": "all_params_annotated", "question": "Does every function parameter in this file have a type annotation (excluding self/cls)?", "answer": false }, { "point_num": 2, "id": "every_function_under_20_lines", "question": "Is every function in this file shorter than ...
3
hcipy/metrics/contrast.py
yinzi-xin/hcipy
class MultipartProblem: """A container for multiple related Problems grouped together in one question. If q1 is a MPP, its subquestions are accessed as q1.a, q1.b, etc. """ def __init__(self, *probs): self.problems = probs # TODO: This should be ordered. self._prob_map = {} def _repr_markdown_(self): return repr(self) def __repr__(self): varname = self._varname part_names = ['`{}.{}`'.format(varname, letter) for letter in self._prob_map] return """This question is in {} parts. Those parts can be accessed as {}. For example, to get a hint about part a, you would type `{}.a.hint()`.""".format( len(self._prob_map), ', '.join(part_names), varname )
[ { "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
learntools/core/multiproblem.py
bkmalayC/learntools
def draw_mem(): c_width = int( w.Canvas2.cget( "width" )) c_height = int( w.Canvas2.cget( "height" )) print( c_width ) box_start = c_width * 0.05 box_end = c_width * 0.95 mem_title = w.Canvas2.create_text(( c_width / 2 ), 10, fill = "black", font = "Times 10", text = "Flash" ) mem1 = w.Canvas2.create_rectangle( box_start, ( c_height * 0.1 ), box_end, ( c_height * 0.2 ), fill="blue" ) def resize(): c_width = int( w.Canvas2.cget( "width" )) c_height = int( w.Canvas2.cget( "height" )) w.Canvas2.coords( mem1, ( c_width * 0.05 ), ( c_height * 0.1 ), ( c_width * 0.95 ), ( c_height * 0.2 )) c_width = int( w.Canvas2.cget( "width" )) c_height = int( w.Canvas2.cget( "height" )) print( c_width ) box_start = c_width * 0.05 box_end = c_width * 0.95 mem_title = w.Canvas2.create_text(( c_width / 2 ), 10, fill = "black", font = "Times 10", text = "Flash" ) mem1 = w.Canvas2.create_rectangle( box_start, ( c_height * 0.1 ), box_end, ( c_height * 0.2 ), fill="blue" )
[ { "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
Tools/GUI/BlueOS_support_functions.py
speedbug78/BlueOS
from __future__ import unicode_literals from django.core.exceptions import ImproperlyConfigured from waffle.utils import get_setting from django.apps import apps as django_apps VERSION = (0, 13, 0) __version__ = '.'.join(map(str, VERSION)) def flag_is_active(request, flag_name): flag = get_waffle_flag_model().get(flag_name) return flag.is_active(request) def switch_is_active(switch_name): from .models import Switch switch = Switch.get(switch_name) return switch.is_active() def sample_is_active(sample_name): from .models import Sample sample = Sample.get(sample_name) return sample.is_active() def get_waffle_flag_model(): """ Returns the waffle Flag model that is active in this project. """ # Add backwards compatibility by not requiring adding of WAFFLE_FLAG_MODEL # for everyone who upgrades. # At some point it would be helpful to require this to be defined explicitly, # but no for now, to remove pain form upgrading. flag_model_name = get_setting('FLAG_MODEL', 'waffle.Flag') try: return django_apps.get_model(flag_model_name) except ValueError: raise ImproperlyConfigured("WAFFLE_FLAG_MODEL must be of the form 'app_label.model_name'") except LookupError: raise ImproperlyConfigured( "WAFFLE_FLAG_MODEL refers to model '{}' that has not been installed".format( flag_model_name ) )
[ { "point_num": 1, "id": "all_params_annotated", "question": "Does every function parameter in this file have a type annotation (excluding self/cls)?", "answer": false }, { "point_num": 2, "id": "every_function_under_20_lines", "question": "Is every function in this file shorter than ...
3
waffle/__init__.py
PetterS/django-waffle
import assembly_x86 import assembly_arm import assembly_mips import assembly_ppc import os class AsmFactory: def get_type(self, asm_type, input_path, b_online=False, i_list=[]): if asm_type == 'X86': return assembly_x86.X86Asm(input_path, b_online, i_list) elif asm_type == 'ARM': return assembly_arm.ArmAsm(input_path, b_online, i_list) elif asm_type == 'PPC': return assembly_ppc.PPCAsm(input_path, b_online, i_list) elif asm_type == 'MIPS': return assembly_mips.MipsAsm(input_path, b_online, i_list) else: return def generate_batch_ir(dir_path): file_list = os.listdir(dir_path) path_list = [os.path.join(dir_path, file_name) for file_name in file_list if os.path.isfile(os.path.join(dir_path, file_name))] asm_factory = AsmFactory() for file_path in path_list: print(file_path) if os.path.getsize(file_path) > 0: # asm_factory.get_type('ARM', file_path).translate() asm_factory.get_type('PPC', file_path).translate() else: print('rm') os.remove(file_path) if __name__ == '__main__': # input_list = ['sub esp, 0Ch\n', 'push [esp+148h+s]; s\n', 'call dtls1_max_handshake_message_len\n', 'add esp, 10h\n', 'cmp eax, [esp+13Ch+frag_len]\n', 'jb loc_80CD5DB\n', 'nop\n', 'jmp short err\n'] # asm_factory = AsmFactory() # print(asm_factory.get_type('X86', None, True, input_list).translate()) # asm_factory = AsmFactory() # asm_factory.get_type('X86', './openssl-1.0.1a-O0-g.asm').translate() # generate_batch_ir('../output-binutils') generate_batch_ir('/home/ubuntu/output')
[ { "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
preprocess_assembly.py
LN-Curiosity/PMatch
# GENERATED BY KOMAND SDK - DO NOT EDIT import komand import json class Component: DESCRIPTION = "Update value by key" class Input: ARRAY = "array" KEY = "key" OBJECT = "object" VALUE = "value" class Output: JSON = "json" class UpdateInput(komand.Input): schema = json.loads(""" { "type": "object", "title": "Variables", "properties": { "array": { "type": "array", "title": "Array", "description": "Array of JSON objects", "items": { "type": "object" }, "order": 2 }, "key": { "type": "string", "title": "Key", "description": "JSON key to update", "order": 3 }, "object": { "type": "object", "title": "Object", "description": "JSON object", "order": 1 }, "value": { "type": "string", "title": "Value", "description": "New value", "order": 4 } }, "required": [ "key", "value" ] } """) def __init__(self): super(self.__class__, self).__init__(self.schema) class UpdateOutput(komand.Output): schema = json.loads(""" { "type": "object", "title": "Variables", "properties": { "json": { "type": "array", "title": "JSON", "description": "Array of objects", "items": { "type": "object" }, "order": 1 } }, "required": [ "json" ] } """) def __init__(self): super(self.__class__, self).__init__(self.schema)
[ { "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
plugins/json_edit/komand_json_edit/actions/update/schema.py
lukaszlaszuk/insightconnect-plugins
import theano.tensor as T import numpy as np import theano from theano import shared class sgd(object): """ Stochastic Gradient Descent (SGD) Generates update expressions of the form: param := param - learning_rate * gradient """ def __init__(self, params, masks=None): self.masks = masks def updates(self, params, grads, learning_rate): """ Parameters ---------- params : list of shared variables The variables to generate update expressions for learning_rate : float or symbolic scalar The learning rate controlling the size of update steps Returns ------- list(tuple) A tuple mapping each parameter to its update expression """ updates = [] for param, grad, mask in zip(params, grads, self.masks): update = - (learning_rate * grad) select = np.arange(len(mask.eval()))[mask.eval()] # compute parameter update, using the 'old' delta_accu updates.append(( param, T.inc_subtensor(param[select], update[select]) )) return updates
[ { "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
models/optimizers/sgd.py
mwong009/iclv_rbm
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Generated from FHIR 3.0.0.11832 on 2017-03-22. # 2017, SMART Health IT. import os import io import unittest import json from . import servicedefinition from .fhirdate import FHIRDate class ServiceDefinitionTests(unittest.TestCase): def instantiate_from(self, filename): datadir = os.environ.get('FHIR_UNITTEST_DATADIR') or '' with io.open(os.path.join(datadir, filename), 'r', encoding='utf-8') as handle: js = json.load(handle) self.assertEqual("ServiceDefinition", js["resourceType"]) return servicedefinition.ServiceDefinition(js) def testServiceDefinition1(self): inst = self.instantiate_from("servicedefinition-example.json") self.assertIsNotNone(inst, "Must have instantiated a ServiceDefinition instance") self.implServiceDefinition1(inst) js = inst.as_json() self.assertEqual("ServiceDefinition", js["resourceType"]) inst2 = servicedefinition.ServiceDefinition(js) self.implServiceDefinition1(inst2) def implServiceDefinition1(self, inst): self.assertEqual(inst.date.date, FHIRDate("2015-07-22").date) self.assertEqual(inst.date.as_json(), "2015-07-22") self.assertEqual(inst.description, "Guideline appropriate ordering is used to assess appropriateness of an order given a patient, a proposed order, and a set of clinical indications.") self.assertEqual(inst.id, "example") self.assertEqual(inst.identifier[0].use, "official") self.assertEqual(inst.identifier[0].value, "guildeline-appropriate-ordering") self.assertEqual(inst.status, "draft") self.assertEqual(inst.text.status, "generated") self.assertEqual(inst.title, "Guideline Appropriate Ordering Module") self.assertEqual(inst.topic[0].text, "Guideline Appropriate Ordering") self.assertEqual(inst.topic[1].text, "Appropriate Use Criteria") self.assertEqual(inst.version, "1.0.0")
[ { "point_num": 1, "id": "every_function_has_docstring", "question": "Does every function in this file have a docstring?", "answer": false }, { "point_num": 2, "id": "every_function_under_20_lines", "question": "Is every function in this file shorter than 20 lines?", "answer": tru...
3
models/servicedefinition_tests.py
elementechemlyn/CareConnectBuilder
#!/usr/bin/env python3 # Copyright (c) 2016 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. import test_framework.loginit # # Helper script to create the cache # (see BitcoinTestFramework.setup_chain) # from test_framework.test_framework import BitcoinTestFramework class CreateCache(BitcoinTestFramework): def __init__(self): super().__init__() # Test network and test nodes are not required: self.num_nodes = 0 self.nodes = [] def setup_network(self): pass def run_test(self): pass if __name__ == '__main__': CreateCache().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": "more_functions_than_classes", "question": "Does this file define more functions than classes?", "answer": true }...
3
qa/rpc-tests/create_cache.py
jtoomim/BitcoinUnlimited
from Shoots.bin.shoots import Shoots from Shoots.bin.info import Info from Shoots.bin.ai.shooter import CFRShooter as AIShooter class AIShoots(Shoots): """ automatically add two AIShooter """ def __init__(self): super().__init__() self.map.map = [ [self.map.ROAD] * 5 ] * 5 self.players.append(AIShooter(self.map)) self.players.append(AIShooter(self.map)) self.viewers = [] self.view = None def update_model(self): if len(self.viewers) == 0: return if [i.dead for i in self.players].count(False) == 1: raise Exception("Game over") for i in self.players: i.action() super().update_model() fullInfo = Info() for j in self.players: fullInfo.shooter.append({ 'position':j.position, 'facing':j.face }) for i in self.viewers: i.update_info(fullInfo) def update_frame(self): if self.update_frame_callback: self.update_frame_callback() def add_player(self): player = AIShooter(self.map) self.viewers.append(player) return player
[ { "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
Shoots/bin/ai/shoots.py
lyh-ADT/Shoots
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # # http://www.apache.org/licenses/LICENSE-2.0 # # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. from aliyunsdkcore.request import RpcRequest from aliyunsdkvs.endpoint import endpoint_data class DeleteRenderingDevicesRequest(RpcRequest): def __init__(self): RpcRequest.__init__(self, 'vs', '2018-12-12', 'DeleteRenderingDevices') self.set_method('POST') if hasattr(self, "endpoint_map"): setattr(self, "endpoint_map", endpoint_data.getEndpointMap()) if hasattr(self, "endpoint_regional"): setattr(self, "endpoint_regional", endpoint_data.getEndpointRegional()) def get_OwnerId(self): return self.get_query_params().get('OwnerId') def set_OwnerId(self,OwnerId): self.add_query_param('OwnerId',OwnerId) def get_InstanceIds(self): return self.get_query_params().get('InstanceIds') def set_InstanceIds(self,InstanceIds): self.add_query_param('InstanceIds',InstanceIds)
[ { "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
aliyun-python-sdk-vs/aliyunsdkvs/request/v20181212/DeleteRenderingDevicesRequest.py
yndu13/aliyun-openapi-python-sdk
from django.shortcuts import render, redirect, HttpResponse from student.forms import StudentsForm from student.models import Students def std(request): if request.method == "POST": form = StudentsForm(request.POST) if form.is_valid(): try: form.save() return redirect('/') except: pass else: form = StudentsForm() return render(request, 'student/home.html', {'form': form}) def view(request): students = Students.objects.all() return render(request, 'view.html', {'students': students}) def delete(request, id): students = Students.objects.get(id=id) students.delete() return redirect("/") def edit(request, id): students = Students.objects.get(id=id) return render(request, 'edit.html', {'students': students}) # Create your views here. def home(request): # return render(request, 'student/home.html') students = Students.objects.all() return render(request, 'student/home.jinja2', {'students': students}) def about(request): return render(request, 'student/testjinja2.jinja', {'title': 'about'})
[ { "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
14_Tran_An_Thien/ManagementStudents/student/views.py
lpython2006e/exercies
import hashlib from pathlib import PurePath # return a mapping from external id to file names def read_index_file(index_file): extid_to_name = {} with open(index_file) as f: for line in f: pairs = line.strip().split() external_id = int(pairs[0]) file_name = PurePath(pairs[1]).stem extid_to_name[external_id] = file_name return extid_to_name def gen_secret_code(tasks_session): """ input is crossdochash1-crossdochash2-crossdochash3 """ string = tasks_session + "-cdecanntool" return hashlib.sha256(str.encode(string)).hexdigest() def gen_hash(name): name = str(name) return hashlib.sha256(str.encode(name)).hexdigest()
[ { "point_num": 1, "id": "every_function_under_20_lines", "question": "Is every function in this file shorter than 20 lines?", "answer": true }, { "point_num": 2, "id": "has_nested_function_def", "question": "Does this file contain any function defined inside another function?", "...
3
multidoc-stave/simple-backend/nlpviewer_backend/utils.py
adithya7/cdec-ann-tool
import model def dolzina_maksimalnega_clena(sez): m = len(sez) n = len(sez[0]) najvecji = max([sez[i][j] for i in range(m) for j in range(n)]) return len(str(najvecji)) def prikaz_matrike(sez): m = len(sez) n = len(sez[0]) razmik = dolzina_maksimalnega_clena(sez) for i in range(m): vrstica = '|' for j in range(n): clen = sez[i][j] razlika = razmik - len(str(clen)) for _ in range(razlika // 2 + 1): vrstica += ' ' vrstica += str(clen) for _ in range(razlika // 2): vrstica += ' ' if razlika % 2 == 1: vrstica += ' ' print(vrstica + ' |') def zahtevaj_velikost(): return input("Stevilo vrstic: "), input("Stevilo stolpcev: ") def zahtevaj_vnos(m, n): return [[int(input("a_{0},{1} = ".format(i, j))) for j in range(1, n+1)] for i in range(1, m+1)] def pozeni_vmesnik(): while True: m, n = zahtevaj_velikost() sez = zahtevaj_vnos(int(m), int(n)) return sez def prikazi_matriko(sez): m = len(sez) n = len(sez[0]) razmik = dolzina_maksimalnega_clena(sez) matrika = '' for i in range(m): vrstica = '|' for j in range(n): clen = sez[i][j] razlika = razmik - len(str(clen)) for _ in range(razlika // 2 + 1): vrstica += ' ' vrstica += str(clen) for _ in range(razlika // 2): vrstica += ' ' if razlika % 2 == 1: vrstica += ' ' matrika += (vrstica + ' |\n') return matrika #a = pozeni_vmesnik() #print(prikaz_matrike(a))
[ { "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
tekstovni_vmesnik.py
milaneztim/Racunanje-z-matrikami
import torch import torch.nn as nn import torch.nn.functional as F from networks.network_utils import hidden_init class MADDPGCriticVersion1(nn.Module): def __init__(self, num_agents, state_size, action_size, fcs1_units, fc2_units, seed=0): """Initialize parameters and build model. Params ====== num_agents (int): number of agents state_size (int): Dimension of each state action_size (int): Dimension of each action seed (int): Random seed fcs1_units (int): Number of nodes in the first hidden layer fc2_units (int): Number of nodes in the second hidden layer """ super().__init__() self.seed = torch.manual_seed(seed) self.fcs1 = nn.Linear(num_agents*state_size, fcs1_units) self.fc2 = nn.Linear(fcs1_units+(num_agents*action_size), fc2_units) self.fc3 = nn.Linear(fc2_units, 1) self.reset_parameters() def reset_parameters(self): self.fcs1.weight.data.uniform_(*hidden_init(self.fcs1)) self.fc2.weight.data.uniform_(*hidden_init(self.fc2)) self.fc3.weight.data.uniform_(-3e-3, 3e-3) def forward(self, states_1d, actions_1d): """ Build a critic (value) network that maps (state, action) pairs -> Q-values. Args: states_1d (torch.tensor): shape[1] = (num_agents*state_size) actions_1d (torch.tensor): shape[1] = (num_agents*action_size) """ xs = F.relu(self.fcs1(states_1d)) x = torch.cat((xs, actions_1d), dim=1) x = F.relu(self.fc2(x)) return self.fc3(x)
[ { "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
p3_collab-compet/MADDPG/networks/maddpg_critic_version_1.py
Brandon-HY-Lin/deep-reinforcement-learning
from django.db import models from django.contrib.auth import get_user_model User = get_user_model() class Group(models.Model): title = models.CharField(max_length=200) slug = models.SlugField(unique=True) description = models.TextField() def __str__(self): return str(self.title) #в задании говорится сделать тут __str__ class Post(models.Model): text = models.TextField() pub_date = models.DateTimeField("date published", auto_now_add=True) author = models.ForeignKey(User, on_delete=models.CASCADE, related_name="posts") group = models.ForeignKey(Group, on_delete = models.SET_NULL, blank=True, null=True, related_name="posts") def __str__(self): return str(self.text) class Meta: ordering = ["-pub_date"]
[ { "point_num": 1, "id": "every_function_has_docstring", "question": "Does every function in this file have a docstring?", "answer": false }, { "point_num": 2, "id": "more_functions_than_classes", "question": "Does this file define more functions than classes?", "answer": false ...
3
posts/models.py
DavLivesey/hw02_community-master
from typing import Callable from httpx import Request, Response, codes from pytest import raises from pytest_httpx import HTTPXMock from firebolt.client.auth import Token from firebolt.utils.exception import AuthorizationError from tests.unit.util import execute_generator_requests def test_token_happy_path( httpx_mock: HTTPXMock, test_token: str, check_token_callback: Callable ) -> None: """Validate that provided token is added to request.""" httpx_mock.add_callback(check_token_callback) auth = Token(test_token) execute_generator_requests(auth.auth_flow(Request("GET", "https://host"))) def test_token_invalid(httpx_mock: HTTPXMock) -> None: """Authorization error raised when token is invalid.""" def authorization_error(*args, **kwargs) -> Response: return Response(status_code=codes.UNAUTHORIZED) httpx_mock.add_callback(authorization_error) auth = Token("token") with raises(AuthorizationError): execute_generator_requests(auth.auth_flow(Request("GET", "https://host"))) def test_token_expired() -> None: """Authorization error is raised when token expires.""" auth = Token("token") auth._expires = 0 with raises(AuthorizationError): execute_generator_requests(auth.auth_flow(Request("GET", "https://host")))
[ { "point_num": 1, "id": "all_return_types_annotated", "question": "Does every function in this file have a return type annotation?", "answer": true }, { "point_num": 2, "id": "no_function_exceeds_5_params", "question": "Does every function in this file take 5 or fewer parameters (exc...
3
tests/unit/client/auth/test_token.py
firebolt-db/firebolt-python-sdk
import telegram from . import start from . import add_feed from . import remove_feed def register_commands(dispatcher: telegram.ext.Dispatcher): def add_all(handlers): for handler in handlers: dispatcher.add_handler(handler) add_all(start.get_handlers()) add_all(add_feed.get_handlers()) add_all(remove_feed.get_handlers())
[ { "point_num": 1, "id": "every_function_has_docstring", "question": "Does every function in this file have a docstring?", "answer": false }, { "point_num": 2, "id": "has_nested_function_def", "question": "Does this file contain any function defined inside another function?", "ans...
3
src/sauce_bot/commands/__init__.py
asmello/feed-tracker-bot
from django.core.exceptions import BadRequest, PermissionDenied from .books import books_list, BookListView, BookDetailView, BookDeleteView from .index import index, IndexView from .readers import readers_list, ReaderListView from .users import users_list, UserListView, CreateUserView def server_death(request): raise Exception def bad_user_request(request): raise BadRequest def permission_denied(request): raise PermissionDenied __all__ = [ users_list, UserListView, CreateUserView, readers_list, ReaderListView, books_list, BookListView, BookDetailView, BookDeleteView, index, IndexView, server_death, bad_user_request, permission_denied ]
[ { "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
microblog/blog/views/__init__.py
zaldis/MAcademy2021
# Manter Ordem Alfabética def join_list(lst, string=', '): """ :param lst: List to be joined :param string: String that will be used to join the items in the list :return: List after being converted into a string """ lst = str(string).join(str(x) for x in lst) return lst def unique_list(lst): to_eliminate = [] for c, item in enumerate(lst): if lst.index(item) != c: to_eliminate += [c] to_eliminate.sort(reverse=True) for c in to_eliminate: lst.pop(c) return lst
[ { "point_num": 1, "id": "all_params_annotated", "question": "Does every function parameter in this file have a type annotation (excluding self/cls)?", "answer": false }, { "point_num": 2, "id": "every_function_under_20_lines", "question": "Is every function in this file shorter than ...
3
Modules/my_list/__init__.py
guilhermebaos/Curso-em-Video-Python
PI = 3.14 def rectangle_funk(): a = float(input("Please, enter first side of rectangle: ")) b = float(input("Please, enter second side of rectangle: ")) return a * b def triangle_funk(): a = float(input("Please, enter side of triangle: ")) h = float(input("Please, enter height of triangle: ")) return 0.5 * a * h def circle_funk(): radius = float(input("Please, enter radius of circle: ")) return (PI * radius**2) area = input("What area do you want: rectangle - 1, triangle - 2, circle - 3? ") if area == "1": print(f"{rectangle_funk()} is area of rectangle") elif area == "2": print(f"{triangle_funk()} is area of triangle") elif area == "3": print(f"{circle_funk()} is area of circle") else: print("Sorry, you entered wrong number")
[ { "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
HW6/VeronyWise/task6.2.py
kolyasalubov/Lv-677.PythonCore
def topological_sort(propagation_end_node): """A utility function to perform a topological sort on a DAG starting from the node to perform backpropagation. Parameters ---------- propagation_end_node : Node The node to perform backpropagation. Returns ------- List[Node] A list of nodes that have been topologically sorted, starting with propagation_end_node. """ counting_dict = {} stack = [] childness_nodes = [] # Starting with the node where the propagation ends stack.append(propagation_end_node) childness_nodes.append(propagation_end_node) # Counting the number of children of each node where the direction of the # edges is the same as the direction of the propagation while stack: node = stack.pop() if node in counting_dict: counting_dict[node] += 1 else: counting_dict[node] = 1 stack.extend(node.parents) # Returns the nodes without children while childness_nodes: good_node = childness_nodes.pop() yield good_node for parent in good_node.parents: if counting_dict[parent] == 1: childness_nodes.append(parent) else: counting_dict[parent] -= 1 def substitute_values(x, index_value_pairs): x_list = list(x) for i, v in index_value_pairs: x_list[i] = v return tuple(x_list) def substitute_value(x, index, value): x_list = list(x) x_list[index] = value return tuple(x_list)
[ { "point_num": 1, "id": "has_nested_function_def", "question": "Does this file contain any function defined inside another function?", "answer": false }, { "point_num": 2, "id": "no_function_exceeds_5_params", "question": "Does every function in this file take 5 or fewer parameters (...
3
util.py
ChristophorusX/A-Tentative-Autograd-Implementation
def add(a,b): return a + b def subtract(a,b): return a - b def product(a,b): return a * b
[ { "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
example.py
CJSmekens/code-refinery-bq-1
# -*- coding: utf-8 -*- """URLs for all views.""" from django.conf import settings from django.shortcuts import render def home(request): """Dashboard home.""" return render( request, 'dashboard/home.html', {'foobar': settings.FOO_BAR}, ) def search(request): """Dashboard search.""" return render( request, 'dashboard/search.html', {} )
[ { "point_num": 1, "id": "every_function_has_docstring", "question": "Does every function in this file have a docstring?", "answer": true }, { "point_num": 2, "id": "every_function_under_20_lines", "question": "Is every function in this file shorter than 20 lines?", "answer": true...
3
djskeletor/dashboard/views.py
carthagecollege/django-djskeletor
from django.contrib.admin import AdminSite from django.contrib.admin.apps import AdminConfig from django.urls import path class CustomAdminSite(AdminSite): def get_urls(self): from degvabank.core import views urls = super().get_urls() my_urls = [ path( 'reports/client_transaction/', self.admin_view(views.ReportClientTransaction.as_view()), name='report-client-transaction', ), path( 'reports/client_list/', self.admin_view(views.ReportClientList.as_view()), name='report-client-list', ), path( 'reports/transactions/', self.admin_view(views.ReportTransactions.as_view()), name='report-transactions', ), ] urls = my_urls + urls return urls class AdminConfig(AdminConfig): default_site = "degvabank.core.admin.CustomAdminSite"
[ { "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
degvabank/degvabank/core/admin.py
Vixx-X/DEGVABanck-backend
from dataclasses import dataclass from debussy_concert.core.config.movement_parameters.base import MovementParametersBase @dataclass(frozen=True) class BigQueryDataPartitioning: partitioning_type: str gcs_partition_schema: str partition_field: str destination_partition: str @dataclass(frozen=True) class BigQueryTimeDataPartitioning(BigQueryDataPartitioning): partition_granularity: str @dataclass(frozen=True) class TimePartitionedDataIngestionMovementParameters(MovementParametersBase): extract_connection_id: str data_partitioning: BigQueryTimeDataPartitioning def __post_init__(self): if isinstance(self.data_partitioning, BigQueryTimeDataPartitioning): return data_partitioning = BigQueryTimeDataPartitioning(**self.data_partitioning) # hack for frozen dataclass https://stackoverflow.com/a/54119384 # overwriting data_partitioning with BigQueryTimeDataPartitioning instance object.__setattr__(self, 'data_partitioning', data_partitioning)
[ { "point_num": 1, "id": "every_class_has_docstring", "question": "Does every class in this file have a docstring?", "answer": false }, { "point_num": 2, "id": "more_functions_than_classes", "question": "Does this file define more functions than classes?", "answer": false }, {...
3
debussy_concert/data_ingestion/config/movement_parameters/time_partitioned.py
DotzInc/debussy_concert
''' Created on 8 May 2021 @author: julianporter ''' from .chunk import FLPChunk class FLPHeader(FLPChunk): def __init__(self,data=b''): super().__init__(data) try: self.format = FLPChunk.getInt16(self.data[0:2]) self.nTracks = FLPChunk.getInt16(self.data[2:4]) self.division = FLPChunk.getInt16(self.data[4:6]) except: self.format = 0 self.nTracks = 0 self.division=0 def __str__(self): return f'Format {hex(self.format)} nTracks {hex(self.nTracks)} division {hex(self.division)}'
[ { "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
FLP/chunks/header.py
TheXIFC/FL-Studio-Time-Calculator
from HDPython import * from HDPython.examples import * from .helpers import Folders_isSame, vhdl_conversion, do_simulation,printf from HDPython.test_handler import add_test class test_bench_axi_fifo(v_entity): def __init__(self): super().__init__() self.architecture() def architecture(self): clkgen = clk_generator() maxCount = v_slv(32,20) pipe1 = rollingCounter(clkgen.clk,maxCount) \ | axiFifo(clkgen.clk) \ | axiFifo(clkgen.clk, depth = 5) \ | axiPrint(clkgen.clk) end_architecture() @do_simulation def test_bench_axi_fifo_sim(OutputPath, f= None): tb = test_bench_axi_fifo() return tb def test_test_bench_axi_fifo_sim(): return test_bench_axi_fifo_sim("tests/axi_fifo_sim/") add_test("axi_fifo_sim", test_test_bench_axi_fifo_sim) @vhdl_conversion def test_bench_axi_fifo_2vhdl(OutputPath, f= None): tb = test_bench_axi_fifo() return tb def test_test_bench_axi_fifo_2vhdl(): return test_bench_axi_fifo_2vhdl("tests/axi_fifo/") add_test("axi_fifo_2vhdl", test_test_bench_axi_fifo_2vhdl)
[ { "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
HDPython/tests/test_axi_fifo.py
HardwareDesignWithPython/HDPython
import unittest from securityheaders.checkers.cors import AccessControlExposeHeadersSensitiveChecker class AccessControlExposeHeadersSensitiveCheckerTest(unittest.TestCase): def setUp(self): self.x = AccessControlExposeHeadersSensitiveChecker() def test_checkNoHeader(self): nox = dict() nox['test'] = 'value' self.assertEqual(self.x.check(nox), []) def test_checkNone(self): nonex = None self.assertEqual(self.x.check(nonex), []) def test_checkNone2(self): hasx = dict() hasx['access-control-expose-headers'] = None self.assertEqual(self.x.check(hasx), []) def test_checkInvalid(self): hasx2 = dict() hasx2['access-control-expose-headers'] = "Authentication-Token" result = self.x.check(hasx2) self.assertIsNotNone(result) self.assertEqual(len(result), 1) def test_checkInvalid2(self): hasx5 = dict() hasx5['access-control-expose-headers'] = "Authorization" result = self.x.check(hasx5) self.assertIsNotNone(result) self.assertEqual(len(result), 1) def test_checkInvalid3(self): hasx5 = dict() hasx5['access-control-expose-headers'] = "Session" result = self.x.check(hasx5) self.assertIsNotNone(result) self.assertEqual(len(result), 1) def test_checkInvalid4(self): hasx5 = dict() hasx5['access-control-expose-headers'] = "Session, Authentication-Token, PUT" result = self.x.check(hasx5) self.assertIsNotNone(result) self.assertEqual(len(result), 2) def test_checkValid2(self): hasx5 = dict() hasx5['access-control-expose-headers'] = "PUT" self.assertEqual(self.x.check(hasx5), []) if __name__ == '__main__': unittest.main()
[ { "point_num": 1, "id": "all_function_names_snake_case", "question": "Are all function names in this file written in snake_case?", "answer": false }, { "point_num": 2, "id": "every_function_under_20_lines", "question": "Is every function in this file shorter than 20 lines?", "ans...
3
securityheaders/checkers/cors/exposeheaders/test_exposesensitiveheaders.py
th3cyb3rc0p/securityheaders
#!/usr/bin/env python """Tests for synonym.""" import unittest from synonym import synonym class SynonymTestCase(unittest.TestCase): def return_synonym(self, query): parser = synonym.get_parser() args = vars(parser.parse_args(query.split(' '))) return synonym.synonym(args) def setUp(self): self.queries = ['display', 'make', 'very'] self.typo_queries = ['halla', 'intesting', 'placs'] self.bad_queries = ['lksdlkf', 'lksjldkjf'] def tearDown(self): pass def test_synonyms(self): for query in self.queries: self.assertTrue(self.return_synonym(query)) for query in self.typo_queries: self.assertTrue(self.return_synonym(query)) for query in self.bad_queries: self.assertTrue(self.return_synonym(query)) def test_property(self): query = self.queries[0] first_answer = self.return_synonym(query) second_answer = self.return_synonym(query + ' -pn') self.assertNotEqual(first_answer, second_answer) if __name__ == '__main__': unittest.main()
[ { "point_num": 1, "id": "every_function_has_docstring", "question": "Does every function in this file have a docstring?", "answer": false }, { "point_num": 2, "id": "has_nested_function_def", "question": "Does this file contain any function defined inside another function?", "ans...
3
test_synonym.py
gavinzbq/synonym
# Copyright 2020, Kay Hayen, mailto:kay.hayen@gmail.com # # Python test originally created or extracted from other peoples work. The # parts from me are licensed as below. It is at least Free Software where # it's copied from other people. In these cases, that will normally be # indicated. # # 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. # def f1(): yield 1, 2, 3 def f2(): yield 1, 2, 4 def comparer(): g1 = f1() g2 = f2() # This enables tracing in a custom build of mine. a = 1 o = oct o(a) for i in range(10000): # g1 == g2 g1 == a if __name__ == "__main__": comparer()
[ { "point_num": 1, "id": "every_function_under_20_lines", "question": "Is every function in this file shorter than 20 lines?", "answer": true }, { "point_num": 2, "id": "has_nested_function_def", "question": "Does this file contain any function defined inside another function?", "...
3
tests/benchmarks/micro/GeneratorComparison.py
juanfra684/Nuitka
# -*- encoding:utf-8 -*- import discord from discord.ext.commands import check, NotOwner def is_owner(): """ A :func:`.check` that checks if the person invoking this command is the owner of the bot. This is powered by :meth:`.Bot.is_owner`. This check raises a special exception, :exc:`.NotOwner` that is derived from :exc:`.CheckFailure`. """ async def predicate(ctx): if not await ctx.bot.is_owner(ctx.author): embed = discord.Embed() embed.set_author(name=f' | You do not own this bot.', url=ctx.author.avatar_url, icon_url=ctx.author.avatar_url) await ctx.channel.send(embed=embed) raise NotOwner(f"({ctx.author.name}#{ctx.author.discriminator} | {str(ctx.author.id)}) to run a system that shouldn't.") return True return check(predicate)
[ { "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
utils/overwrite.py
AliasPedroKarim/Kagura
import asyncio import inspect import re from typing import Any, Callable, Dict, Set from pydantic.typing import ForwardRef, evaluate_forwardref def get_typed_signature(call: Callable) -> inspect.Signature: "Finds call signature and resolves all forwardrefs" signature = inspect.signature(call) globalns = getattr(call, "__globals__", {}) typed_params = [ inspect.Parameter( name=param.name, kind=param.kind, default=param.default, annotation=get_typed_annotation(param, globalns), ) for param in signature.parameters.values() ] typed_signature = inspect.Signature(typed_params) return typed_signature def get_typed_annotation(param: inspect.Parameter, globalns: Dict[str, Any]) -> Any: annotation = param.annotation if isinstance(annotation, str): annotation = make_forwardref(annotation, globalns) return annotation def make_forwardref(annotation: str, globalns: Dict[str, Any]): annotation = ForwardRef(annotation) annotation = evaluate_forwardref(annotation, globalns, globalns) return annotation def get_path_param_names(path: str) -> Set[str]: "turns path string like /foo/{var}/path/{another}/end to set ['var', 'another']" return {item.strip("{}") for item in re.findall("{[^}]*}", path)} def is_async(callable: Callable): return asyncio.iscoroutinefunction(callable)
[ { "point_num": 1, "id": "all_params_annotated", "question": "Does every function parameter in this file have a type annotation (excluding self/cls)?", "answer": true }, { "point_num": 2, "id": "no_function_exceeds_5_params", "question": "Does every function in this file take 5 or few...
3
ninja/signature/utils.py
dengerr/django-ninja
# -*- coding: utf-8 -*- ''' Interface with a Junos device via proxy-minion. ''' # Import python libs from __future__ import print_function from __future__ import absolute_import import logging # Import 3rd-party libs # import jnpr.junos # import jnpr.junos.utils # import jnpr.junos.utils.config import json HAS_JUNOS = True __proxyenabled__ = ['junos'] thisproxy = {} log = logging.getLogger(__name__) # def __init__(opts): # ''' # Open the connection to the Junos device, login, and bind to the # Resource class # ''' # log.debug('Opening connection to junos') # thisproxy['conn'] = jnpr.junos.Device(user=opts['proxy']['username'], # host=opts['proxy']['host'], # password=opts['proxy']['passwd']) # thisproxy['conn'].open() # thisproxy['conn'].bind(cu=jnpr.junos.utils.config.Config) def conn(): return thisproxy['conn'] def facts(): return thisproxy['conn'].facts def refresh(): return thisproxy['conn'].facts_refresh() def proxytype(): ''' Returns the name of this proxy ''' return 'junos' def id(opts): ''' Returns a unique ID for this proxy minion ''' return thisproxy['conn'].facts['hostname'] def ping(): ''' Ping? Pong! ''' return thisproxy['conn'].connected def shutdown(opts): ''' This is called when the proxy-minion is exiting to make sure the connection to the device is closed cleanly. ''' log.debug('Proxy module {0} shutting down!!'.format(opts['id'])) try: thisproxy['conn'].close() except Exception: pass def rpc(): return json.dumps(thisproxy['conn'].rpc.get_software_information())
[ { "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
salt/proxy/junos.py
vamshi98/salt-formulas
# -*- coding: utf-8 -*- from django.contrib.sitemaps import Sitemap from ionyweb.page.models import Page class PagesSitemap(Sitemap): changefreq = "weekly" priority = 0.5 def items(self): return Page.objects.filter(draft=False) def lastmod(self, obj): return obj.last_modif
[ { "point_num": 1, "id": "more_functions_than_classes", "question": "Does this file define more functions than classes?", "answer": true }, { "point_num": 2, "id": "has_nested_function_def", "question": "Does this file contain any function defined inside another function?", "answe...
3
ionyweb/page/sitemap.py
makinacorpus/ionyweb
import imutils import numpy as np import cv2 import base64 def byte_to_image(string_byte): jpg_original = base64.b64decode(string_byte) jpg_as_np = np.frombuffer(jpg_original, dtype=np.uint8) img = cv2.imdecode(jpg_as_np, flags=1) return img def file_to_image(file): img = np.asarray(bytearray(file.read()), dtype="uint8") img = cv2.imdecode(img, cv2.IMREAD_COLOR) return img def resize_gray_image(image): orig_resize = imutils.resize(image, width=500) gray = cv2.cvtColor(orig_resize, cv2.COLOR_BGR2GRAY) return gray def detect_blur_fft(image, size, thresh): (h, w) = image.shape (cX, cY) = (int(w / 2.0), int(h / 2.0)) fft = np.fft.fft2(image) fft_shift = np.fft.fftshift(fft) fft_shift[cY - size:cY + size, cX - size:cX + size] = 0 fft_shift = np.fft.ifftshift(fft_shift) recon = np.fft.ifft2(fft_shift) magnitude = 20 * np.log(np.abs(recon)) mean = np.mean(magnitude) return mean, mean <= thresh def evaluate_image(image, file_name_param, radio_value, thresh_value): image = resize_gray_image(image) (mean, blurry) = detect_blur_fft(image, radio_value, thresh_value) return {"filename": file_name_param, "value": mean, "isblur": blurry}
[ { "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
Rest Django Framework/api_image_manager/blur_image_app/blur_image.py
PaulMarcelo/Python
"""Defines the core data classes and types for Gearbox environments.""" from dataclasses import dataclass from typing import Any, Callable, Iterable, Union @dataclass class Action: """Base class that all actions are suggested to extend.""" @dataclass class State: """Base class that all states are suggested to extend.""" @dataclass class Outcome: """Ground-truth outcome returned by engines. Attributes: state: Ground-truth state of the environment. reward: Reward for each agent. done: Whether or not the episode is complete. info: Information not captured by other fields. """ state: State reward: Union[int, Iterable[int]] done: bool info: Any Engine = Callable[[State, Action], Outcome] class InvalidActionException(Exception): """Exception engines are suggested to raise if an action is invalid.""" @dataclass class Environment: """Stateful wrapper for engines that persists the state. Attributes: state: State of the environment persisted after each step. engine: Engine defining the environment logic. """ state: State engine: Engine def step(self, action: Action) -> Outcome: """Advance the environment a step forward with the provided action. Args: action: Action to take on the environment Returns: Outcome defining result of the action on the environment. """ outcome = self.engine(self.state, action) self.state = outcome.state return outcome
[ { "point_num": 1, "id": "has_multiple_inheritance", "question": "Does any class in this file use multiple inheritance?", "answer": false }, { "point_num": 2, "id": "more_functions_than_classes", "question": "Does this file define more functions than classes?", "answer": false }...
3
gearbox_py/core/environments.py
sColin16/gearbox_py
# -*- coding: utf-8 -*- """Experiments Metrics controller.""" import platiagro from projects.exceptions import NotFound class MetricController: def __init__(self, session): self.session = session def list_metrics(self, project_id: str, experiment_id: str, run_id: str, operator_id: str): """ Lists all metrics from object storage. Parameters ---------- project_id : str experiment_id : str run_id : str The run_id. If `run_id=latest`, then returns metrics from the latest run_id. operator_id : str Returns ------- list A list of metrics. """ try: return platiagro.list_metrics(experiment_id=experiment_id, operator_id=operator_id, run_id=run_id) except FileNotFoundError as e: raise NotFound(str(e))
[ { "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
projects/controllers/experiments/runs/metrics.py
dnlcesilva/projects
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import random from torch.nn import Module from MinkowskiEngine import SparseTensor class Wrapper(Module): """ Wrapper for the segmentation networks. """ OUT_PIXEL_DIST = -1 def __init__(self, NetClass, in_nchannel, out_nchannel, config): super(Wrapper, self).__init__() self.initialize_filter(NetClass, in_nchannel, out_nchannel, config) def initialize_filter(self, NetClass, in_nchannel, out_nchannel, config): raise NotImplementedError('Must initialize a model and a filter') def forward(self, x, coords, colors=None): soutput = self.model(x) # During training, make the network invariant to the filter if not self.training or random.random() < 0.5: # Filter requires the model to finish the forward pass wrapper_coords = self.filter.initialize_coords(self.model, coords, colors) finput = SparseTensor(soutput.F, wrapper_coords) soutput = self.filter(finput) return soutput
[ { "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
downstream/semseg/models/wrapper.py
ut-amrl/ContrastiveSceneContexts
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """Factorial test module.""" __author__ = "Stanislav D. Kudriavtsev" from pytest import mark, raises from gcd_iter import gcd_iter from gcd_rec import gcd_rec # pylint: disable=arguments-out-of-order @mark.parametrize("num1, num2", [(1.0, 2), (1, 2.0), (0, -1.0), (-1, 0.0)]) def test_incorrect_inputs(num1, num2): """Test non-integers.""" with raises(TypeError): gcd_iter(num1, num2) with raises(TypeError): gcd_rec(num1, num2) @mark.parametrize( "num1, num2", [(0, 0), (3, 0), (4, 1), (12, 3), (12, 4), (12, 6), (12, 10), (12, 12)], ) def test_various_inputs(num1, num2): """Test various inputs.""" for params in ((num1, num2), (-num1, num2), (num1, -num2), (-num1, -num2)): assert gcd_iter(*params) == gcd_rec(*params) params = params[::-1] assert gcd_iter(*params) == gcd_rec(*params)
[ { "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
Python/math/gcd/test_gcd.py
stanislav-kudriavtsev/Algorithms
class CNN(nn.Module): def __init__(self): super().__init__() # Important, otherwise will throw an error self.cnn = nn.Sequential( nn.Conv2d(3, 32, kernel_size=5, stride=1, padding=2), # 32x32x32 nn.ReLU(inplace=True), nn.MaxPool2d(kernel_size=2, stride=2, padding=0), # 32x16x16 nn.Conv2d(32, 64, kernel_size=5, stride=1, padding=2), # 64x16x16 nn.ReLU(inplace=True), # faster with inplace, no need to copy nn.MaxPool2d(kernel_size=2, stride=2, padding=0), # 64x8x8 nn.Conv2d(64, 64, kernel_size=5, stride=1, padding=2), # 64x8x8 nn.ReLU(inplace=True), nn.MaxPool2d(kernel_size=2, stride=2, padding=0), # 64x4x4 ) self.fc1 = nn.Linear(4 * 4 * 64, 1000) self.act = nn.ReLU(inplace=True) self.fc2 = nn.Linear(1000, 10) def forward(self, x): x = self.cnn(x) b, c, h, w = x.shape x = x.view(b, c * h * w) # equivalent to x.view(b, -1) x = self.act(self.fc1(x)) x = self.fc2(x) return x
[ { "point_num": 1, "id": "every_function_has_docstring", "question": "Does every function in this file have a docstring?", "answer": false }, { "point_num": 2, "id": "more_functions_than_classes", "question": "Does this file define more functions than classes?", "answer": true }...
3
static/code/cnn/lenet.py
navivokaj/deepcourse
from django.db import transaction from rest_framework import generics, mixins class BaseAPIView(generics.GenericAPIView, mixins.CreateModelMixin, mixins.ListModelMixin, mixins.RetrieveModelMixin, mixins.UpdateModelMixin, mixins.DestroyModelMixin): @transaction.atomic def get(self, request, *args, **kwargs): if kwargs.get('pk'): return self.retrieve(request, *args, **kwargs) else: return self.list(request, *args, **kwargs) @transaction.atomic def post(self, request, *args, **kwargs): return self.create(request, *args, **kwargs) @transaction.atomic def put(self, request, *args, **kwargs): return self.update(request, *args, **kwargs) @transaction.atomic def patch(self, request, *args, **kwargs): return self.partial_update(request, *args, **kwargs) @transaction.atomic def delete(self, request, *args, **kwargs): return self.destroy(request, *args, **kwargs)
[ { "point_num": 1, "id": "all_params_annotated", "question": "Does every function parameter in this file have a type annotation (excluding self/cls)?", "answer": false }, { "point_num": 2, "id": "all_function_names_snake_case", "question": "Are all function names in this file written ...
3
core/api/base.py
care2donate/care2donate
#!/usr/bin/env python # -*- coding: utf-8 -*- # author:ls import tornado.ioloop import tornado.web class MainHandler(tornado.web.RequestHandler): def get(self,*args,**kwargs): self.write("Hello, world") def main(): application = tornado.web.Application([ (r"/", MainHandler), ],debug=True) application.listen(8888) tornado.ioloop.IOLoop.current().start() 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": "every_function_has_docstring", "question": "Does every function in this file have a docstring?", "answer": false }...
3
tornado_learning/simple_server.py
rwbooks/python_learning
""" ECB没有偏移量 """ from Crypto.Cipher import AES from binascii import b2a_hex, a2b_hex from utils import DES_decrypt, DES_encrypt def add_to_16(text): if len(text.encode('utf-8')) % 16: add = 16 - (len(text.encode('utf-8')) % 16) else: add = 0 text = text + ('\0' * add) return text.encode('utf-8') # 加密函数 def encrypt(text): key = '9999999999999999'.encode('utf-8') mode = AES.MODE_ECB text = add_to_16(text) cryptos = AES.new(key, mode) cipher_text = cryptos.encrypt(text) return b2a_hex(cipher_text) # 解密后,去掉补足的空格用strip() 去掉 def decrypt(text): key = '9999999999999999'.encode('utf-8') mode = AES.MODE_ECB cryptor = AES.new(key, mode) plain_text = cryptor.decrypt(a2b_hex(text)) return bytes.decode(plain_text).rstrip('\0') if __name__ == '__main__': e = DES_encrypt("hello world") # 加密 print(type(e)) d = DES_decrypt(e) # 解密 print("加密:", e) print("解密:", d)
[ { "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
try.py
peterzheng98/Valentine-Gift
import importlib import inspect import logging import os from app.plugin import Hook, Command PLUGINS_DIR = 'plugins' def find_plugins(): """Returns a list of plugin path names.""" for root, dirs, files in os.walk(PLUGINS_DIR): for file in files: if file.endswith('.py'): yield os.path.join(root, file) def load_plugins(hook_plugins, command_plugins): """Populates the plugin lists.""" for file in find_plugins(): try: module_name = os.path.splitext(os.path.basename(file))[0] module = importlib.import_module(PLUGINS_DIR + '.' + module_name) for entry_name in dir(module): entry = getattr(module, entry_name) if not inspect.isclass(entry) or inspect.getmodule(entry) != module: continue if issubclass(entry, Hook): hook_plugins.append(entry()) elif issubclass(entry, Command): command_plugins.append(entry()) except (ImportError, NotImplementedError): continue def process_commands(input_obj, commands): logging.debug('Processing commands') hook_plugins = [] command_plugins = [] load_plugins(hook_plugins, command_plugins) for command_str in commands: for plugin in command_plugins: if command_str in plugin.names: for hook in hook_plugins: hook.before_handle(input_obj, plugin) input_obj = plugin.handle(input_obj) for hook in hook_plugins: hook.after_handle(input_obj, plugin)
[ { "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
app/processor.py
glombard/python-plugin-experiment
import cv2 # type: ignore import numpy as np def extract_frame_of_movie(tiff_movie, frame_number, output_file): """Extract a certain frame of tiff_movie, and write it into a separate file. Used for testing find_frame_of_image Args: tiff_movie (str): path to input frame_number (int): which frame to extract Raises: IOError: raised when tiff file cannot be found """ retval, imgs = cv2.imreadmulti(tiff_movie) if not retval: print(f'Error: {tiff_movie} not found.') raise IOError # tiff file not found output = imgs[frame_number] print(output.shape) cv2.imwrite(filename=output_file, img=output, ) def extract_frames_of_movie(tiff_movie, frame_number, output_file): """Extract up to a certain frame of tiff_movie, and write it into a separate file. Used for testing find_frame_of_image Args: tiff_movie (str): path to input frame_number (int): up to which frame to extract Raises: IOError: raised when tiff file cannot be found """ retval, imgs = cv2.imreadmulti(tiff_movie) if not retval: print(f'Error: {tiff_movie} not found.') raise IOError # tiff file not found output = imgs[:frame_number] cv2.imwritemulti(filename=output_file, img=output, ) if __name__ == '__main__': # extract_frames_of_movie(f'{constants.LOCAL_MOVIE_DIR}/{constants.TIFS_NAMES[1]}.tif', 10, f'{constants.LOCAL_OUT_DIR}/{constants.TIFS_NAMES[1]}_up_to_frame_10.tif') pass
[ { "point_num": 1, "id": "has_nested_function_def", "question": "Does this file contain any function defined inside another function?", "answer": false }, { "point_num": 2, "id": "all_params_annotated", "question": "Does every function parameter in this file have a type annotation (ex...
3
biu/siam_unet/helpers/extract_frame_of_movie.py
danihae/bio-image-unet