source
string
points
list
n_points
int64
path
string
repo
string
""" Unittests for examples. All examples are executed to check against latest code base. """ from __future__ import print_function, division import unittest import os import imp from helpers import filesInDirectory # ---------------------------------------------------------------- # List of python files to test # ---------------------------------------------------------------- examples_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', '..', 'examples') notebookdir = os.path.join(examples_dir, 'notebooks-py') tedir = os.path.join(examples_dir, 'tellurium-files') py_files = [] py_files.extend(filesInDirectory(notebookdir, suffix='.sedml')) py_files.extend(filesInDirectory(tedir, suffix='.sedml')) # ---------------------------------------------------------------- # Test class # ---------------------------------------------------------------- class PythonExampleTestCase(unittest.TestCase): def setUp(self): # switch the backend of matplotlib, so plots can be tested import matplotlib matplotlib.pyplot.switch_backend("Agg") # ---------------------------------------------------------------- # Dynamic generation of tests from python files # ---------------------------------------------------------------- def ftest_generator(filePath): def test(self=None): """ Test failes if Exception in execution of f. """ if self is not None: print(filePath) imp.load_source(os.path.basename(filePath)[:-3], filePath) return test for k, f in enumerate(py_files): test_name = 'test_{:03d}_{}'.format(k, os.path.basename(f)[:-3]) test_name = test_name.replace('.', '_') test = ftest_generator(f) setattr(PythonExampleTestCase, test_name, test) 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
tellurium/tests/test_examples.py
ShaikAsifullah/distributed-tellurium
import numpy as np from pysao.eim.evolutionary_interpolation import EvolutionaryInterpolationModel from pysao.metamodels.metamodel import Metamodel class EIModel(Metamodel): def __init__(self): Metamodel.__init__(self) self.model = None def _predict(self, X): return self.model.predict(X), np.zeros(X.shape[0]) def _fit(self, X, F, data): self.model = EvolutionaryInterpolationModel(xl=0 * np.ones(X.shape[1]), xu=1 * np.ones(X.shape[1])) self.model.fit(X, F) self.model.optimize() return self @staticmethod def get_params(): val = [{}] return val
[ { "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
pysurrogate/archive/eim/meta_eim.py
julesy89/pysurrogate
from maml_zoo.baselines.base import Baseline import numpy as np class ZeroBaseline(Baseline): """ Dummy baseline """ def __init__(self): super(ZeroBaseline, self).__init__() def get_param_values(self, **kwargs): """ Returns the parameter values of the baseline object Returns: (None): coefficients of the baseline """ return None def set_param_values(self, value, **kwargs): """ Sets the parameter values of the baseline object Args: value (None): coefficients of the baseline """ pass def fit(self, paths, **kwargs): """ Improves the quality of zeroes output by baseline Args: paths: list of paths """ pass def predict(self, path): """ Produces some zeroes Args: path (dict): dict of lists/numpy array containing trajectory / path information such as "observations", "rewards", ... Returns: (np.ndarray): numpy array of the same length as paths["observations"] specifying the reward baseline """ return np.zeros_like(path["rewards"])
[ { "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
maml_zoo/baselines/zero_baseline.py
intel-isl/MetaLearningTradeoffs
import functools from tornado.routing import PathMatches from core import PipelineDelegate class MethodMatches(PathMatches): """Matches request path and maethod.""" def __init__(self, path_pattern, method: str): super().__init__(path_pattern) self.method = method.upper() def match(self, request): result = super().match(request) if result is not None: if request.method.upper() != self.method: return None return result class Router: _routes = [] def __call__(self, path: str, name=None, method: str = None): def wrapper(func): if method is None: self._routes.append((path, PipelineDelegate, {'delegate': func}, name)) else: self._routes.append((MethodMatches(path, method), PipelineDelegate, {'delegate': func}, name)) return func return wrapper get = functools.partialmethod(__call__, method='GET') post = functools.partialmethod(__call__, method='POST') put = functools.partialmethod(__call__, method='PUT') patch = functools.partialmethod(__call__, method='PATCH') delete = functools.partialmethod(__call__, method='DELETE') def get_routes(self): return tuple(self._routes) route = Router()
[ { "point_num": 1, "id": "all_function_names_snake_case", "question": "Are all function names in this file written in snake_case?", "answer": true }, { "point_num": 2, "id": "has_multiple_inheritance", "question": "Does any class in this file use multiple inheritance?", "answer": ...
3
routing.py
kingfozhou/tornado-middleware
from .functions import open_uri_with_browser from .image_processing import get_colored_image_base64_by_region from .settings import get_setting from .shared import global_get from .types import ImageDict import sublime POPUP_TEMPLATE = """ <body id="open-uri-popup"> <style> img {{ width: {w}{size_unit}; height: {h}{size_unit}; }} </style> <a href="{uri}"><img src="data:{mime};base64,{base64}"></a> {text_html} </body> """ def generate_popup_html(view: sublime.View, uri_region: sublime.Region) -> str: img: ImageDict = global_get("images.popup") base_size = 2.5 return POPUP_TEMPLATE.format( uri=sublime.html_format_command(view.substr(uri_region)), mime=img["mime"], w=base_size * img["ratio_wh"], h=base_size, size_unit="em", base64=get_colored_image_base64_by_region("popup", uri_region), text_html=get_setting("popup_text_html"), ) def show_popup(view: sublime.View, uri_region: sublime.Region, point: int) -> None: view.show_popup( generate_popup_html(view, uri_region), flags=sublime.COOPERATE_WITH_AUTO_COMPLETE | sublime.HIDE_ON_MOUSE_MOVE_AWAY, location=point, max_width=500, on_navigate=open_uri_with_browser, )
[ { "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
plugin/popup.py
jfcherng/Sublime-OpenUriInBrowser
import requests from requests.adapters import HTTPAdapter from requests.packages.urllib3.util.retry import Retry from pagarme import sdk def headers(): _headers = { 'User-Agent': 'pagarme-python/{}'.format(sdk.VERSION), 'X-PagarMe-User-Agent': 'pagarme-python/{}'.format(sdk.VERSION) } return _headers def requests_retry_session( retries=3, backoff_factor=0.3, status_forcelist=(500, 502, 504), session=None, ): session = session or requests.Session() session.headers.update(headers()) retry = Retry( total=retries, read=retries, connect=retries, backoff_factor=backoff_factor, status_forcelist=status_forcelist, ) adapter = HTTPAdapter(max_retries=retry) session.mount('https://', adapter) return session
[ { "point_num": 1, "id": "every_function_has_docstring", "question": "Does every function in this file have a docstring?", "answer": false }, { "point_num": 2, "id": "no_function_exceeds_5_params", "question": "Does every function in this file take 5 or fewer parameters (excluding sel...
3
pagarme/resources/requests_retry.py
pythonprobr/pagarme-python
"""For entities that have a parameter template.""" from gemd.entity.link_by_uid import LinkByUID from gemd.entity.setters import validate_list from gemd.entity.template.base_template import BaseTemplate from gemd.entity.template.parameter_template import ParameterTemplate class HasParameterTemplates(object): """ Mixin-trait for entities that include parameter templates. Parameters ---------- parameters: List[ParameterTemplate] A list of this entity's parameter templates. """ def __init__(self, parameters): self._parameters = None self.parameters = parameters @property def parameters(self): """ Get the list of parameter templates. Returns ------- List[ParameterTemplate] List of this entity's parameter templates """ return self._parameters @parameters.setter def parameters(self, parameters): lst = validate_list(parameters, (ParameterTemplate, LinkByUID, list, tuple)) # make sure attribute can be a Parameter # TODO: list.map(_.validate_scope(AttributeType.PARAMETER)) all true self._parameters = list(map(BaseTemplate._homogenize_ranges, lst))
[ { "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
gemd/entity/template/has_parameter_templates.py
lkubie/gemd-python
import os import imageio import numpy as np from PIL import Image from torch.autograd import Variable from torchvision.utils import save_image def create_gif(image_path): frames = [] gif_name = os.path.join("images", 'mnist1.gif') image_list = os.listdir(image_path) sorted(image_list) for image_name in image_list: frames.append(imageio.imread(os.path.join(image_path, image_name))) imageio.mimsave(gif_name, frames, 'GIF', duration=0.1) def resize_img(path): names = os.listdir(path) for name in names: img_path = os.path.join(path, name) img = Image.open(img_path) img = img.resize((172, 172)) img.save(img_path) def sample_image(opt, n_row, batches_done, generator, FloatTensor, LongTensor): z = Variable(FloatTensor(np.random.normal(0, 1, (n_row ** 2, opt.latent_dim)))) labels = np.array([num for _ in range(n_row) for num in range(n_row)]) labels = Variable(LongTensor(labels)) gen_imgs = generator(z, labels) save_image(gen_imgs.data, "images/%d.png" % batches_done, nrow=n_row, normalize=True) if __name__ == "__main__": image_path = "images/example1" resize_img(image_path) create_gif(image_path)
[ { "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
cgan/utils.py
GodWriter/GAN-Pytorch
from logbunker.contexts.bunker.logs.domain.LogRepository import LogRepository from logbunker.contexts.bunker.logs.domain.entities.Log import Log from logbunker.contexts.bunker.logs.domain.entities.LogContent import LogContent from logbunker.contexts.bunker.logs.domain.entities.LogCreationDate import LogCreationDate from logbunker.contexts.bunker.logs.domain.entities.LogId import LogId from logbunker.contexts.bunker.logs.domain.entities.LogLevel import LogLevel from logbunker.contexts.bunker.logs.domain.entities.LogOrigin import LogOrigin from logbunker.contexts.bunker.logs.domain.entities.LogTrace import LogTrace from logbunker.contexts.bunker.logs.domain.entities.LogType import LogType from logbunker.contexts.shared.domain.EventBus import EventBus class LogCreator: def __init__(self, log_repository: LogRepository, event_bus: EventBus): self.__log_repository = log_repository self.__event_bus = event_bus async def run( self, log_id: LogId, content: LogContent, level: LogLevel, origin: LogOrigin, log_type: LogType, trace: LogTrace, creation_date: LogCreationDate, ): log: Log = Log.create(log_id, content, level, origin, log_type, trace, creation_date) await self.__log_repository.create_one(log) await self.__event_bus.publish(log.pull_domain_events())
[ { "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
logbunker/contexts/bunker/logs/application/createone/LogCreator.py
parada3desu/logbunker
import pandas as pd from opinion import config, utils def transform_url(df): df['media_source'] = df['media_source'].apply( lambda x: x.replace('https', 'http') ) return df def process_url(url): try: domain, path = utils.parse_url(url) return domain except ValueError as e: print(e, url) return 'na' def main(): df_top50 = pd.read_csv(config.data / 'media_sources.csv') df_all = pd.read_csv(config.data / 'all_media.csv', index_col=0) df_all['url'] = df_all['url'].apply(process_url) df_top50['media_source'] = df_top50['media_source'].apply(process_url) df_merged = pd.merge(df_top50, df_all, how='left', left_on='media_source', right_on='url') df_merged = df_merged[['media_source', 'has_opinion', 'media_id', 'name']] df_merged.to_csv(config.data / 'media_with_ids.csv', index=False) if __name__ == '__main__': main()
[ { "point_num": 1, "id": "all_function_names_snake_case", "question": "Are all function names in this file written in snake_case?", "answer": true }, { "point_num": 2, "id": "every_function_has_docstring", "question": "Does every function in this file have a docstring?", "answer":...
3
src/0_test_corpus/01_match_media_ids.py
benlevyx/opinion-vs-fact
import csv import sys def orderEdges(fileName): dynamic_dependencies_file = open(fileName) csv_reader = csv.reader(dynamic_dependencies_file) list_of_edges = [] for row in csv_reader: list_of_edges.append(row[0].split()) sortedList = insertionSort(list_of_edges) return sortedList def writeCSV(sortedList, fileName): with open(fileName, "w") as f: writer = csv.writer(f) writer.writerows(sortedList) def insertionSort(list_of_values): for i in range(len(list_of_values)): j = findMin(i, list_of_values) list_of_values[i], list_of_values[j] = list_of_values[j], list_of_values[i] return list_of_values def findMin(i, list_of_values): smallest_value = int(list_of_values[i][2]) index = i for j in range(i, len(list_of_values)): if int(list_of_values[j][2]) < smallest_value: index = j smallest_value = int(list_of_values[j][2]) return index if __name__ == "__main__": fileName = sys.argv[1] sortedList = orderEdges(fileName) writeCSV(sortedList, 'sorted_edges.csv')
[ { "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
mono2micro/ebc-application/ebc-data_dependencies/dynamic_dependencies/order_dependencies.py
jahn18/Normalized-TurboMQ
#! /usr/bin/env python3 """ Bishbot - https://github.com/ldgregory/bishbot Leif Gregory <leif@devtek.org> space.py v0.1 Tested to Python v3.7.3 Description: Bot commands for the Space channel Changelog: 20200603 - Initial code Copyright 2020 Leif Gregory Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ import json import requests from discord.ext import commands class Space(commands.Cog): def __init__(self, bot): self.bot = bot # Events @commands.Cog.listener() async def on_ready(self): print('- Space Cog loaded') @commands.command(name='launches', description='Show the next five launches', help='Show the next five launches', ignore_extra=True, hidden=False, enabled=True) async def launches(self, ctx): response = requests.get('https://fdo.rocketlaunch.live/json/launches/next/5') data = json.loads(response.text) launches = '**Here are the next five launches**\n\n' for result in data['result']: launches += f"- {result['quicktext']}\n" await ctx.channel.send(launches) def setup(bot): bot.add_cog(Space(bot))
[ { "point_num": 1, "id": "all_function_names_snake_case", "question": "Are all function names in this file written in snake_case?", "answer": true }, { "point_num": 2, "id": "no_function_exceeds_5_params", "question": "Does every function in this file take 5 or fewer parameters (exclu...
3
cogs/space.py
ldgregory/bishbot
from re import search from base64 import b64decode from email.message import Message class mimetest: def __init__(self, mime): self.mime = mime assert not mime.defects def __getitem__(self, header): return self.mime[header] @property def transfer_encoding(self): return self['Content-Transfer-Encoding'] @property def encoding(self): return self.mime.get_content_charset(None) @property def mimetype(self): return self.mime.get_content_type() @property def payload(self): payload = self.mime.get_payload().encode(self.encoding or 'ascii') if self.transfer_encoding == 'base64': return b64decode(payload) return payload @property def parts(self): payload = self.mime.get_payload() if not isinstance(payload, list): raise TypeError return [mimetest(k) for k in payload] def blank(): return Message()
[ { "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
tests/mimetest.py
seantis/mailthon
# Copyright (C) 2015 Google Inc., authors, and contributors <see AUTHORS file> # Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file> # Created By: anze@reciprocitylabs.com # Maintained By: anze@reciprocitylabs.com """Add finished/verified dates to cycle tasks Revision ID: 13e52f6a9deb Revises: 18bdb0671010 Create Date: 2016-01-04 13:52:43.017848 """ from alembic import op import sqlalchemy as sa from sqlalchemy.dialects import mysql # revision identifiers, used by Alembic. revision = '13e52f6a9deb' down_revision = '18bdb0671010' def upgrade(): op.add_column('cycle_task_group_object_tasks', sa.Column('finished_date', sa.DateTime(), nullable=True)) op.add_column('cycle_task_group_object_tasks', sa.Column('verified_date', sa.DateTime(), nullable=True)) op.execute(""" UPDATE cycle_task_group_object_tasks SET finished_date = updated_at WHERE status = "Finished" """) op.execute(""" UPDATE cycle_task_group_object_tasks SET verified_date = updated_at, finished_date = updated_at WHERE status = "Verified" """) def downgrade(): op.drop_column('cycle_task_group_object_tasks', 'verified_date') op.drop_column('cycle_task_group_object_tasks', 'finished_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": "every_function_under_20_lines", "question": "Is every function in this file shorter than 20 lines?", "answer": tru...
3
src/ggrc_workflows/migrations/versions/20160104135243_13e52f6a9deb_add_finished_verified_dates_to_cycle_.py
Smotko/ggrc-core
############################################################################### # # Tests for XlsxWriter. # # Copyright (c), 2013-2020, John McNamara, jmcnamara@cpan.org # from ..excel_comparison_test import ExcelComparisonTest from ...workbook import Workbook class TestCompareXLSXFiles(ExcelComparisonTest): """ Test file created by XlsxWriter against a file created by Excel. """ def setUp(self): self.set_filename('chart_column07.xlsx') def test_create_file(self): """Test the creation of a simple XlsxWriter file.""" workbook = Workbook(self.got_filename) worksheet = workbook.add_worksheet() chart = workbook.add_chart({'type': 'column'}) chart.axis_ids = [68810240, 68811776] data = [ [1, 2, 3, 4, 5], [2, 4, 6, 8, 10], [3, 6, 9, 12, 15], ] worksheet.write_column('A1', data[0]) worksheet.write_column('B1', data[1]) worksheet.write_column('C1', data[2]) chart.add_series({ 'values': '=(Sheet1!$A$1:$A$2,Sheet1!$A$4:$A$5)', 'values_data': [1, 2, 4, 5], }) worksheet.insert_chart('E9', chart) workbook.close() self.assertExcelEqual()
[ { "point_num": 1, "id": "has_multiple_inheritance", "question": "Does any class in this file use multiple inheritance?", "answer": false }, { "point_num": 2, "id": "has_nested_function_def", "question": "Does this file contain any function defined inside another function?", "answ...
3
xlsxwriter/test/comparison/test_chart_column07.py
dthadi3/XlsxWriter
# 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 class GetConsoleInfoRequest(RpcRequest): def __init__(self): RpcRequest.__init__(self, 'UniMkt', '2018-12-07', 'GetConsoleInfo') self.set_protocol_type('https') self.set_method('POST') def get_Message(self): return self.get_body_params().get('Message') def set_Message(self,Message): self.add_body_params('Message', Message)
[ { "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
aliyun-python-sdk-unimkt/aliyunsdkunimkt/request/v20181207/GetConsoleInfoRequest.py
liumihust/aliyun-openapi-python-sdk
import heapq import rx class PriorityQueue(object): """Priority queue for scheduling""" def __init__(self, capacity=None): self.items = [] self.count = 0 # Monotonic increasing for sort stability self.lock = rx.config.get("Lock")() def __len__(self): """Returns length of queue""" return len(self.items) def peek(self): """Returns first item in queue without removing it""" return self.items[0][0] def remove_at(self, index): """Removes item at given index""" with self.lock: item = self.items.pop(index)[0] heapq.heapify(self.items) return item def dequeue(self): """Returns and removes item with lowest priority from queue""" with self.lock: item = heapq.heappop(self.items)[0] return item def enqueue(self, item): """Adds item to queue""" with self.lock: heapq.heappush(self.items, (item, self.count)) self.count += 1 def remove(self, item): """Remove given item from queue""" with self.lock: for index, _item in enumerate(self.items): if _item[0] == item: self.items.pop(index) heapq.heapify(self.items) return True return False
[ { "point_num": 1, "id": "no_function_exceeds_5_params", "question": "Does every function in this file take 5 or fewer parameters (excluding self/cls)?", "answer": true }, { "point_num": 2, "id": "more_functions_than_classes", "question": "Does this file define more functions than cla...
3
addons/Sprytile-6b68d00/rx/internal/priorityqueue.py
trisadmeslek/V-Sekai-Blender-tools
""" Helper functions to get information about the environment. """ import importlib.util import os as python_os import subprocess import sys as python_sys from typing import Any, Optional from homura.liblog import get_logger logger = get_logger("homura.environment") # Utility functions that useful libraries are available or not def is_accimage_available() -> bool: return importlib.util.find_spec("accimage") is not None def enable_accimage() -> None: if is_accimage_available(): import torchvision torchvision.set_image_backend("accimage") logger.info("accimage is activated") else: logger.warning("accimage is not available") def is_faiss_available() -> bool: _faiss_available = importlib.util.find_spec("faiss") is not None if _faiss_available: import faiss if not hasattr(faiss, 'StandardGpuResources'): logger.info("faiss is available but is not for GPUs") return _faiss_available def is_cupy_available() -> bool: return importlib.util.find_spec("cupy") is not None # get environment information def get_git_hash() -> str: def _decode_bytes(b: bytes) -> str: return b.decode("ascii")[:-1] try: is_git_repo = subprocess.run(["git", "rev-parse", "--is-inside-work-tree"], stdout=subprocess.PIPE, stderr=subprocess.DEVNULL).stdout except FileNotFoundError: return "" if _decode_bytes(is_git_repo) == "true": git_hash = subprocess.run(["git", "rev-parse", "--short", "HEAD"], stdout=subprocess.PIPE).stdout return _decode_bytes(git_hash) else: logger.info("No git info available in this directory") return "" def get_args() -> list: return python_sys.argv def get_environ(name: str, default: Optional[Any] = None ) -> str: return python_os.environ.get(name, default)
[ { "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
homura/utils/environment.py
Xiangyu-Han/homura
import pytest from portfolio_rebalance.skeleton import fib, main __author__ = "David Simmons" __copyright__ = "David Simmons" __license__ = "MIT" def test_fib(): """API Tests""" assert fib(1) == 1 assert fib(2) == 1 assert fib(7) == 13 with pytest.raises(AssertionError): fib(-10) def test_main(capsys): """CLI Tests""" # capsys is a pytest fixture that allows asserts agains stdout/stderr # https://docs.pytest.org/en/stable/capture.html main(["7"]) captured = capsys.readouterr() assert "The 7-th Fibonacci number is 13" in captured.out
[ { "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
tests/test_skeleton.py
desimmons/portfolio_rebalance
"""Provides functionality for ranking Records and their differences.""" from .db import sesh from .record import Record, RA from .difference import Diff, difference from .filter import filter_ from .exceptions import FilterMetricError def rank(date, metric, usernames=None, record_filters=None): """Rank the Records on the date by the metric.""" q = sesh.query(Record).filter(Record.date == date) if usernames: q = q.filter(Record.username.in_(usernames)) if record_filters: q = filter_(q, Record, record_filters) try: q = q.order_by(getattr(Record, metric).desc()) except AttributeError as e: raise FilterMetricError(f"Metric '{metric}' not in Record") from e return q def diffrank(date_a, date_b, metric, usernames=None, record_filters=None, diff_filters=None): """Rank the difference between Records on the date_a and date_b by the metric.""" q = difference(date_a, date_b, usernames) if record_filters: q = filter_(q, RA, record_filters) if diff_filters: q = filter_(q, Diff, diff_filters) try: q = q.order_by(getattr(Diff, metric).desc()) except AttributeError as e: raise FilterMetricError(f"Metric '{metric}' not in Diff") from e return q
[ { "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": false }, { "point_num": 2, "id": "has_nested_function_def", "question": "Does this file contain any function defined insi...
3
rwrtrack/rank.py
david-wm-sanders/rwrtrack
""" OpenAI Gym environments with predicted state vector of specified VisionToState model (data_id, model_name) as state @Author: Steffen Bleher """ from gym import spaces from gym_brt.data.config.configuration import FREQUENCY import numpy as np from gym_brt.envs.reinforcementlearning_extensions.vision_wrapping_classes import VisionQubeBeginDownEnv from visiontostate.vision_predictor import VisionPredictor OBS_MAX = np.asarray([1, 1, 1, 1, np.inf, np.inf], dtype=np.float64) class VtSQubeBeginDownEnv(VisionQubeBeginDownEnv): def __init__(self, data_id, model_name, frequency=FREQUENCY, batch_size=2048, use_simulator=False, simulation_mode='ode', encoder_reset_steps=int(1e8), no_image_normalization=False): super().__init__(frequency, batch_size, use_simulator, simulation_mode, encoder_reset_steps, no_image_normalization) self.observation_space = spaces.Box(-OBS_MAX, OBS_MAX, dtype=np.float32) self.predictor = VisionPredictor(data_id, model_name) def _get_state(self): image = super()._get_state() state = self.predictor.predict(image) return state[0:6]
[ { "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/statetoinput/state_estimator_wrapper.py
Data-Science-in-Mechanical-Engineering/furuta-pixel-to-torque-control
from AbstractObject import * class EOFObject(AbstractObject): def __init__(self, value): super(EOFObject, self).__init__(value) def generate(self, out_code): pass
[ { "point_num": 1, "id": "more_functions_than_classes", "question": "Does this file define more functions than classes?", "answer": true }, { "point_num": 2, "id": "every_function_has_docstring", "question": "Does every function in this file have a docstring?", "answer": false }...
3
src/fecc_object/EOFObject.py
castor91/fecc
from . import lexer from .parseRoll import parser def roll(expression : str): "Runs the dice expression provided and returns long form result" try: tree = parser.parse(expression) result, hist = tree.roll() except Exception as E: return str(E) return result, hist, tree def compile(expression : str): tree = parser.parse(expression) return tree try: from .rgrcog import RGR def setup(bot): bot.add_cog(RGR(bot)) except ModuleNotFoundError as e: def setup(bot): raise Exception(str(e), e) pass
[ { "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
rgr/__init__.py
Faxn/rgr
''' Camera Example ============== This example demonstrates a simple use of the camera. It shows a window with a buttoned labelled 'play' to turn the camera on and off. Note that not finding a camera, perhaps because gstreamer is not installed, will throw an exception during the kv language processing. ''' # Uncomment these lines to see all the messages # from kivy.logger import Logger # import logging # Logger.setLevel(logging.TRACE) from kivy.app import App from kivy.lang import Builder from kivy.uix.boxlayout import BoxLayout import time Builder.load_string(''' <CameraClick>: orientation: 'vertical' Camera: id: camera resolution: (640, 480) play: False ToggleButton: text: 'Play' on_press: camera.play = not camera.play size_hint_y: None height: '48dp' Button: text: 'Capture' size_hint_y: None height: '48dp' on_press: root.capture() ''') class CameraClick(BoxLayout): def capture(self): ''' Function to capture the images and give them the names according to their captured time and date. ''' camera = self.ids['camera'] timestr = time.strftime("%Y%m%d_%H%M%S") camera.export_to_png("IMG_" + timestr) print("Captured") class TestCamera(App): def build(self): return CameraClick() TestCamera().run()
[ { "point_num": 1, "id": "has_multiple_inheritance", "question": "Does any class in this file use multiple inheritance?", "answer": false }, { "point_num": 2, "id": "every_class_has_docstring", "question": "Does every class in this file have a docstring?", "answer": false }, {...
3
examples/camera/main.py
RiiotLabs/kivy
from passgen import args def test_num_words(): mock_argv = ['passgen', '-n', '22'] options = args.get_cli_options(mock_argv) assert 22 == options.num_words mock_argv = ['passgen', '--num-words', '33'] options = args.get_cli_options(mock_argv) assert 33 == options.num_words mock_argv = ['passgen'] options = args.get_cli_options(mock_argv) assert args.DEFAULT_NUM_WORDS == options.num_words def test_count(): mock_argv = ['passgen', '-c', '22'] options = args.get_cli_options(mock_argv) assert 22 == options.count mock_argv = ['passgen', '--count', '33'] options = args.get_cli_options(mock_argv) assert 33 == options.count mock_argv = ['passgen'] options = args.get_cli_options(mock_argv) assert args.DEFAULT_COUNT == options.count mock_argv = ['passgen', '--count', '-1'] # negative value ignored options = args.get_cli_options(mock_argv) assert args.DEFAULT_COUNT == options.count def test_min_chars(): mock_argv = ['passgen', '--min-chars', '33'] options = args.get_cli_options(mock_argv) assert 33 == options.min_chars mock_argv = ['passgen'] options = args.get_cli_options(mock_argv) assert args.DEFAULT_MIN_CHARS == options.min_chars def test_max_chars(): mock_argv = ['passgen', '--max-chars', '33'] options = args.get_cli_options(mock_argv) assert 33 == options.max_chars mock_argv = ['passgen'] options = args.get_cli_options(mock_argv) assert args.DEFAULT_MAX_CHARS == options.max_chars def test_conflicting_min_max_chars(): mock_argv = ['passgen', '--min-chars', '9999', '--max-chars', '11'] options = args.get_cli_options(mock_argv) assert 9999 == options.min_chars assert args.DEFAULT_MAX_CHARS == options.max_chars def test_get_defaults(): options = args.get_default_options() assert args.DEFAULT_COUNT == options.count
[ { "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
tests/test_args.py
rauljim/passgen
import unittest from programy.utils.logging.ylogger import YLoggerSnapshot class YLoggerSnapshotTests(unittest.TestCase): def test_snapshot_with_defaults(self): snapshot = YLoggerSnapshot() self.assertIsNotNone(snapshot) self.assertEquals("Critical(0) Fatal(0) Error(0) Exception(0) Warning(0) Info(0), Debug(0)", str(snapshot)) self.assertEqual({'criticals': 0, 'debugs': 0, 'errors': 0, 'exceptions': 0, 'fatals': 0, 'infos': 0, 'warnings': 0}, snapshot.to_json()) def test_snapshot_without_defaults(self): snapshot = YLoggerSnapshot(criticals=1, fatals=2, errors=3, exceptions=4, warnings=5, infos=6, debugs=7) self.assertIsNotNone(snapshot) self.assertEquals("Critical(1) Fatal(2) Error(3) Exception(4) Warning(5) Info(6), Debug(7)", str(snapshot)) self.assertEqual({'criticals': 1, 'debugs': 7, 'errors': 3, 'exceptions': 4, 'fatals': 2, 'infos': 6, 'warnings': 5}, snapshot.to_json())
[ { "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
test/programytest/utils/logging/test_snapshot.py
cdoebler1/AIML2
def decorate(func): def decorated(): print("==" * 20) print("before") func() print("after") return decorated @decorate def target(): print("target 함수") target() ## output """ ======================================== before target 함수 after """ def target2(): print("target2 함수 실행함") target2 = decorate(target2) target2() ## output """ ======================================== before target2 함수 실행함 after """
[ { "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
decorator_example/deco1.py
wapj/pyconkr2019
""" Core mail sender""" from django.template.loader import render_to_string from django.core.mail import EmailMessage class SendMail: """ Send email to user """ def __init__(self, template_name, context, to, subject="Awesome Blog API", request=None): self.template_name = template_name self.context = context self.to = to self.subject = subject self.request = request def send(self): """ Send mail. """ message = render_to_string( self.template_name, context=self.context, request=self.request) mail = EmailMessage( subject=self.subject, body=message, to=self.to ) mail.content_subtype = "html" mail.send()
[ { "point_num": 1, "id": "no_function_exceeds_5_params", "question": "Does every function in this file take 5 or fewer parameters (excluding self/cls)?", "answer": true }, { "point_num": 2, "id": "every_function_under_20_lines", "question": "Is every function in this file shorter than...
3
authors/apps/core/email.py
Tittoh/blog-API
# Created by DraX on 2005.08.08 import sys from ru.catssoftware.gameserver.model.quest import State from ru.catssoftware.gameserver.model.quest import QuestState from ru.catssoftware.gameserver.model.quest.jython import QuestJython as JQuest qn = "30031_biotin_occupation_change" HIGH_PRIEST_BIOTIN = 30031 class Quest (JQuest) : def __init__(self,id,name,descr): JQuest.__init__(self,id,name,descr) def onEvent (self,event,st): htmltext = event return htmltext def onTalk (Self,npc,player): st = player.getQuestState(qn) npcId = npc.getNpcId() Race = st.getPlayer().getRace() ClassId = st.getPlayer().getClassId() # Humans got accepted if npcId == HIGH_PRIEST_BIOTIN and Race in [Race.Human]: if ClassId in [ClassId.fighter, ClassId.warrior, ClassId.knight, ClassId.rogue]: htmltext = "30031-08.htm" if ClassId in [ClassId.warlord, ClassId.paladin, ClassId.treasureHunter]: htmltext = "30031-08.htm" if ClassId in [ClassId.gladiator, ClassId.darkAvenger, ClassId.hawkeye]: htmltext = "30031-08.htm" if ClassId in [ClassId.wizard, ClassId.cleric]: htmltext = "30031-06.htm" if ClassId in [ClassId.sorceror, ClassId.necromancer, ClassId.warlock, ClassId.bishop, ClassId.prophet]: htmltext = "30031-07.htm" else: htmltext = "30031-01.htm" return htmltext # All other Races must be out if npcId == HIGH_PRIEST_BIOTIN and Race in [Race.Dwarf, Race.Darkelf, Race.Elf, Race.Orc]: st.exitQuest(1) return "30031-08.htm" QUEST = Quest(30031,qn,"village_master") QUEST.addStartNpc(30031) QUEST.addTalkId(30031)
[ { "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
game/data/scripts/village_master/30031_biotin_occupation_change/__init__.py
TheDemonLife/Lineage2Server-Interlude
# coding: utf-8 """ Kubernetes No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) OpenAPI spec version: v1.12.2 Generated by: https://github.com/swagger-api/swagger-codegen.git """ from __future__ import absolute_import import os import sys import unittest import kubernetes.client from kubernetes.client.rest import ApiException from kubernetes.client.models.v1_cluster_role_binding import V1ClusterRoleBinding class TestV1ClusterRoleBinding(unittest.TestCase): """ V1ClusterRoleBinding unit test stubs """ def setUp(self): pass def tearDown(self): pass def testV1ClusterRoleBinding(self): """ Test V1ClusterRoleBinding """ # FIXME: construct object with mandatory attributes with example values #model = kubernetes.client.models.v1_cluster_role_binding.V1ClusterRoleBinding() pass if __name__ == '__main__': unittest.main()
[ { "point_num": 1, "id": "every_function_has_docstring", "question": "Does every function in this file have a docstring?", "answer": false }, { "point_num": 2, "id": "all_function_names_snake_case", "question": "Are all function names in this file written in snake_case?", "answer"...
3
kubernetes/test/test_v1_cluster_role_binding.py
sgwilliams-ebsco/python
import Inline import Core import web info = { "friendly_name": "Attachment", "example_template": "pagename:attachmentname", "summary": "Links to an attachment of this (or another, named) page.", "details": """ <p>If invoked as [attachment some.filename], it will either embed (if the attachment is an image) or link to (otherwise) the named attachment. If invoked as [attachment PageName:some.filename], it will do the same, but for the named attachment on the named page instead of the current page.</p> """ } def SpanHandler(rest, acc): (text, rest) = Inline.collectSpan(rest) parts = text.split('/', 1) name = parts[0] pagename = '' if name.find(':') != -1: (pagename, name) = name.split(':', 1) if not pagename: pagename = web.ctx.source_page_title if len(parts) > 1: alt = parts[1] else: alt = '[Attachment ' + pagename + ':' + name + ']' a = Core.Attachment(pagename, name, None) acc.append(AttachmentReference(a, alt)) return rest class AttachmentReference(Core.Renderable): def __init__(self, attachment, alt): self.attachment = attachment self.alt = alt def templateName(self): return 'pyle_attachmentreference'
[ { "point_num": 1, "id": "has_multiple_inheritance", "question": "Does any class in this file use multiple inheritance?", "answer": false }, { "point_num": 2, "id": "all_params_annotated", "question": "Does every function parameter in this file have a type annotation (excluding self/c...
3
lib/rabbitmq-dotnet-client-rabbitmq_v3_4_4/docs/pyle2-fcfcf7e/spanhandlers/attachment.py
CymaticLabs/Unity3d.Amqp
#!/usr/bin/env python3 import sys sys.path.insert(0, "../lib-ext") sys.path.insert(0, "..") import unittest from omron_2jcie_bu01 import Omron2JCIE_BU01 class BLENotificationTestCase(unittest.TestCase): ADDRESS = None @classmethod def setUpClass(cls): sensor = Omron2JCIE_BU01.ble() cls.ADDRESS = sensor.address print(f"Target HW address: {cls.ADDRESS}") def setUp(self): self.sensor = Omron2JCIE_BU01.ble(self.ADDRESS) def tearDown(self): pass def test_notify(self): def callback(sender, tpl): print(f"{sender} {tpl}") self.sensor.start_notify(0x5012, callback) self.sensor.start_notify(0x5013, callback) self.sensor.sleep(5) self.sensor.stop_notify(0x5012) self.sensor.stop_notify(0x5013) 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": true }, { "point_num": 2, "id": "all_function_names_snake_case", "question": "Are all function names in this file written in snake_case?", ...
3
test/test_notify.py
nobrin/omron-2jcie-bu01
from fastapi import FastAPI, HTTPException from pydantic import BaseModel from src.build_model import convert, predict app = FastAPI() # pydantic models class StockIn(BaseModel): ticker: str class StockOut(StockIn): forecast: dict # routes @app.get("/ping") async def pong(): return {"ping": "pong!"} @app.post("/predict", response_model=StockOut, status_code=200) def get_prediction(payload: StockIn): ticker = payload.ticker prediction_list = predict(ticker) if not prediction_list: raise HTTPException(status_code=400, detail="Model not found.") response_object = {"ticker": ticker, "forecast": convert(prediction_list)} return response_object
[ { "point_num": 1, "id": "has_multiple_inheritance", "question": "Does any class in this file use multiple inheritance?", "answer": false }, { "point_num": 2, "id": "every_function_has_docstring", "question": "Does every function in this file have a docstring?", "answer": false ...
3
main.py
benayas1/FastAPI-demo
from rest_framework import serializers from profiles_api import models class HelloSerializer (serializers.Serializer): """Serializes a name field for testing our APIView""" name = serializers.CharField(max_length=10) class UserProfileSerializer(serializers.ModelSerializer): """Serializes a user profile object""" class Meta: model = models.UserProfile fields = ('id', 'email', 'name', 'password') extra_kwargs = { 'password' :{ 'write_only' : True, 'style': {'input_type': 'password'} } } def create(self, validated_data): """Create and return a new user""" user = models.UserProfile.objects.create_user( email=validated_data['email'], name=validated_data['name'], password=validated_data['password'] ) return user class ProfileFeedItemSerializer(serializers.ModelSerializer): """Serializes profile feed items""" class Meta: model = models.ProfileFeedItem fields = ('id', 'user_profile', 'status_text', 'created_on') extra_kwargs = {'user_profile:': {'read_only': True}}
[ { "point_num": 1, "id": "more_functions_than_classes", "question": "Does this file define more functions than classes?", "answer": false }, { "point_num": 2, "id": "has_multiple_inheritance", "question": "Does any class in this file use multiple inheritance?", "answer": false }...
3
profiles_api/serializers.py
danisuram/profiles-rest-api
""" Sprawdz czy istnieje permutacja danego slowa bedaca palindromem. """ # Wersja 1 def znajdz_permutacje(napis, start, koniec, wynik=[]): if start >= koniec: if "".join(napis) not in wynik: wynik.append("".join(napis)) else: for i in range(start, koniec): napis[start], napis[i] = napis[i], napis[start] znajdz_permutacje(napis, start + 1, koniec, wynik) napis[start], napis[i] = napis[i], napis[start] return wynik def czy_palindrom(slowo): for i in range(len(slowo) // 2): if slowo[i] != slowo[-i - 1]: return False return True def czy_istnieje_permutacja_bedaca_palindromem_v1(slowo): permutacje = znajdz_permutacje(list(slowo), 0, len(slowo)) wynik = [] for p in permutacje: if czy_palindrom(p): wynik.append(p) return wynik # testy poprawnosci slowo = "adamm" wynik = ["madam", "amdma"] assert sorted(czy_istnieje_permutacja_bedaca_palindromem_v1(slowo)) == sorted(wynik)
[ { "point_num": 1, "id": "all_params_annotated", "question": "Does every function parameter in this file have a type annotation (excluding self/cls)?", "answer": false }, { "point_num": 2, "id": "every_function_has_docstring", "question": "Does every function in this file have a docst...
3
src/Python/12_Napisy_anagramy_palindromy/Zad6.py
djeada/Nauka-programowania
#author: Christoffer Norell #contact: christoffernorell@yahoo.se #This is a simple simulator of a deck of cards I made for fun. #The values in the dictionaries are there for better comparison during games. import random #Using dictionaries to represent values. #The color-values was taken from bridge-order: #http://pokerterms.com/bridge-order.html colors = [{'Hearts': 0 },{'Diamonds': 1},{'Clubs': 2},{'Spades':3}] values = [{'Two':2},{'Three': 3},{'Four':4},{'Five':5},{'Six': 6},{'Seven': 7}, {'Eight': 8}, {'Nine': 9} , {'Ten': 10},{'Jack': 11} , {'Queen':12}, {'King':13} , {'Ace':14}] class Card(): def __init__(self,value,color): self.color = color self.value = value def show(self): return (self.color, self.value) class Deck(): def __init__(self): self.deck = [] for x in range(len(colors)): for y in range(len(values)): self.deck.append(Card(colors[x],values[y])) def shuffle(self): random.shuffle(self.deck) def hand_card(self): card = self.deck.pop() return card def hand_cards(self, amount): tmp = [] if amount <= len(self.deck): for x in range(amount): tmp.append(self.hand_card()) return tmp else: print("out of cards") return None
[ { "point_num": 1, "id": "every_function_under_20_lines", "question": "Is every function in this file shorter than 20 lines?", "answer": true }, { "point_num": 2, "id": "all_params_annotated", "question": "Does every function parameter in this file have a type annotation (excluding se...
3
DeckOfCards.py
crippe-90/DeckOfCards
from typing import Union, Optional from slack_sdk.models import JsonObject class SocketModeResponse: envelope_id: str payload: dict def __init__( self, envelope_id: str, payload: Optional[Union[dict, JsonObject, str]] = None ): self.envelope_id = envelope_id if payload is None: self.payload = None elif isinstance(payload, JsonObject): self.payload = payload.to_dict() elif isinstance(payload, dict): self.payload = payload elif isinstance(payload, str): self.payload = {"text": payload} else: raise ValueError(f"Unsupported payload data type ({type(payload)})") def to_dict(self) -> dict: # skipcq: PYL-W0221 d = {"envelope_id": self.envelope_id} if self.payload is not None: d["payload"] = self.payload return d
[ { "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
slack_sdk/socket_mode/response.py
priya1puresoftware/python-slack-sdk
from topaz.astcompiler import SymbolTable from topaz.module import ClassDef from topaz.objects.objectobject import W_Object class W_BindingObject(W_Object): classdef = ClassDef("Binding", W_Object.classdef) _immutable_fields_ = ["names[*]", "cells[*]", "w_self", "lexical_scope"] def __init__(self, space, names, cells, w_self, lexical_scope): W_Object.__init__(self, space) self.names = names self.cells = cells self.w_self = w_self self.lexical_scope = lexical_scope classdef.undefine_allocator() @classdef.method("eval", source="str") def method_eval(self, space, source): symtable = SymbolTable() for name in self.names: symtable.cells[name] = symtable.FREEVAR bc = space.compile(source, "(eval)", symtable=symtable) frame = space.create_frame(bc, w_self=self.w_self, lexical_scope=self.lexical_scope) for idx, cell in enumerate(self.cells): frame.cells[idx + len(bc.cellvars)] = cell with space.getexecutioncontext().visit_frame(frame): return space.execute_frame(frame, bc)
[ { "point_num": 1, "id": "no_function_exceeds_5_params", "question": "Does every function in this file take 5 or fewer parameters (excluding self/cls)?", "answer": true }, { "point_num": 2, "id": "has_multiple_inheritance", "question": "Does any class in this file use multiple inherit...
3
topaz/objects/bindingobject.py
ruby-compiler-survey/topaz
import django from django import template from django_countries.fields import Country, countries register = template.Library() simple_tag = register.simple_tag @simple_tag def get_country(code): return Country(code=code) @simple_tag def get_countries(): return list(countries)
[ { "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
django_countries/templatetags/countries.py
domdinicola/django-countries
from flask import Blueprint, render_template, redirect, request from flask_login import current_user from app.models import EditableHTML from app.main.forms import HabitForm from app.models import Habit from app import db, csrf main = Blueprint('main', __name__) @main.route('/') def index(): if current_user.is_authenticated: return redirect('/daily') else: editable_html_obj = EditableHTML.get_editable_html('index') return render_template( 'main/index.html', editable_html_obj=editable_html_obj) @csrf.exempt @main.route('/daily', methods=['GET', 'POST']) def daily(): editable_html_obj = EditableHTML.get_editable_html('daily') if request.method == 'POST': data = request.get_json() id = int(data['id']) habit = Habit.query.get(id) habit.complete = data['complete'] db.session.commit() habits = current_user.habits return render_template( 'main/daily.html', editable_html_obj=editable_html_obj, habits=habits) @main.route('/monthly') def monthly(): editable_html_obj = EditableHTML.get_editable_html('monthly') return render_template( 'main/monthly.html', editable_html_obj=editable_html_obj) @main.route('/habits') def habits(): editable_html_obj = EditableHTML.get_editable_html('habits') habits = current_user.habits return render_template( 'main/habits.html', editable_html_obj=editable_html_obj, habits=habits) @main.route('/add-habit', methods=['GET', 'POST']) def add_habit(): form = HabitForm() if form.validate_on_submit(): habit = Habit(description=form.description.data, complete=form.complete.data, parent_id=current_user.id) db.session.add(habit) db.session.commit() return redirect('/habits') return render_template('main/add_habit.html', form=form) @main.route('/habit/<curr_habit>', methods=['GET', 'POST']) def view_habit(curr_habit): return render_template('main/habit_info.html', habit=curr_habit)
[ { "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
app/main/views.py
melissa-gu/habit_tracker
import random from ansible_collections.community.general.tests.unit.compat import unittest from ansible_collections.community.general.plugins.module_utils.cloud import _exponential_backoff, \ _full_jitter_backoff class ExponentialBackoffStrategyTestCase(unittest.TestCase): def test_no_retries(self): strategy = _exponential_backoff(retries=0) result = list(strategy()) self.assertEqual(result, [], 'list should be empty') def test_exponential_backoff(self): strategy = _exponential_backoff(retries=5, delay=1, backoff=2) result = list(strategy()) self.assertEqual(result, [1, 2, 4, 8, 16]) def test_max_delay(self): strategy = _exponential_backoff(retries=7, delay=1, backoff=2, max_delay=60) result = list(strategy()) self.assertEqual(result, [1, 2, 4, 8, 16, 32, 60]) def test_max_delay_none(self): strategy = _exponential_backoff(retries=7, delay=1, backoff=2, max_delay=None) result = list(strategy()) self.assertEqual(result, [1, 2, 4, 8, 16, 32, 64]) class FullJitterBackoffStrategyTestCase(unittest.TestCase): def test_no_retries(self): strategy = _full_jitter_backoff(retries=0) result = list(strategy()) self.assertEqual(result, [], 'list should be empty') def test_full_jitter(self): retries = 5 seed = 1 r = random.Random(seed) expected = [r.randint(0, 2**i) for i in range(0, retries)] strategy = _full_jitter_backoff( retries=retries, delay=1, _random=random.Random(seed)) result = list(strategy()) self.assertEqual(result, expected)
[ { "point_num": 1, "id": "has_multiple_inheritance", "question": "Does any class in this file use multiple inheritance?", "answer": false }, { "point_num": 2, "id": "has_nested_function_def", "question": "Does this file contain any function defined inside another function?", "answ...
3
exercises/networking_selfpaced/networking-workshop/collections/ansible_collections/community/general/tests/unit/module_utils/cloud/test_backoff.py
tr3ck3r/linklight
from opencage.geocoder import _query_for_reverse_geocoding def _expected_output(input_latlng, expected_output): # pylint: disable=no-self-argument def test(): lat, lng = input_latlng assert _query_for_reverse_geocoding(lat, lng) == expected_output return test def test_reverse(): _expected_output((10, 10), "10,10") _expected_output((10.0, 10.0), "10.0,10.0") _expected_output((0.000002, -120), "0.000002,-120") _expected_output((2.000002, -120), "2.000002,-120") _expected_output((2.000002, -120.000002), "2.000002,-120.000002") _expected_output((2.000002, -1.0000002), "2.000002,-1.0000002") _expected_output((2.000002, 0.0000001), "2.000002,0.0000001") _expected_output(("2.000002", "-120"), "2.000002,-120")
[ { "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
test/test_reverse.py
mtmail/python-opencage-geocoder
#!/usr/bin/env python from golbase import GameOfLifeBase, Cell import random import time import logging class GameOfLifeBlockSwitch(GameOfLifeBase): def __init__(self, *args, **kwargs): super(GameOfLifeBlockSwitch, self).__init__(*args, **kwargs) self.toroidal = True def run(self): self.initializeCells() y = 15 x = 8 self.cells[x + 11][y + 6].alive = True self.cells[x + 13][y + 6].alive = True self.cells[x + 13][y + 5].alive = True self.cells[x + 15][y + 4].alive = True self.cells[x + 15][y + 3].alive = True self.cells[x + 15][y + 2].alive = True self.cells[x + 17][y + 3].alive = True self.cells[x + 17][y + 2].alive = True self.cells[x + 17][y + 1].alive = True self.cells[x + 18][y + 2].alive = True while True: self.drawCells() self.canvas = self.matrix.SwapOnVSync(self.canvas) time.sleep(0.3) self.evolve() # Main function if __name__ == "__main__": gol = GameOfLifeBlockSwitch() if (not gol.process()): gol.print_help()
[ { "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": false...
3
pubsub/animation/gol-block-switch.py
yanigisawa/coffee-scale
from django.contrib.auth import user_logged_out from djet import assertions, restframework from rest_framework import status import djoser.constants import djoser.utils import djoser.views from .common import create_user class TokenDestroyViewTest(restframework.APIViewTestCase, assertions.StatusCodeAssertionsMixin): view_class = djoser.views.TokenDestroyView def setUp(self): self.signal_sent = False def signal_receiver(self, *args, **kwargs): self.signal_sent = True def test_post_should_logout_logged_in_user(self): user = create_user() user_logged_out.connect(self.signal_receiver) request = self.factory.post(user=user) response = self.view(request) self.assert_status_equal(response, status.HTTP_204_NO_CONTENT) self.assertEqual(response.data, None) self.assertTrue(self.signal_sent) def test_post_should_deny_logging_out_when_user_not_logged_in(self): create_user() request = self.factory.post() response = self.view(request) self.assert_status_equal(response, status.HTTP_401_UNAUTHORIZED) def test_options(self): user = create_user() request = self.factory.options(user=user) response = self.view(request) self.assert_status_equal(response, status.HTTP_200_OK)
[ { "point_num": 1, "id": "all_function_names_snake_case", "question": "Are all function names in this file written in snake_case?", "answer": false }, { "point_num": 2, "id": "has_multiple_inheritance", "question": "Does any class in this file use multiple inheritance?", "answer":...
3
testproject/testapp/tests/test_token_destroy.py
mark-slepkov/djoser
def valid_pubsub(config): if (config.get("topic_id") is not None and config.get("project_id") is not None and config.get("subscription_id") is not None): return True return False def valid_kafka(config): if config.get("bootstrap_server") is not None and config.get("port") is not None: return True return False
[ { "point_num": 1, "id": "every_function_has_docstring", "question": "Does every function in this file have a docstring?", "answer": false }, { "point_num": 2, "id": "has_nested_function_def", "question": "Does this file contain any function defined inside another function?", "ans...
3
unified_api/utils/utils.py
campos537/deep-fashion-system
#!/bin/env python """ Simple VTK example in Python to load an STL mesh and display with a manipulator. Chris Hodapp, 2014-01-28, (c) 2014 """ import vtk def render(): # Create a rendering window and renderer ren = vtk.vtkRenderer() renWin = vtk.vtkRenderWindow() renWin.AddRenderer(ren) # Create a RenderWindowInteractor to permit manipulating the camera iren = vtk.vtkRenderWindowInteractor() iren.SetRenderWindow(renWin) style = vtk.vtkInteractorStyleTrackballCamera() iren.SetInteractorStyle(style) stlFilename = "magnolia.stl" polydata = loadStl(stlFilename) ren.AddActor(polyDataToActor(polydata)) ren.SetBackground(0.1, 0.1, 0.1) # enable user interface interactor iren.Initialize() renWin.Render() iren.Start() def loadStl(fname): """Load the given STL file, and return a vtkPolyData object for it.""" reader = vtk.vtkSTLReader() reader.SetFileName(fname) reader.Update() polydata = reader.GetOutput() return polydata def polyDataToActor(polydata): """Wrap the provided vtkPolyData object in a mapper and an actor, returning the actor.""" mapper = vtk.vtkPolyDataMapper() if vtk.VTK_MAJOR_VERSION <= 5: #mapper.SetInput(reader.GetOutput()) mapper.SetInput(polydata) else: mapper.SetInputConnection(polydata.GetProducerPort()) actor = vtk.vtkActor() actor.SetMapper(mapper) #actor.GetProperty().SetRepresentationToWireframe() actor.GetProperty().SetColor(0.5, 0.5, 1.0) return actor render()
[ { "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
VTKviewer.py
Benjamin-Fouquet/Processing-scripts
import json config = 'config.json' with open(config, 'r') as f: data = json.load(f) default = data["default"] class AbstractCommand(): def __init__(self, handler = [], description = None): self.handler = handler self.description = description def hdl(self): return self.handler def dsc(self): return self.description @staticmethod async def ans_up(ans, m, att = None): if (m.text.count(' ') == 0): if (m.text == m.text.upper()): up = True else: up = False else: ind = m.text.index(' ') text = m.text[:ind] if (text == text.upper()): up = True else: up = False if (ans != ''): if (up): await m.answer(default["prefix"] + ans.upper()) return True else: await m.answer(ans) return True elif (att != None): if (up): await m.answer(default["prefix"].upper(), attachment=att) return True else: await m.answer(attachment=att) return True
[ { "point_num": 1, "id": "every_function_under_20_lines", "question": "Is every function in this file shorter than 20 lines?", "answer": false }, { "point_num": 2, "id": "has_multiple_inheritance", "question": "Does any class in this file use multiple inheritance?", "answer": fals...
3
classes/abstract_command.py
platofff/quote-bot
from django.db import models from django.forms import ModelForm from django.contrib.auth import get_user_model # Create your models here. # Get the user model User = get_user_model() class BillingAddress(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) address = models.CharField(max_length=100) zipcode = models.CharField(max_length=50) city = models.CharField(max_length=30) landmark = models.CharField(max_length=20) def __str__(self): return f'{self.user.username} billing address' class Meta: verbose_name_plural = "Billing Addresses" # Address Form class BillingForm(ModelForm): class Meta: model = BillingAddress fields = ['address', 'zipcode', 'city', 'landmark']
[ { "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
ecommerce/checkout/models.py
starboi02/e-commerce-CMS
# 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 class DescribeScalingActivityRequest(RpcRequest): def __init__(self): RpcRequest.__init__(self, 'Emr', '2016-04-08', 'DescribeScalingActivity') def get_ResourceOwnerId(self): return self.get_query_params().get('ResourceOwnerId') def set_ResourceOwnerId(self,ResourceOwnerId): self.add_query_param('ResourceOwnerId',ResourceOwnerId) def get_HostGroupId(self): return self.get_query_params().get('HostGroupId') def set_HostGroupId(self,HostGroupId): self.add_query_param('HostGroupId',HostGroupId) def get_ClusterId(self): return self.get_query_params().get('ClusterId') def set_ClusterId(self,ClusterId): self.add_query_param('ClusterId',ClusterId) def get_ScalingActivityId(self): return self.get_query_params().get('ScalingActivityId') def set_ScalingActivityId(self,ScalingActivityId): self.add_query_param('ScalingActivityId',ScalingActivityId)
[ { "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
aliyun-python-sdk-emr/aliyunsdkemr/request/v20160408/DescribeScalingActivityRequest.py
sdk-team/aliyun-openapi-python-sdk
import asyncio import discord from discord.ext.commands import Bot from discord.ext import commands from discord import Color, Embed import backend.commands as db from backend import strikechannel # This command allows players to change their name. # # !name [new_name] # # This replaces the default nickname changing that Discord provides so # that their name will also be replaced in the spreadsheet. class Name(commands.Cog): def __init__(self, bot): self.bot = bot self.strike_channel_id = strikechannel @commands.command() async def name(self, ctx): old_name = ctx.author.display_name new_name = ctx.message.content[6:] print(old_name) print(new_name) # This changes their name in the "#strikes" channel channel = self.bot.get_channel(self.strike_channel_id) async for msg in channel.history(limit=None): text = msg.content.replace("```", "") text_lst = text.split("\n") d = {} for line in text_lst: try: name, strikes = line.rsplit(" - ", 1) except: continue d[name] = int(strikes) if old_name in d: d[new_name] = d[old_name] del d[old_name] inner_text = "" for k, v in d.items(): inner_text += f"{k} - {v}\n" full_text = f"```\n{inner_text}```" await msg.edit(content=full_text) db.change_name(old_name, new_name) await ctx.author.edit(nick=new_name) await ctx.channel.send("Name Changed!") def setup(bot): bot.add_cog(Name(bot))
[ { "point_num": 1, "id": "no_function_exceeds_5_params", "question": "Does every function in this file take 5 or fewer parameters (excluding self/cls)?", "answer": true }, { "point_num": 2, "id": "all_function_names_snake_case", "question": "Are all function names in this file written...
3
commands/name.py
DaleNaci/AUC
from tweetengine import model from google.appengine.api import users def setConfiguration(): account_name='tweet_engine' password='passwd' oauth_key='fookey' oauth_secret='foosecret' conf = model.Configuration.instance() conf.oauth_key = oauth_key conf.oauth_secret = oauth_secret conf.put() def addTwitterAccounts(): account = model.TwitterAccount.get_or_insert( 'tweet_engine', oauth_token='usertoken', oauth_secret='usersecret', name='Full name', picture='') account.put() def addUsers(): user_data = (('test1@example.org', 1), ('test2@example.org', 2)) for email, role in user_data: user = users.User(email=email) usr = model.GoogleUserAccount(user=user) usr.put() permission = model.Permission.create( usr, model.TwitterAccount.get_by_key_name('tweet_engine'), model.ROLE_ADMINISTRATOR) permission.put()
[ { "point_num": 1, "id": "all_function_names_snake_case", "question": "Are all function names in this file written in snake_case?", "answer": false }, { "point_num": 2, "id": "every_function_has_docstring", "question": "Does every function in this file have a docstring?", "answer"...
3
src/tweetengine/utils.py
Arachnid/tweetengine
# coding: utf-8 """ Control-M Services Provides access to BMC Control-M Services # noqa: E501 OpenAPI spec version: 9.20.220 Contact: customer_support@bmc.com Generated by: https://github.com/swagger-api/swagger-codegen.git """ from __future__ import absolute_import import unittest import controlm_py from controlm_py.models.agent_in_hostgroup import AgentInHostgroup # noqa: E501 from controlm_py.rest import ApiException class TestAgentInHostgroup(unittest.TestCase): """AgentInHostgroup unit test stubs""" def setUp(self): pass def tearDown(self): pass def testAgentInHostgroup(self): """Test AgentInHostgroup""" # FIXME: construct object with mandatory attributes with example values # model = controlm_py.models.agent_in_hostgroup.AgentInHostgroup() # noqa: E501 pass if __name__ == '__main__': unittest.main()
[ { "point_num": 1, "id": "has_multiple_inheritance", "question": "Does any class in this file use multiple inheritance?", "answer": false }, { "point_num": 2, "id": "every_function_has_docstring", "question": "Does every function in this file have a docstring?", "answer": false ...
3
test/test_agent_in_hostgroup.py
dcompane/controlm_py
"""The tests for the rss_feed_api component.""" from defusedxml import ElementTree import pytest from openpeerpower.const import HTTP_NOT_FOUND from openpeerpower.setup import async_setup_component @pytest.fixture def mock_http_client(loop, opp, opp_client): """Set up test fixture.""" config = { "rss_feed_template": { "testfeed": { "title": "feed title is {{states.test.test1.state}}", "items": [ { "title": "item title is {{states.test.test2.state}}", "description": "desc {{states.test.test3.state}}", } ], } } } loop.run_until_complete(async_setup_component(opp, "rss_feed_template", config)) return loop.run_until_complete(opp_client()) async def test_get_nonexistant_feed(mock_http_client): """Test if we can retrieve the correct rss feed.""" resp = await mock_http_client.get("/api/rss_template/otherfeed") assert resp.status == HTTP_NOT_FOUND async def test_get_rss_feed(mock_http_client, opp): """Test if we can retrieve the correct rss feed.""" opp.states.async_set("test.test1", "a_state_1") opp.states.async_set("test.test2", "a_state_2") opp.states.async_set("test.test3", "a_state_3") resp = await mock_http_client.get("/api/rss_template/testfeed") assert resp.status == 200 text = await resp.text() xml = ElementTree.fromstring(text) assert xml[0].text == "feed title is a_state_1" assert xml[1][0].text == "item title is a_state_2" assert xml[1][1].text == "desc a_state_3"
[ { "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
tests/components/rss_feed_template/test_init.py
pcaston/core
import collections import random from typing import Counter import demistomock as demisto # noqa: F401 from CommonServerPython import * # noqa: F401 def parse_data(list_content): lists_data = [] list_collections: Counter = collections.Counter(list_content) top_lists = list_collections.most_common(10) lists_number = len(top_lists) list_number = 0 while list_number < lists_number: for list_element in top_lists: random_number = random.randint(0, 16777215) hex_number = str(hex(random_number)) # convert to hexadecimal color = f'#{hex_number[2:].zfill(6)}' # remove 0x and prepend '#' list_widget_data = { "data": [ list_element[1] ], "name": str(list_element[0]), "color": color } lists_data.append(list_widget_data) list_number += 1 return lists_data def main(): list_data = demisto.executeCommand("getList", {"listName": "XSOAR Health - Failed Integrations Category"}) list_content = list_data[0].get('Contents', '').split(",") if list_content != ['']: data = parse_data(list_content) else: data = [{ "data": [ 0 ], "name": "N/A", "color": "#00CD33" }] demisto.results(json.dumps(data)) if __name__ in ["__main__", "builtin", "builtins"]: main()
[ { "point_num": 1, "id": "every_function_under_20_lines", "question": "Is every function in this file shorter than 20 lines?", "answer": false }, { "point_num": 2, "id": "has_nested_function_def", "question": "Does this file contain any function defined inside another function?", ...
3
Packs/IntegrationsAndIncidentsHealthCheck/Scripts/IntegrationsCheck_Widget_IntegrationsCategory/IntegrationsCheck_Widget_IntegrationsCategory.py
diCagri/content
""" 链家二手房数据抓取 """ import requests from lxml import etree import time import random from fake_useragent import UserAgent import pymongo class LianJiaSpider: def __init__(self): self.url = 'https://lf.lianjia.com/ershoufang/pg{}/' # 3个对象 self.conn = pymongo.MongoClient('localhost', 27017) self.db = self.conn['lianjiadb'] self.myset = self.db['lianjiaset'] def get_html(self, url): headers = {'User-Agent':UserAgent().random} html = requests.get(url=url, headers=headers).text # 直接调用解析函数 self.parse_html(html) def parse_html(self, html): eobj = etree.HTML(html) li_list = eobj.xpath('//ul/li[@class="clear LOGVIEWDATA LOGCLICKDATA"]') for li in li_list: item = {} name_list = li.xpath('.//div[@class="positionInfo"]/a[1]/text()') item['name'] = name_list[0] if name_list else None address_list = li.xpath('.//div[@class="positionInfo"]/a[2]/text()') item['address'] = address_list[0] if address_list else None info_list = li.xpath('.//div[@class="houseInfo"]/text()') item['info'] = info_list[0] if info_list else None total_list = li.xpath('.//div[@class="totalPrice"]/span/text()') item['total'] = total_list[0] if total_list else None unit_list = li.xpath('.//div[@class="unitPrice"]/span/text()') item['unit'] = unit_list[0] if unit_list else None print(item) self.myset.insert_one(item) def crawl(self): for page in range(1, 101): page_url = self.url.format(page) self.get_html(url=page_url) # 控制数据抓取的频率 time.sleep(random.randint(1, 2)) if __name__ == '__main__': spider = LianJiaSpider() spider.crawl()
[ { "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
month05/spider/day04_course/day04_code/01_lianjiaSpider.py
chaofan-zheng/tedu-python-demo
class DigitalSignatureScheme(object): def get_public_key(self): return self.public_key def sign(self, messsage): raise NotImplementedError def verify(self, message, signature): raise NotImplementedError
[ { "point_num": 1, "id": "no_function_exceeds_5_params", "question": "Does every function in this file take 5 or fewer parameters (excluding self/cls)?", "answer": true }, { "point_num": 2, "id": "has_multiple_inheritance", "question": "Does any class in this file use multiple inherit...
3
common/signature/__init__.py
lukius/mts
# Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import mock from openstack.tests.unit import base from openstack.clustering.v1 import profile_type FAKE = { 'name': 'FAKE_PROFILE_TYPE', 'schema': { 'foo': 'bar' }, 'support_status': { '1.0': [{ 'status': 'supported', 'since': '2016.10', }] } } class TestProfileType(base.TestCase): def test_basic(self): sot = profile_type.ProfileType() self.assertEqual('profile_type', sot.resource_key) self.assertEqual('profile_types', sot.resources_key) self.assertEqual('/profile-types', sot.base_path) self.assertTrue(sot.allow_fetch) self.assertTrue(sot.allow_list) def test_instantiate(self): sot = profile_type.ProfileType(**FAKE) self.assertEqual(FAKE['name'], sot._get_id(sot)) self.assertEqual(FAKE['name'], sot.name) self.assertEqual(FAKE['schema'], sot.schema) self.assertEqual(FAKE['support_status'], sot.support_status) def test_ops(self): sot = profile_type.ProfileType(**FAKE) resp = mock.Mock() resp.json = mock.Mock(return_value='') sess = mock.Mock() sess.get = mock.Mock(return_value=resp) self.assertEqual('', sot.type_ops(sess)) url = 'profile-types/%s/ops' % sot.id sess.get.assert_called_once_with(url)
[ { "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
openstack/tests/unit/clustering/v1/test_profile_type.py
NeCTAR-RC/openstacksdk
import section import pytest # 作成 class Test_2つの整数を引数に閉区間オブジェクトをつくる: def test_3から8の閉区間を作れる(self): x=section.Section(3,8) assert x.lower==3 and x.upper==8 def test_3から8の閉区間を作れる(self): x=section.Section(3,3) assert x.lower==3 and x.upper==3 # 作成(例外処理) class Test_整数以外では閉区間オブジェクトをつくれない: def test_小数3_1から8_1の閉区間は作れない(self): with pytest.raises(ValueError): x=section.Section(3.1,8.1) def 文字列_あ_や_い_では閉区間は作れない(self): try: x=section.Section("あ","い") assert False except: assert True class Test_始点の方が大きい閉区間は作れない: def test_8から3の閉区間は作れない(self): try: x=section.Section(8,3) assert False except: assert True # 文字列表現を返す class Test_閉区間オブジェクトは文字列表現を返す: def test_3から8の閉区間の文字列表現を返せる(self): x=section.Section(3,8) assert isinstance(x.toString(),str) assert str([3,8]) == x.toString() class Test_閉区間オブジェクトは指定した整数を含むかどうかを判定できる: def test_2は3から8の閉区間には含まれない(self): x=section.Section(3,8) assert (not x.num_in(2)) def test_3は3から8の閉区間には含まれる(self): x=section.Section(3,8) assert (x.num_in(3)) def test_8は3から8の閉区間には含まれる(self): x=section.Section(3,8) assert (x.num_in(8)) def test_9は3から8の閉区間には含まれる(self): x=section.Section(3,8) assert (not x.num_in(9)) class Test_閉区間オブジェクトは別の閉区間と等価かどうかを判定できる: def test_3から8の閉区間と3から8の閉区間は等価(self): x=section.Section(3,8) y=section.Section(3,8) assert x.equal(y) def test_3から8の閉区間と4から8の閉区間は等価(self): x=section.Section(3,8) y=section.Section(4,8) assert (not x.equal(y))
[ { "point_num": 1, "id": "every_function_under_20_lines", "question": "Is every function in this file shorter than 20 lines?", "answer": true }, { "point_num": 2, "id": "every_class_has_docstring", "question": "Does every class in this file have a docstring?", "answer": false },...
3
section_test.py
y-k-k/python_pytest
# -*- coding: utf-8 -*- __author__ = 'huangpeng' class AGList(list): def each(self, func): for a in self: func(a) return self def map(self, func): return map(func, self) def filter(self, func): return filter(func, self) class AGDict(dict): def each(self, func): for (k, v) in self.items(): func(k, v) return self def map(self, func): return map(func, self) def filter(self, func): return filter(func, self)
[ { "point_num": 1, "id": "has_multiple_inheritance", "question": "Does any class in this file use multiple inheritance?", "answer": false }, { "point_num": 2, "id": "every_function_has_docstring", "question": "Does every function in this file have a docstring?", "answer": false ...
3
containers.py
hpsoar/pplib
# -*- coding: utf-8 -*- class Storage(object): def set(self, key, value, time=0):# pragma: no cover raise NotImplementedError() def get(self, key, default=None):# pragma: no cover raise NotImplementedError() def delete(self, key):# pragma: no cover raise NotImplementedError() class LocalMemStorage(Storage): def __init__(self): self.storage = {} def set(self, key, value, time=0): self.storage[key] = value return True def get(self, key, default=None): return self.storage.get(key, default) def delete(self, key): if key in self.storage: del self.storage[key] return True class MemcachedStorage(Storage): def __init__(self, conf): import memcache conf = conf if isinstance(conf, (list, tuple)) else [conf] self.storage = memcache.Client(conf) def set(self, key, value, time=0): return self.storage.set(key, value, time) def get(self, key, default=None): value = self.storage.get(key) if value is None: return default return value def delete(self, key): return self.storage.delete(key)
[ { "point_num": 1, "id": "all_function_names_snake_case", "question": "Are all function names in this file written in snake_case?", "answer": true }, { "point_num": 2, "id": "all_params_annotated", "question": "Does every function parameter in this file have a type annotation (excludi...
3
iktomi/storage.py
boltnev/iktomi
import webapp2 class MainHandler(webapp2.RequestHandler): def get(self): self.response.write('Hello world!') class CountHandler(webapp2.RequestHandler): def get(self): for i in range(1, 21): self.response.write('Hello %d <br>' % i) app = webapp2.WSGIApplication([ ('/', MainHandler), ('/count', CountHandler) ], debug=True)
[ { "point_num": 1, "id": "every_function_has_docstring", "question": "Does every function in this file have a docstring?", "answer": false }, { "point_num": 2, "id": "has_multiple_inheritance", "question": "Does any class in this file use multiple inheritance?", "answer": false ...
3
src/example02/main.py
luisibanez/cssi-appengine-introduction-01
import re from typing import List class StringProcessService: def __init__(self): self._charmap = { 0x201c: u'"', 0x201d: u'"', 0x2018: u"'", 0x2019: u"'", 'ff': u'ff', 'fi': u'fi', 'fl': u'fl', 'ffi': u'ffi', 'ffl': u'ffl', '″': u'"', '′': u"'", '„': u'"', '«': u'"', '»': u'"' } self._number_regex = '^(((([0-9]*)(\.|,)([0-9]+))+)|([0-9]+))' def convert_string_unicode_symbols(self, text: str) -> str: result = text.translate(self._charmap) return result def convert_strings_unicode_symbols(self, texts: List[str]) -> List[str]: result = [self.convert_string_unicode_symbols(x) for x in texts] return result def replace_string_numbers(self, text: str) -> str: result = re.sub(self._number_regex, '0', text) return result def replace_strings_numbers(self, texts: List[str]) -> List[str]: result = [self.replace_string_numbers(x) for x in texts] return result def remove_string_characters(self, text: str, characters: List[str]) -> str: result = text for character in characters: result = result.replace(character, '') return result def remove_strings_characters(self, texts: List[str], characters: List[str]) -> List[str]: result = [self.remove_string_characters(x, characters) for x in texts] return result
[ { "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
services/string_process_service.py
ktodorov/historical-ocr
import unittest from backend.services.messaging.template_service import ( template_var_replacing, get_template, clean_html, format_username_link, ) from flask import current_app class TestTemplateService(unittest.TestCase): def test_variable_replacing(self): # Act content = get_template("email_verification_en.html") replace_list = [ ["[USERNAME]", "test_user"], ["[VERIFICATION_LINK]", "http://localhost:30/verify.html#1234"], ["[ORG_CODE]", "HOT"], ["[ORG_NAME]", "Organization Test"], ] processed_content = template_var_replacing(content, replace_list) # Assert self.assertIn("test_user", processed_content) self.assertIn("http://localhost:30/verify.html#1234", processed_content) self.assertIn("HOT", processed_content) self.assertIn("Organization Test", processed_content) self.assertNotIn("[USERNAME]", processed_content) self.assertNotIn("[VERIFICATION_LINK]", processed_content) self.assertNotIn("[ORG_CODE]", processed_content) self.assertNotIn("[ORG_NAME]", processed_content) def test_clean_html(self): self.assertEqual( clean_html( 'Welcome to <a href="https://tasks.hotosm.org">Tasking Manager</a>!' ), "Welcome to Tasking Manager!", ) def test_format_username_link(self): base_url = current_app.config["APP_BASE_URL"] self.assertEqual( format_username_link("try @[yo] @[us2]! [t](http://a.c)"), f'try <a href="{base_url}/users/yo/">@yo</a> <a href="{base_url}/users/us2/">@us2</a>! [t](http://a.c)', ) self.assertEqual( format_username_link( "testing @user! Write me at i@we.com [test](http://link.com)" ), "testing @user! Write me at i@we.com [test](http://link.com)", )
[ { "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
tests/backend/unit/services/messaging/test_template_service.py
d-rita/tasking-manager
# -*- coding: utf-8 -*- """API Request cache tests.""" # # (C) Pywikibot team, 2012-2014 # # Distributed under the terms of the MIT license. # from __future__ import unicode_literals __version__ = '$Id: 790cd19ca8b22937365bf24b6e40ed90c79ee12b $' # from pywikibot.site import BaseSite import scripts.maintenance.cache as cache from tests import _cache_dir from tests.aspects import unittest, TestCase class RequestCacheTests(TestCase): """Validate cache entries.""" net = False def _check_cache_entry(self, entry): """Assert validity of the cache entry.""" self.assertIsInstance(entry.site, BaseSite) self.assertIsInstance(entry.site._loginstatus, int) self.assertIsInstance(entry.site._username, list) if entry.site._loginstatus >= 1: self.assertIsNotNone(entry.site._username[0]) self.assertIsInstance(entry._params, dict) self.assertIsNotNone(entry._params) # TODO: more tests on entry._params, and possibly fixes needed # to make it closely replicate the original object. def test_cache(self): """Test the apicache by doing _check_cache_entry over each entry.""" cache.process_entries(_cache_dir, self._check_cache_entry) 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": true },...
3
tests/cache_tests.py
valhallasw/pywikibot-core
# 279. Perfect Squares # https://leetcode.com/problems/perfect-squares import unittest class Solution(object): def numSquares(self, n): if n < 2: return n squares = [i ** 2 for i in range(1, int(n ** 0.5) + 1)] queue, depth = {n}, 1 while queue: next_nodes = set() for val in queue: for sq in squares: if val == sq: return depth elif val < sq: break next_nodes.add(val - sq) queue = next_nodes depth += 1 return depth class TestPerfectSquares(unittest.TestCase): def test(self): sol = Solution() self.assertEqual(sol.numSquares(12), 3) self.assertEqual(sol.numSquares(13), 2) if __name__ == '__main__': unittest.TestCase()
[ { "point_num": 1, "id": "every_function_has_docstring", "question": "Does every function in this file have a docstring?", "answer": false }, { "point_num": 2, "id": "has_multiple_inheritance", "question": "Does any class in this file use multiple inheritance?", "answer": false ...
3
problems/perfect_square.py
smartdolphin/recommandation-tutorial
#!/usr/bin/env python # ***************************************************************************** # Copyright (C) 2022 Thomas Touhey <thomas@touhey.fr> # # This software is licensed as described in the file LICENSE, which you # should have received as part of this distribution. # # THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS # IN THE SOFTWARE. # ***************************************************************************** """ ressourcessgdf module definition. """ from visyerres_sgdf_woob.backend import Module as _Module from woob.tools.value import ValueBackendPassword as _ValueBackendPassword from .browser import RessourcesSGDFBrowser as _RessourcesSGDFBrowser __all__ = ['RessourcesSGDFModule'] class RessourcesSGDFModule(_Module): NAME = 'ressourcessgdf' DESCRIPTION = 'Ressources Scouts et Guides de France' MAINTAINER = 'Thomas Touhey' EMAIL = 'thomas@touhey.fr' LICENSE = 'Proprietary' BROWSER = _RessourcesSGDFBrowser username = _ValueBackendPassword( label="Nom d'utilisateur", masked=False, ) password = _ValueBackendPassword( label='Mot de passe', masked=True, ) def create_default_browser(self): return self.create_browser( self.config['username'].get(), self.config['password'].get(), weboob=self.weboob, ) def check_login(self): return self.browser.check_login() # End of file.
[ { "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
visyerres_sgdf_woob/modules/ressourcessgdf/module.py
cakeisalie5/visyerres_sgdf_woob
class LeaderboardData: """This is the Custom Hypixel API Leaderboard Data Model.""" def __init__(self, data: dict) -> None: """ Parameters ---------- data: dict The Leaderboard JSON data per game response received from the Hypixel API. """ self.PATH = data["path"] self.PREFIX = data["prefix"] self.TITLE = data["title"] self.LOCATION = data["location"] self.COUNT = data["count"] self.LEADERS_UUID = data["leaders"] def __repr__(self) -> str: return f'<{self.__class__.__name__} title="{self.TITLE}" location="{self.LOCATION}">' def __str__(self) -> str: return self.TITLE
[ { "point_num": 1, "id": "every_function_has_docstring", "question": "Does every function in this file have a docstring?", "answer": false }, { "point_num": 2, "id": "has_multiple_inheritance", "question": "Does any class in this file use multiple inheritance?", "answer": false ...
3
hypixelio/models/leaderboard/leaderboard_data.py
FoxNerdSaysMoo/HypixelIO
from RPG.bot_classes.base_handler import BaseHandler from RPG.consts.game_states import PLAYER_PROFILE class PlayerProfile(BaseHandler): def __init__(self, game): super().__init__(game, PLAYER_PROFILE) self.reply_keyboard.row('⬅Atrás') def show(self, message): self.game.bot.send_message(message.chat.id, self.game.player.get_stats(), parse_mode='Markdown', reply_markup=self.reply_keyboard) def handle(self, message): if message.text == '⬅Atrás': self.game.main_menu.start(message) else: self.show_input_error(message)
[ { "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
RPG/bot_classes/main_menu/player_profile.py
JuanShotLC/Negative_Space_Bot
import torch import torch.distributions as td class GMM2D(td.MixtureSameFamily): def __init__(self, mixture_distribution, component_distribution): super(GMM2D, self).__init__(mixture_distribution, component_distribution) def mode_mode(self): mode_k = torch.argmax(self.mixture_distribution.probs[0, 0]).item() mode_gaussian = self.component_distribution.mean[:, 0, mode_k, :2] return mode_gaussian def position_log_prob(self, x): # Computing the log probability over only the positions. component_dist = td.MultivariateNormal(loc=self.component_distribution.mean[..., :2], scale_tril=self.component_distribution.scale_tril[..., :2, :2]) position_dist = td.MixtureSameFamily(self.mixture_distribution, component_dist) return position_dist.log_prob(x) @property def pis(self): return self.mixture_distribution.probs[0, 0]
[ { "point_num": 1, "id": "all_function_names_snake_case", "question": "Are all function names in this file written in snake_case?", "answer": true }, { "point_num": 2, "id": "no_function_exceeds_5_params", "question": "Does every function in this file take 5 or fewer parameters (exclu...
3
mats/model/components/gmm2d.py
StanfordASL/MATS
""" This module contains the tests for the configurations """ # standard imports import unittest from app import create_app class TestDevelopmentConfig(unittest.TestCase): """ Test class for development config """ def setUp(self): """Initialize app""" self.app = create_app('development') def test_app_is_development(self): """ Test function for development environment """ self.assertEqual(self.app.config['DEBUG'], True) self.assertEqual(self.app.config['TESTING'], False) def tearDown(self): """Clear app""" self.app = None class TestTestingConfig(unittest.TestCase): """ Test class for testing config """ def setUp(self): """Initialize app""" self.app = create_app('testing') def test_app_is_development(self): """ Test function for testing environment """ self.assertEqual(self.app.config['DEBUG'], False) self.assertEqual(self.app.config['TESTING'], True) def tearDown(self): """Clear app""" self.app = None
[ { "point_num": 1, "id": "every_function_has_docstring", "question": "Does every function in this file have a docstring?", "answer": true }, { "point_num": 2, "id": "every_class_has_docstring", "question": "Does every class in this file have a docstring?", "answer": true }, { ...
3
app/tests/test_config.py
erick-maina/Questioner_API
# Copyright 2017 Neural Networks and Deep Learning lab, MIPT # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import sys from pathlib import Path from ._meta import __author__, __description__, __email__, __keywords__, __license__, __version__ from .configs import configs from .core.commands.infer import build_model from .core.commands.train import train_evaluate_model_from_config from .core.common.base import Element, Model from .core.common.chainer import Chainer from .core.common.log import init_logger from .download import deep_download # TODO: make better def train_model(config: [str, Path, dict], download: bool = False, recursive: bool = False) -> Chainer: train_evaluate_model_from_config(config, download=download, recursive=recursive) return build_model(config, load_trained=True) def evaluate_model(config: [str, Path, dict], download: bool = False, recursive: bool = False) -> dict: return train_evaluate_model_from_config(config, to_train=False, download=download, recursive=recursive) # check version assert sys.hexversion >= 0x3060000, 'Does not work in python3.5 or lower' # resolve conflicts with previous DeepPavlov installations versioned up to 0.0.9 dot_dp_path = Path('~/.deeppavlov').expanduser().resolve() if dot_dp_path.is_file(): dot_dp_path.unlink() # initiate logging init_logger()
[ { "point_num": 1, "id": "no_function_exceeds_5_params", "question": "Does every function in this file take 5 or fewer parameters (excluding self/cls)?", "answer": true }, { "point_num": 2, "id": "all_return_types_annotated", "question": "Does every function in this file have a return...
3
deeppavlov/__init__.py
techthiyanes/DeepPavlov
from django.shortcuts import render from .models import Photos,Category,Location from django.http import HttpResponse, Http404 # Create your views here. def home(request): photos = Photos.objects.all() return render(request,'index.html',{"photos":photos}) def search_photo(request): if 'category' in request.GET and request.GET["category"]: search_category = request.GET.get("category") searched_photos = Photos.search_by_category(search_category) message = f"{search_category}" title = "Search photo" return render(request,'search.html',{"searched_photos":searched_photos, "message":message, "title":title}) else: message = "You haven't searched for any category" return render(request, 'search.html',{"message":message}) def photo(request,photo_id): try: photo = Photos.objects.get(id=photo_id) title = "Photo" except : raise Http404() return render(request,'photo.html',{"photo":photo,"title":title})
[ { "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
my_gallery/views.py
Abdihakim-Muhumed/gallery
# Copyright 2014, Dell # # 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 cb2_api.endpoint import EndPoint from apiobject import ApiObject class GroupEP(EndPoint): ''' https://github.com/digitalrebar/core/blob/master/doc/devguide/api/group.md ''' __endpoint = "/api/v2/groups" __apiObjectType = "Group" def __init__(self, session): self.session = session self.endpoint = GroupEP.__endpoint super(GroupEP, self).__init__(session) class Group(ApiObject): ''' Group object ''' def __init__(self, json={}): self.category = None self.description = None self.created_at = None self.updated_at = None self.id = None self.order = None self.name = None self.__dict__ = json super(Group, self).__init__() class Enums_Group(): ''' TODO '''
[ { "point_num": 1, "id": "every_class_has_docstring", "question": "Does every class in this file have a docstring?", "answer": true }, { "point_num": 2, "id": "every_function_has_docstring", "question": "Does every function in this file have a docstring?", "answer": false }, {...
3
core/clients/python/api_bindings/cb2_api/objects/group.py
aledbf/digitalrebar
def hello(): return get_greeting() def get_greeting(): return "Hola Mundo en el curso de Python"
[ { "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
section-22-unittesting/02_mock_basic/mock_example.py
mugan86/bootcamp-basic-to-expert-from-scratch
import unittest.mock from programy.parser.pattern.nodes.base import MultiValueDict class MultiValueDictTests(unittest.TestCase): def test_add_remove(self): multidict = MultiValueDict() multidict["name"] = "value1" multidict["name"].append("value2") self.assertTrue("name" in multidict) multidict.remove("name", "value1") self.assertTrue("name" in multidict) multidict.remove("name", "value2") self.assertFalse("name" in multidict) def test_remove_no_key(self): multidict = MultiValueDict() multidict["name"] = "value1" multidict["name"].append("value2") multidict.remove("other", "value1") def test_remove_no_value(self): multidict = MultiValueDict() multidict["name"] = "value1" multidict["name"].append("value2") multidict.remove("name", "value3")
[ { "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/programytest/parser/pattern/nodes_tests/test_multidict.py
cdoebler1/AIML2
#!/usr/bin/python2.5 # # Copyright 2009 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Mapreduce handlers and functions.""" __author__ = 'elsigh@google.com (Lindsey Simon)' from base import shardedcounter from mapreduce import operation as op from google.appengine.ext import db def ResultParentCountSet(entity): shardedcounter.increment(entity.category) def UserTestBeaconCount(entity): entity.beacon_count = int( shardedcounter.get_count(entity.get_memcache_keyname())) yield op.db.Put(entity) def UserTestDeletedFalse(entity): entity.deleted = False yield op.db.Put(entity) def SaveMasterSlaveKey(entity): entity.master_slave_key = '%s' % entity.key() yield op.db.Put(entity) def ResultParentUaDeNorm(entity): try: if (not entity.category or not entity.user_agent or (entity.category == 'reflow' and entity.params_str)): yield op.db.Delete(entity) else: entity.user_agent_string_list = entity.user_agent.get_string_list() for attr in ['user_agent_family', 'user_agent_v1', 'user_agent_v2', 'user_agent_v3']: if hasattr(entity, attr): delattr(entity, attr) yield op.db.Put(entity) except db.ReferencePropertyResolveError: yield op.db.Delete(entity)
[ { "point_num": 1, "id": "all_function_names_snake_case", "question": "Are all function names in this file written in snake_case?", "answer": false }, { "point_num": 2, "id": "has_nested_function_def", "question": "Does this file contain any function defined inside another function?",...
3
base/mapreducer.py
elsigh/browserscope
import re ### parse_text(text) # takes a string, return a list of strings with the matching groups def parse_text_regex(text, regex): try: compiled_regex = re.compile(regex) if compiled_regex is None: raise Exception(f"String {text} doesn't match {regex}") except TypeError as te: raise Exception(te) except Exception as e: raise e match = compiled_regex.match(text) return match.groups() def clean_string_with_regex(text, regex): cleaned_string = re.sub(regex, '', text) cleaned_string = cleaned_string.strip() return cleaned_string
[ { "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
TPS_dice_roller_bot/core/parse.py
PumaConcolor/TPS-dice-roller-bot
from setuptools import Extension from .enums import ExtType class GenericGDNativeLibrary(Extension): def __init__(self, name, **gdnative_options): self._gdnative_type = ExtType.GENERIC_LIBRARY self._gdnative_options = gdnative_options super().__init__(name, sources=[]) class GDNativeLibrary(Extension): def __init__(self, name, *, extra_sources=None, **gdnative_options): self._gdnative_type = ExtType.LIBRARY self._gdnative_options = gdnative_options sources = [] if extra_sources is not None: for src in extra_sources: sources.append(src) super().__init__(name, sources=sources)
[ { "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
godot_tools/setup/libraries.py
WilliamTambellini/godopy
""" Generate a `load_data` function to use in a data migration. Usage: from django.db import models, migrations from utils.load_data import load_data class Migration(migrations.Migration): dependencies = [ ] # dependencies operations = [ migrations.RunPython(load_data('path/to/fixtures1.json')), migrations.RunPython(load_data('path/to/fixtures2.json')), ] """ from django.core.serializers import base, python from django.core.management import call_command def load_data(path_to_fixture, database='default'): """ Create a function for loading fixture data. Rather than using the built-in `loaddata` command as-is, the returned function loads fixture data based on the current model state (in case a data migration needs to run in the middle of schema migrations). """ def do_it(apps, schema_editor): if schema_editor.connection.alias == database: original_get_model = python._get_model try: # monkey-patch python_.get_model to use the apps argument # to get the version of a model at this point in the # migrations. def _get_model(model_identifier): try: return apps.get_model(model_identifier) except (LookupError, TypeError): msg = ('Invalid model identifier: \'{}\' ' ''.format(model_identifier)) raise base.DeserializationError(msg) python._get_model = _get_model call_command('loaddata', path_to_fixture, database=database) finally: python._get_model = original_get_model return do_it
[ { "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
django/sierra/utils/load_data.py
Miamiohlibs/catalog-api
"""Utilities module.""" import base64 import hashlib import json import os import traceback from copy import copy from datetime import datetime from functools import wraps from itertools import chain from typing import Callable, List, Optional from ratelimit import sleep_and_retry, limits from pacu.settings import app_dir def defer_wrap(func): @wraps(func) def func_wrapper(*args, **kwargs): deferred = [] _defer = lambda dfunc: deferred.append(dfunc) try: return func(*args, defer=_defer, **kwargs) finally: deferred.reverse() for f in deferred: f() return func_wrapper def limit_requests(reqs_second: int = 0): """Returns a function that blocks if called more then 'reqs_second' times a second.""" @sleep_and_retry @limits(reqs_second, 1) def _limit_requests(*args, **kwargs): pass return _limit_requests def pcache(ignore_args: List[str] = None, ignore_kwargs: List[str] = None): def arg_wrapper(func: Callable): def _wrapper(*args, **kwargs): hargs, hkwargs = list(copy(args)), list(copy(kwargs)) if ignore_args is not None: for i in ignore_args: del hargs[i] if ignore_kwargs is not None: for i in ignore_args: del hkwargs[i] argstr = json.dumps({'args': hargs, 'kwargs': hkwargs}, default=str) m = hashlib.sha256() m.update(argstr.encode()) path = app_dir / 'cache' / func.__name__ / f"{base64.b64encode(m.digest()).decode().replace('/', '_')}.json" if path.is_file(): return json.loads(path.read_text()) os.makedirs(path.parent, exist_ok=True) resp = func(*args, **kwargs) path.write_text(json.dumps(resp, default=str)) return resp return _wrapper return arg_wrapper
[ { "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
pacu/utils.py
RyanJarv/Pacu2
import json class Json: def encode(self, request): return json.dumps(request.body) def decode(self, data): return json.loads(data) def content_type(self): return "application/json"
[ { "point_num": 1, "id": "has_nested_function_def", "question": "Does this file contain any function defined inside another function?", "answer": false }, { "point_num": 2, "id": "all_function_names_snake_case", "question": "Are all function names in this file written in snake_case?",...
3
paypalhttp/serializers/json_serializer.py
cameronmoten/paypalhttp_python
# Quicksort algorithm by taking last element as pivot def partitionIndex(arr, l, r): i = l - 1 pivot = arr[r] for j in range(l, r): if arr[j] <= pivot: i += 1 arr[j], arr[i] = arr[i], arr[j] arr[i+1], arr[r] = arr[r], arr[i+1] return (i+1) def quicksort(arr, l, r): if l < r: index = partitionIndex(arr, l ,r) quicksort(arr, l, index-1) quicksort(arr, index+1, r) if __name__ == '__main__': #Sample input arr = [106, 503, 444, 22, 90, 34, 108, 34, 73, 88, 66, 444, 10, 90] n = len(arr) quicksort(arr, 0, n-1) print(arr)
[ { "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
Code/sorting_algorithms/quick_sort/quick_sort.py
Kevinjadia/Hacktoberfest_DSA_2021
import sys import os import argparse import subprocess class CommandLineParser: def __init__(self): self.term_width = 100 self.formater = lambda prog: argparse.HelpFormatter(prog, max_help_position=int(self.term_width / 2), width=self.term_width) self.commands = {} self.hidden_commands = [] self.parser = argparse.ArgumentParser(prog='cbuild', formatter_class=self.formater) self.parser.add_argument('command', nargs='?') def run(self, args): # If first arg is not a known command, assume user wants to run the setup # command. known_commands = list(self.commands.keys()) + ['-h', '--help'] options = self.parser.parse_args(args) try: return options.run_func(options) except Exception: return 2 def is_tool(name): try: devnull = open(os.devnull) subprocess.Popen([name], stdout=devnull, stderr=devnull).communicate() except OSError as e: if e.errno == os.errno.ENOENT: return False return True def run(original_args, mainfile): if is_tool('ls'): print("ls found") else: print("ls not found") args = original_args[:] return CommandLineParser().run(args) def main(): # Always resolve the command path so Ninja can find it for regen, tests, etc. if 'cbuild.exe' in sys.executable: assert(os.path.isabs(sys.executable)) launcher = sys.executable else: launcher = os.path.realpath(sys.argv[0]) return run(sys.argv[1:], launcher) if __name__ == '__main__': sys.exit(main())
[ { "point_num": 1, "id": "no_function_exceeds_5_params", "question": "Does every function in this file take 5 or fewer parameters (excluding self/cls)?", "answer": true }, { "point_num": 2, "id": "has_multiple_inheritance", "question": "Does any class in this file use multiple inherit...
3
crossbuild/crossbuildmain.py
smohantty/tbuild
''' Created by auto_sdk on 2015.06.10 ''' from top.api.base import RestApi class BaichuanOrderurlGetRequest(RestApi): def __init__(self,domain='gw.api.taobao.com',port=80): RestApi.__init__(self,domain, port) self.name = None def getapiname(self): return 'taobao.baichuan.orderurl.get'
[ { "point_num": 1, "id": "has_nested_function_def", "question": "Does this file contain any function defined inside another function?", "answer": false }, { "point_num": 2, "id": "every_function_has_docstring", "question": "Does every function in this file have a docstring?", "ans...
3
taobao_wechat_bot/top/api/rest/BaichuanOrderurlGetRequest.py
zyphs21/myPythonPractise
from django.test import TestCase from datetime import datetime, timedelta from django.utils.dateparse import parse_date from blog.models import Article from blog.tools import * # Create your tests here. class ArticleTests(TestCase): def test_future_article_will_be_public(self): p = Article(title='test', content='test', draft=False, date = datetime.today() + timedelta(days=30), commentable=True) p.save() lbp = retrieveArticles(drafts=False, future=False) contained = p in lbp p.delete() self.assertEqual(contained, False) def test_draft_article_will_be_public(self): p = Article(title='test', content='test', draft=True, date = datetime.today() - timedelta(days=30), commentable=True) p.save() lbp = retrieveArticles(drafts=False, future=False) contained = p in lbp p.delete() self.assertEqual(contained, False) def test_todays_article_will_be_public(self): p = Article(title='test', content='test', draft=False, date = datetime.today(), commentable=True) p.save() lbp = retrieveArticles(drafts=False, future=False) contained = p in lbp p.delete() self.assertEqual(contained, True)
[ { "point_num": 1, "id": "all_function_names_snake_case", "question": "Are all function names in this file written in snake_case?", "answer": true }, { "point_num": 2, "id": "every_function_under_20_lines", "question": "Is every function in this file shorter than 20 lines?", "answ...
3
blog/tests.py
LeonardA-L/plog
import re import json import importlib import logging logger = logging.getLogger(__name__) class PythonValueInvalid(Exception): pass class PythonParser(object): variable_pattern = r'^\@\{?([\_a-zA-Z0-9][\_\-\.a-zA-Z0-9]+)\}?$' variable_value_pattern = r'(?<!\@)\@\>?\{?([\_a-zA-Z0-9][\_\-\.a-zA-Z0-9]+)\}?' def __init__(self, modules): self.modules = modules def parse(self, value): if not isinstance(value, str): return value if re.search(self.variable_pattern, value): value = self.parse_variable(value) else: for ref_match in re.finditer(self.variable_value_pattern, value): variable_value = self.parse_variable("@{}".format(ref_match.group(1))) if isinstance(variable_value, (list, tuple)): variable_value = ",".join(variable_value) elif isinstance(variable_value, dict): variable_value = json.dumps(variable_value) if variable_value: value = value.replace(ref_match.group(0), str(variable_value)).strip() return value def parse_variable(self, value): config_match = re.search(self.variable_pattern, value) if config_match: lookup = config_match.group(1).split('.') attribute = lookup.pop() lookup_name = ".".join(lookup) for name, lookup_module in self.modules.items(): if name == lookup_name and hasattr(lookup_module, attribute): return getattr(lookup_module, attribute) try: module = importlib.import_module(lookup_name) return getattr(module, attribute) except Exception as e: logger.error("Module attribute import failed: {}.{}: {}".format(".".join(lookup), attribute, e)) # Not found, raise alarm bells!! raise PythonValueInvalid("No Python module/attribute combination for lookup: {}".format(value))
[ { "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
app/utility/python.py
criticallycode/zima
# # yjDateTime.py, 200506 # from ctypes import * from modules.windows_jumplist.lib import Filetimes import datetime def filetime_to_datetime(filetime, inchour = 0): ''' v = filetime_to_datetime(ft, 9).isoformat() ''' if __debug__: assert type(filetime) is int try: return Filetimes.filetime_to_dt(filetime) + datetime.timedelta(hours=inchour) except Exception: return None # TFileTime class FILETIME(LittleEndianStructure): _fields_ = [ ('LowDateTime', c_uint32), ('HighDateTime', c_uint32) ] def FileTime(v): ''' v = filetime_to_datetime(FileTime(ft), 9).isoformat() v = filetime_to_datetime(FileTime(ft), 9) v = filetime_to_datetime(FileTime(ft)) ''' if __debug__: assert type(v) is FILETIME return (v.HighDateTime << 32) + v.LowDateTime
[ { "point_num": 1, "id": "every_function_has_docstring", "question": "Does every function in this file have a docstring?", "answer": true }, { "point_num": 2, "id": "more_functions_than_classes", "question": "Does this file define more functions than classes?", "answer": true },...
3
modules/windows_jumplist/lib/yjDateTime.py
naaya17/carpe
import pygame from pygame.sprite import Sprite class Ship(Sprite): """Parent ship class for Blast.""" def __init__(self, blast_settings, screen): """Init ship and starting position.""" super(Ship, self).__init__() self.screen = screen self.blast_settings = blast_settings self.image = pygame.image.load('../images/player.png') self.rect = self.image.get_rect() self.screen_rect = screen.get_rect() self.rect.centerx = self.screen_rect.centerx self.rect.centery = self.screen_rect.centery self.rect.bottom = self.screen_rect.bottom self.center = float(self.rect.centerx) self.vertical = float(self.rect.centery) # Movement flags self.moving_right = False self.moving_left = False self.moving_up = False self.moving_down = False def update(self): """Update the ship's pos based on the movement flags.""" if self.moving_right and self.rect.right < self.screen_rect.right: self.center += self.blast_settings.ship_speed_factor if self.moving_left and self.rect.left > 0: self.center -= self.blast_settings.ship_speed_factor if self.moving_up and self.rect.top > 0: self.vertical -= self.blast_settings.ship_speed_factor if self.moving_down and self.rect.bottom < self.screen_rect.bottom: self.vertical += self.blast_settings.ship_speed_factor self.rect.centerx = self.center self.rect.centery = self.vertical def blitme(self): """Draw ship at current location.""" self.screen.blit(self.image, self.rect) def center_ship(self): """Center ship on screen""" self.center = self.screen_rect.centerx # FIXME: Arbitrary "magic number" to get ship to bottom self.vertical = self.screen_rect.bottom - 25
[ { "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": true },...
3
src/ship.py
tomice/Blast
# coding: utf-8 """ iEngage 2.0 API This API enables Intelligent Engagement for your Business. iEngage is a platform that combines process, augmented intelligence and rewards to help you intelligently engage customers. OpenAPI spec version: 2.0 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 iengage_client from iengage_client.rest import ApiException from iengage_client.models.verve_response_comment_list import VerveResponseCommentList class TestVerveResponseCommentList(unittest.TestCase): """ VerveResponseCommentList unit test stubs """ def setUp(self): pass def tearDown(self): pass def testVerveResponseCommentList(self): """ Test VerveResponseCommentList """ model = iengage_client.models.verve_response_comment_list.VerveResponseCommentList() 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_verve_response_comment_list.py
iEngage/python-sdk
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from ripozo.exceptions import RestException class MissingModelException(RestException): """ Raised when a a model_name on a model class does not exist in the database. """ class UnauthenticatedException(RestException): """Raised when the user is not authenticated""" def __init__(self, status_code=401, *args, **kwargs): super(UnauthenticatedException, self).__init__(status_code=status_code, *args, **kwargs) class UnauthorizedException(RestException): """Raised when the user is not authorized""" def __init__(self, status_code=403, *args, **kwargs): super(UnauthorizedException, self).__init__(status_code=status_code, *args, **kwargs)
[ { "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
rest_builder/exceptions.py
timmartin19/browser-REST-builder
# import the necessary packages from __future__ import absolute_import import numpy as np import cv2 from ..convenience import is_cv2 class RootSIFT: def __init__(self): # initialize the SIFT feature extractor for OpenCV 2.4 if is_cv2(): self.extractor = cv2.DescriptorExtractor_create("SIFT") # otherwise initialize the SIFT feature extractor for OpenCV 3+ else: self.extractor = cv2.xfeatures2d.SIFT_create() def compute(self, image, kps, eps=1e-7): # compute SIFT descriptors (kps, descs) = self.extractor.compute(image, kps) # if there are no keypoints or descriptors, return an empty tuple if len(kps) == 0: return ([], None) # apply the Hellinger kernel by first L1-normalizing and taking the # square-root descs /= (descs.sum(axis=1, keepdims=True) + eps) descs = np.sqrt(descs) # return a tuple of the keypoints and descriptors return (kps, descs)
[ { "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
libs/imutils/feature/rootsift.py
rocketbot-cl/recognition
#!/usr/bin/python # encoding=utf-8 """ 只能管理员编辑,只对外提供fixture。 """ import os import time import pytest # 项目目录路径 _project_dir = os.path.dirname(os.path.abspath(__file__)) # 设置缓存供tep使用 @pytest.fixture(scope="session", autouse=True) def _project_cache(request): request.config.cache.set("project_dir", _project_dir) # 自动导入fixtures _fixtures_dir = os.path.join(_project_dir, "fixtures") _fixtures_paths = [] for root, _, files in os.walk(_fixtures_dir): for file in files: if file.startswith("fixture_") and file.endswith(".py"): full_path = os.path.join(root, file) import_path = full_path.replace(_fixtures_dir, "").replace("\\", ".").replace("/", ".").replace(".py", "") _fixtures_paths.append("fixtures" + import_path) pytest_plugins = _fixtures_paths # pytest hook函数 # https://docs.pytest.org/en/latest/reference/reference.html#hooks def pytest_terminal_summary(terminalreporter, exitstatus, config): total = terminalreporter._numcollected passed = len(terminalreporter.stats.get('passed', [])) failed = len(terminalreporter.stats.get('failed', [])) error = len(terminalreporter.stats.get('error', [])) skipped = len(terminalreporter.stats.get('skipped', [])) duration = time.time() - terminalreporter._sessionstarttime
[ { "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
conftest.py
dongfanger/httpbin
import pytest import logging from traitlets.config.loader import PyFileConfigLoader from traitlets import TraitError from jupyter_telemetry.eventlog import EventLog GOOD_CONFIG = """ import logging c.EventLog.handlers = [ logging.StreamHandler() ] """ BAD_CONFIG = """ import logging c.EventLog.handlers = [ 0 ] """ def get_config_from_file(path, content): # Write config file filename = 'config.py' config_file = path / filename config_file.write_text(content) # Load written file. loader = PyFileConfigLoader(filename, path=str(path)) cfg = loader.load_config() return cfg def test_good_config_file(tmp_path): cfg = get_config_from_file(tmp_path, GOOD_CONFIG) # Pass config to EventLog e = EventLog(config=cfg) # Assert the assert len(e.handlers) > 0 assert isinstance(e.handlers[0], logging.Handler) def test_bad_config_file(tmp_path): cfg = get_config_from_file(tmp_path, BAD_CONFIG) with pytest.raises(TraitError): e = EventLog(config=cfg)
[ { "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
tests/test_eventlog.py
blink1073/telemetry
from . import extension from torchaudio._internal import module_utils as _mod_utils from torchaudio import ( compliance, datasets, kaldi_io, utils, sox_effects, transforms ) from torchaudio.backend import ( list_audio_backends, get_audio_backend, set_audio_backend, save_encinfo, sox_signalinfo_t, sox_encodinginfo_t, get_sox_option_t, get_sox_encoding_t, get_sox_bool, SignalInfo, EncodingInfo, ) from torchaudio.sox_effects import ( init_sox_effects as _init_sox_effects, shutdown_sox_effects as _shutdown_sox_effects, ) try: from .version import __version__, git_version # noqa: F401 except ImportError: pass @_mod_utils.deprecated( "Please remove the function call to initialize_sox. " "Resource initialization is now automatically handled.") def initialize_sox() -> int: """Initialize sox effects. This function is deprecated. See ``torchaudio.sox_effects.init_sox_effects`` """ _init_sox_effects() @_mod_utils.deprecated( "Please remove the function call to torchaudio.shutdown_sox. " "Resource clean up is now automatically handled. " "In the unlikely event that you need to manually shutdown sox, " "please use torchaudio.sox_effects.shutdown_sox_effects.") def shutdown_sox(): """Shutdown sox effects. This function is deprecated. See ``torchaudio.sox_effects.shutdown_sox_effects`` """ _shutdown_sox_effects()
[ { "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
torchaudio/__init__.py
mmxgn/audio
"""empty message Revision ID: 0059 add show_banner_text Revises: 0058 set all has_banner_text Create Date: 2021-10-04 00:10:14.535185 """ # revision identifiers, used by Alembic. revision = '0059 add show_banner_text' down_revision = '0058 set all has_banner_text' from alembic import op import sqlalchemy as sa def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.add_column('events', sa.Column( 'show_banner_text', sa.Boolean(), nullable=True, server_default="True" ) ) op.drop_column('events', 'has_banner_text') # ### end Alembic commands ### def downgrade(): # ### commands auto generated by Alembic - please adjust! ### op.add_column('events', sa.Column('has_banner_text', sa.BOOLEAN(), autoincrement=False, nullable=True)) op.drop_column('events', 'show_banner_text') # ### end Alembic commands ###
[ { "point_num": 1, "id": "every_function_has_docstring", "question": "Does every function in this file have a docstring?", "answer": false }, { "point_num": 2, "id": "every_function_under_20_lines", "question": "Is every function in this file shorter than 20 lines?", "answer": tru...
3
migrations/versions/0059.py
NewAcropolis/api
import os import shutil from openeo.file import File class RESTFile(File): """Represents a file of openeo.""" def download_file(self, target): """ Downloads a user file to the back end. :param target: local path, where the file should be saved. :return: status: Response status code """ # GET /files/{user_id}/{path} path = "/files/{}/{}".format(self.connection.userid, self.path) resp = self.connection.get(path, stream=True) if resp.status_code == 200: with open(target, 'wb') as f: shutil.copyfileobj(resp.raw, f) return resp.status_code else: return resp.status_code def upload_file(self, source): """ Uploads a user file to the back end. :param source: Local path to the file that should be uploaded. :return: status: True if it was successful, False otherwise """ if not os.path.isfile(source): return False if not self.path: self.path = os.path.basename(source) with open(source, 'rb') as f: input_file = f.read() path = "/files/{}/{}".format(self.connection.userid, self.path) content_type = {'Content-Type': 'application/octet-stream'} resp = self.connection.put(path=path, headers=content_type, data=input_file) return resp.status_code def delete_file(self): """ Deletes a user file in the back end. :return: status: True if it was successful, False otherwise """ path = "/users/{}/{}".format(self.connection.userid, self.path) resp = self.connection.delete(path) return resp.status_code
[ { "point_num": 1, "id": "every_function_under_20_lines", "question": "Is every function in this file shorter than 20 lines?", "answer": false }, { "point_num": 2, "id": "every_function_has_docstring", "question": "Does every function in this file have a docstring?", "answer": tru...
3
openeo/rest/rest_file.py
clausmichele/openeo-python-client
# import Flask and pymongo from flask import Flask, render_template from flask_pymongo import PyMongo # import scrape_mars.py import scrape_mars # Create an app, being sure to pass __name__ app = Flask(__name__) # Create connection variable to load in mongo = PyMongo(app, uri="mongodb://localhost:27017/mars_info") # Define app route @app.route("/") def index(): mars = mongo.db.collection.find_one() return render_template("index.html", mars_data=mars) # Define what to do when a user hits the /scrape route @app.route("/scrape") def scrape(): mars=mongo.db.collection mars_data = scrape_mars.scrape() # Update the Mongo database using update and upsert=True mongo.db.collection.update({}, mars_data, upsert=True) return redirect("/") if __name__ == "__main__": app.run(debug=True)
[ { "point_num": 1, "id": "has_nested_function_def", "question": "Does this file contain any function defined inside another function?", "answer": false }, { "point_num": 2, "id": "every_function_under_20_lines", "question": "Is every function in this file shorter than 20 lines?", ...
3
app.py
obfrap/web-scraping-challenge
import typing as t import ssl from motor.motor_asyncio import AsyncIOMotorClient from starlette.middleware.base import BaseHTTPMiddleware from starlette.requests import Request from starlette.responses import JSONResponse, Response from backend.constants import DATABASE_URL, DOCS_PASSWORD, MONGO_DATABASE class DatabaseMiddleware(BaseHTTPMiddleware): async def dispatch(self, request: Request, call_next: t.Callable) -> Response: client: AsyncIOMotorClient = AsyncIOMotorClient( DATABASE_URL, ssl_cert_reqs=ssl.CERT_NONE ) db = client[MONGO_DATABASE] request.state.db = db response = await call_next(request) return response class ProtectedDocsMiddleware(BaseHTTPMiddleware): async def dispatch(self, request: Request, call_next: t.Callable) -> Response: if DOCS_PASSWORD and request.url.path.startswith("/docs"): if request.cookies.get("docs_password") != DOCS_PASSWORD: return JSONResponse({"status": "unauthorized"}, status_code=403) resp = await call_next(request) return resp
[ { "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
backend/middleware.py
MrGrote/forms-backend
import asyncio async def upper_cased(value: str) -> str: await asyncio.sleep(1) return value.upper() coroutines = [ upper_cased("h"), upper_cased("e"), upper_cased("l"), upper_cased("l"), upper_cased("o"), upper_cased(" "), upper_cased("w"), upper_cased("o"), upper_cased("r"), upper_cased("l"), upper_cased("d"), ] async def main(): print("".join(await asyncio.gather(*coroutines))) if __name__ == '__main__': asyncio.run(main())
[ { "point_num": 1, "id": "every_function_has_docstring", "question": "Does every function in this file have a docstring?", "answer": false }, { "point_num": 2, "id": "all_return_types_annotated", "question": "Does every function in this file have a return type annotation?", "answe...
3
python/concurrency/async_hello.py
cbare/Etudes
from svs.models import Customer from django.db import models from django.utils import timezone from svs.models import Customer, Machine from core.models import CoreUser from markdownx.models import MarkdownxField STATUSES = ( ("pending_our", "Pending - Our Side"), ("pending_their", "Pending - Their Side"), ("timeout", "More Than a Week"), ("closed", "Closed 😁"), ) class Issue(models.Model): created_at = models.DateTimeField(default=timezone.now) title = models.CharField(max_length=255) contact = models.CharField(max_length=255) customer = models.ForeignKey(Customer, on_delete=models.CASCADE) user = models.ForeignKey(CoreUser, on_delete=models.CASCADE) machine = models.ForeignKey(Machine, on_delete=models.CASCADE) description = MarkdownxField() status = models.CharField( max_length=20, choices=STATUSES, null=False, default="pending_ours" ) def __str__(self) -> str: return self.title class IssueEntry(models.Model): issue = models.ForeignKey(Issue, on_delete=models.CASCADE) created_at = models.DateTimeField(default=timezone.now) title = models.CharField(max_length=255) description = MarkdownxField() def __str__(self) -> str: return self.title class Meta: verbose_name_plural = "Entries"
[ { "point_num": 1, "id": "every_class_has_docstring", "question": "Does every class in this file have a docstring?", "answer": false }, { "point_num": 2, "id": "all_return_types_annotated", "question": "Does every function in this file have a return type annotation?", "answer": tr...
3
issues/models.py
mariofix/svsagro