source
string
points
list
n_points
int64
path
string
repo
string
import logging import json import os import argparse import tensorflow as tf import numpy as np from contextlib import contextmanager import fcntl logger = logging.getLogger(__name__) def save_to_json(data, f_name): with tf.io.gfile.GFile(f_name, 'w') as writer: writer.write(json.dumps(data, cls=JSONEncoder, indent=4)) class JSONEncoder(json.JSONEncoder): def default(self, obj): if isinstance(obj, np.integer): return int(obj) elif isinstance(obj, np.floating): return float(obj) elif isinstance(obj, np.ndarray): return obj.tolist() else: return super(MyEncoder, self).default(obj) class ArgParseDefault(argparse.ArgumentParser): """Simple wrapper which shows defaults in help""" def __init__(self, **kwargs): super().__init__(**kwargs, formatter_class=argparse.ArgumentDefaultsHelpFormatter) def add_bool_arg(parser, name, default=False, help=''): group = parser.add_mutually_exclusive_group(required=False) group.add_argument('--' + name, dest=name, action='store_true', help=help) group.add_argument('--do_not_' + name, dest=name, action='store_false') parser.set_defaults(**{name: default}) @contextmanager def file_lock(fd): """ Locks FD before entering the context, always releasing the lock. """ try: fcntl.flock(fd, fcntl.LOCK_EX) yield finally: fcntl.flock(fd, fcntl.LOCK_UN)
[ { "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
utils/misc.py
francoispichard/covid_twitter_bert_imbalanced
# Tweepy # Copyright 2009-2010 Joshua Roesslein # See LICENSE for details. from __future__ import print_function import six class TweepError(Exception): """Tweepy exception""" def __init__(self, reason, response=None, api_code=None): self.reason = six.text_type(reason) self.response = response self.api_code = api_code Exception.__init__(self, reason) def __str__(self): return self.reason def is_rate_limit_error_message(message): """Check if the supplied error message belongs to a rate limit error.""" return isinstance(message, list) \ and len(message) > 0 \ and 'code' in message[0] \ and message[0]['code'] == 88 class RateLimitError(TweepError): """Exception for Tweepy hitting the rate limit.""" # RateLimitError has the exact same properties and inner workings # as TweepError for backwards compatibility reasons. pass
[ { "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_class_has_docstring", "question": "Does every class in this file have a docstring?...
3
tweepy/error.py
Wolfofcryptos/tweepy
import json def respond(err, res=None): return { 'statusCode': 400 if err else 200, 'body': 'Python error' if err else json.dumps(res), 'message': 'Python error' if err else res.get('message'), 'headers': { 'Content-Type': 'application/json' } } def parse_parameters(event): e = None returnParameters = {} try: if event.get('queryStringParameters',False): returnParameters = event['queryStringParameters'].copy() except Exception as e: print(e) returnParameters = {} return {'querystring_params:': returnParameters, 'err':e} def handler(event, context): validated_parameters = {} response = {} try: validated_parameters = parse_parameters(event) except Exception as e: return respond(e, validated_parameters.get('querystring_params', None)) response = validated_parameters response['message'] = 'Hello Serverless World' return respond(None, response)
[ { "point_num": 1, "id": "every_function_has_docstring", "question": "Does every function in this file have a docstring?", "answer": false }, { "point_num": 2, "id": "no_function_exceeds_5_params", "question": "Does every function in this file take 5 or fewer parameters (excluding sel...
3
src/python_lambdas/hello_world.py
jonwhittlestone/lambda-api-boto3
#!/usr/bin/env python3 import sys import os import argparse def read_params(args): parser = argparse.ArgumentParser(description='Convert LEfSe output to ' 'Circlader input') parser.add_argument( 'inp_f', metavar='INPUT_FILE', nargs='?', default=None, type=str, help="the input file [stdin if not present]") parser.add_argument( 'out_f', metavar='OUTPUT_FILE', nargs='?', default=None, type=str, help="the output file [stdout if not present]") parser.add_argument('-l', metavar='levels with label', default=0, type=int) return vars(parser.parse_args()) def lefse2circlader(par): finp,fout = bool(par['inp_f']), bool(par['out_f']) with open(par['inp_f']) if finp else sys.stdin as inpf: put_bm = (l.strip().split('\t') for l in inpf.readlines()) biomarkers = [p for p in put_bm if len(p) > 2] circ = [ [ b[0], "" if b[0].count('.') > par['l'] else b[0].split('.')[-1], b[2], b[2]+"_col" ] for b in biomarkers] with open(par['out_f'],'w') if fout else sys.stdout as out_file: for c in circ: out_file.write( "\t".join( c ) + "\n" ) if __name__ == '__main__': params = read_params(sys.argv) lefse2circlader(params)
[ { "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
lefse2circlader.py
bvaisvil/lefse
#!/usr/bin/env python # -*- coding: utf-8 -*- # Author: Benjamin Vial # License: MIT import pytest from gyptis.utils.parallel import * def f(x, y, a=1, b="b"): print(f"f called with {x} {y} {a} {b}") y = x ** 2 print(f"output y = {x}^2 = {y}") return y @parloop(n_jobs=4) def fpar(x, *args, **kwargs): return f(x, *args, **kwargs) def test_para(): x = [1, 2, 3, 4] y = [f(_, 9) for _ in x] ypar = fpar(x, 9) assert ypar == y def test_mpi_print(): mpi_print("Hello world!")
[ { "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
tests/test_parallel.py
benvial/gyptis
# python3 # Copyright 2018 DeepMind Technologies Limited. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Rescaling layers (e.g. to match action specs).""" import dataclasses from acme import specs from jax import lax import jax.numpy as jnp @dataclasses.dataclass class ClipToSpec: """Clips inputs to within a BoundedArraySpec.""" spec: specs.BoundedArray def __call__(self, inputs: jnp.ndarray) -> jnp.ndarray: return jnp.clip(inputs, self.spec.minimum, self.spec.maximum) @dataclasses.dataclass class RescaleToSpec: """Rescales inputs in [-1, 1] to match a BoundedArraySpec.""" spec: specs.BoundedArray def __call__(self, inputs: jnp.ndarray) -> jnp.ndarray: scale = self.spec.maximum - self.spec.minimum offset = self.spec.minimum inputs = 0.5 * (inputs + 1.0) # [0, 1] output = inputs * scale + offset # [minimum, maximum] return output @dataclasses.dataclass class TanhToSpec: """Squashes real-valued inputs to match a BoundedArraySpec.""" spec: specs.BoundedArray def __call__(self, inputs: jnp.ndarray) -> jnp.ndarray: scale = self.spec.maximum - self.spec.minimum offset = self.spec.minimum inputs = lax.tanh(inputs) # [-1, 1] inputs = 0.5 * (inputs + 1.0) # [0, 1] output = inputs * scale + offset # [minimum, maximum] return output
[ { "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
acme/jax/networks/rescaling.py
ostap-viniavskyi/acme
import os import zlib import uuid import re def get_image(repository, name): """Get the full image name by integrating repository and image name. :param repository: The name of repository :param name: The short image name :returns: str: Full image name, format: repo/name. """ return "{repo}/{name}".format( repo=repository, name=name ) def is_running_in_k8s(): """Check if running in the kubernetes cluster.""" return os.path.isdir('/var/run/secrets/kubernetes.io/') def get_current_k8s_namespace(): """Get the current namespace of kubernetes.""" with open('/var/run/secrets/kubernetes.io/serviceaccount/namespace', 'r') as f: return f.readline() def get_default_target_namespace(): """Get the default target namespace, if running in the kubernetes cluster, will be current namespace, Otherwiase, will be "default". """ if not is_running_in_k8s(): return 'default' return get_current_k8s_namespace() def crc(file_name): """Compute a running Cyclic Redundancy Check checksum. :param file_name: The file name that's for crc checksum. """ prev = 0 for eachLine in open(file_name, "rb"): prev = zlib.crc32(eachLine, prev) return "%X" % (prev & 0xFFFFFFFF) def random_tag(): """Get a random tag.""" return str(uuid.uuid4()).split('-')[0] def camel_to_snake(name): """ Converts a string that is camelCase into snake_case """ name = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', name) return re.sub('([a-z0-9])([A-Z])', r'\1_\2', name).lower()
[ { "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
kubeflow/fairing/utils.py
suomitekai/fairing
# -*- coding: utf-8 -*- from scrapy.linkextractors import LinkExtractor from scrapy.spiders import CrawlSpider, Rule from tasksmanager.models import SpiderTask class DefaultCrawlerSpider(CrawlSpider): name = 'defaultcrawler' def __init__(self, *args, **kwargs): self.domain = kwargs.get('domain') self.url = kwargs.get('url') self.spider_conf_id = kwargs.get('spider_conf_id') self.start_urls = [self.url] self.allowed_domains = [self.domain] self.task = SpiderTask.objects.select_related('spider').get(pk=kwargs.get('task_id')) self.spider_conf = self.task.spider DefaultCrawlerSpider.rules = [ Rule(LinkExtractor(unique=True), callback='parse_page', follow=kwargs.get('follow', False)), ] super(DefaultCrawlerSpider, self).__init__(*args, **kwargs) def get_items_structure(self): item_structure = self.spider_conf.extractors.all() return item_structure def parse_page(self, response): structures = self.get_items_structure() for st in structures: if st.xpath: items = response.xpath(st.xpath) for item in items: yield self._extract_item_data(item, st) else: yield self._extract_item_data(response, st) def _extract_item_data(self, selector, structure): data = {} attributes = structure.attributes.all() for attr in attributes: data[attr.name] = selector.xpath(attr.xpath+"//text()").extract_first() print(data) return data
[ { "point_num": 1, "id": "all_params_annotated", "question": "Does every function parameter in this file have a type annotation (excluding self/cls)?", "answer": false }, { "point_num": 2, "id": "no_function_exceeds_5_params", "question": "Does every function in this file take 5 or fe...
3
scrapyapp/scrapyapp/spiders/DefaultCrawler.py
sharawy/genie_crawler
from werkzeug.security import generate_password_hash, check_password_hash from shopyoapi.init import db from flask_login import UserMixin from modules.course.models import Course from modules.lightcourse.models import LightCourse from modules.course.models import QuizHistory course_subs = db.Table('course_subs', db.Column('user_id', db.Integer, db.ForeignKey('users.id')), db.Column('course_id', db.Integer, db.ForeignKey('courses.id')) ) light_course_subs = db.Table('light_course_subs', db.Column('user_id', db.Integer, db.ForeignKey('users.id')), db.Column('light_course_id', db.Integer, db.ForeignKey('light_courses.id')) ) class User(UserMixin, db.Model): __tablename__ = 'users' id = db.Column(db.Integer, primary_key=True) email = db.Column(db.String(100)) password = db.Column(db.String(128)) name = db.Column(db.String(120)) role = db.Column(db.String(120)) pass_changed = db.Column(db.Boolean, default=False) courses = db.relationship("Course", secondary=course_subs, cascade = "all, delete")# !subs- teacher, students light_courses = db.relationship("LightCourse", secondary=light_course_subs, cascade = "all, delete")# !subs- teacher, students quiz_histories = db.relationship('QuizHistory', backref='person', lazy=True, cascade="all, delete, delete-orphan") grade_id = db.Column(db.Integer, db.ForeignKey('grades.id')) def set_hash(self, password): self.password = generate_password_hash(password, method="sha256") def check_hash(self, password): return check_password_hash(self.password, password) def insert(self): db.session.add(self) db.session.commit() def update(self): db.session.commit() def delete(self): db.session.delete(self) db.session.commit()
[ { "point_num": 1, "id": "has_multiple_inheritance", "question": "Does any class in this file use multiple inheritance?", "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
modules/auth/models.py
Maurilearn/learnings
# This example requires the 'members' privileged intents import diskord class MyClient(diskord.Client): async def on_ready(self): print(f'Logged in as {self.user} (ID: {self.user.id})') print('------') async def on_member_join(self, member): guild = member.guild if guild.system_channel is not None: to_send = f'Welcome {member.mention} to {guild.name}!' await guild.system_channel.send(to_send) intents = diskord.Intents.default() intents.members = True client = MyClient(intents=intents) client.run('token')
[ { "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
examples/new_member.py
Hype3808/diskord
#!/usr/bin/env python # -*- coding: utf-8 -*- ''' This is rumdom run node. subscribe No topcs. Publish 'cmd_vel' topic. mainly use for simple sample program by Takuya Yamaguhi. ''' import rospy import random from geometry_msgs.msg import Twist class RandomBot(): def __init__(self, bot_name="NoName"): # bot name self.name = bot_name # velocity publisher self.vel_pub = rospy.Publisher('cmd_vel', Twist,queue_size=1) def calcTwist(self): value = random.randint(1,1000) if value < 250: x = 0.2 th = 0 elif value < 500: x = 0.2 th = 0 elif value < 750: x = 0 th = 1 elif value < 1000: x = 0 th = -1 else: x = 0 th = 0 twist = Twist() twist.linear.x = x; twist.linear.y = 0; twist.linear.z = 0 twist.angular.x = 0; twist.angular.y = 0; twist.angular.z = th return twist def strategy(self): r = rospy.Rate(1) # change speed 1fps target_speed = 0 target_turn = 0 control_speed = 0 control_turn = 0 while not rospy.is_shutdown(): twist = self.calcTwist() print(twist) self.vel_pub.publish(twist) r.sleep() if __name__ == '__main__': rospy.init_node('random_run') bot = RandomBot('Random') bot.strategy()
[ { "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
burger_war_dev/scripts/randomRun.py
shendongqiang/burger_war_dev
"""initial database Revision ID: 4be2799e102a Revises: Create Date: 2018-11-28 20:39:45.470767 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = '4be2799e102a' down_revision = None branch_labels = None depends_on = None def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.create_table('puppy', sa.Column('name', sa.String(length=80), nullable=False), sa.PrimaryKeyConstraint('name') ) # ### end Alembic commands ### def downgrade(): # ### commands auto generated by Alembic - please adjust! ### op.drop_table('puppy') # ### end Alembic commands ###
[ { "point_num": 1, "id": "has_nested_function_def", "question": "Does this file contain any function defined inside another function?", "answer": false }, { "point_num": 2, "id": "every_function_has_docstring", "question": "Does every function in this file have a docstring?", "ans...
3
RESTBasic/migrations/versions/4be2799e102a_initial_database.py
vgeorgo/courses-python-udemy-create-websites-using-flask
import os import posixpath from enum import Enum from fastapi import Path, HTTPException from utils import security class UploadPath(str, Enum): default = "default" UPLOAD_PATH_DICT = { UploadPath.default: "default/" } def get_upload(upload_key: UploadPath = Path(..., description="上传文件块位置")): """ 获取文件上传目录 :param upload_key: :return: """ root_path = posixpath.abspath(UPLOAD_PATH_DICT[upload_key]) def func(folder): path = security.safe_join(root_path, folder) os.makedirs(path, exist_ok=True) return path return func class DownloadPath(str, Enum): default = "default" DOWNLOAD_PATH_DICT = { DownloadPath.default: "default/" } def get_download(download_key: DownloadPath = Path(..., description="下载文件块位置")): """ 获取下载文件路径 :param download_key: :return: """ root_path = posixpath.abspath(DOWNLOAD_PATH_DICT[download_key]) def func(folder): path = security.safe_join(root_path, folder) if not posixpath.exists(path): raise HTTPException(404, "The access file does not exist") for filename in os.listdir(path): return posixpath.join(path, filename), filename return func
[ { "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
app/file/config/__init__.py
SystemLight/T-fastapi
"""empty message Revision ID: 0076_add_intl_flag_to_provider Revises: 0075_create_rates_table Create Date: 2017-04-25 09:44:13.194164 """ # revision identifiers, used by Alembic. revision = "0076_add_intl_flag_to_provider" down_revision = "0075_create_rates_table" import sqlalchemy as sa from alembic import op def upgrade(): op.add_column( "provider_details", sa.Column( "supports_international", sa.Boolean(), nullable=False, server_default=sa.false(), ), ) op.add_column( "provider_details_history", sa.Column( "supports_international", sa.Boolean(), nullable=False, server_default=sa.false(), ), ) op.execute("UPDATE provider_details SET supports_international=True WHERE identifier='mmg'") op.execute("UPDATE provider_details_history SET supports_international=True WHERE identifier='mmg'") def downgrade(): op.drop_column("provider_details_history", "supports_international") op.drop_column("provider_details", "supports_international")
[ { "point_num": 1, "id": "any_function_over_40_lines", "question": "Is any function in this file longer than 40 lines?", "answer": false }, { "point_num": 2, "id": "every_function_has_docstring", "question": "Does every function in this file have a docstring?", "answer": false }...
3
migrations/versions/0076_add_intl_flag_to_provider.py
cds-snc/notifier-api
""" Migration script to create tables for tracking workflow invocations. """ from __future__ import print_function import datetime import logging from sqlalchemy import ( Column, DateTime, ForeignKey, Integer, MetaData, Table ) from galaxy.model.migrate.versions.util import ( create_table, drop_table ) log = logging.getLogger(__name__) now = datetime.datetime.utcnow metadata = MetaData() WorkflowInvocation_table = Table("workflow_invocation", metadata, Column("id", Integer, primary_key=True), Column("create_time", DateTime, default=now), Column("update_time", DateTime, default=now, onupdate=now), Column("workflow_id", Integer, ForeignKey("workflow.id"), index=True, nullable=False)) WorkflowInvocationStep_table = Table("workflow_invocation_step", metadata, Column("id", Integer, primary_key=True), Column("create_time", DateTime, default=now), Column("update_time", DateTime, default=now, onupdate=now), Column("workflow_invocation_id", Integer, ForeignKey("workflow_invocation.id"), index=True, nullable=False), Column("workflow_step_id", Integer, ForeignKey("workflow_step.id"), index=True, nullable=False), Column("job_id", Integer, ForeignKey("job.id"), index=True, nullable=False)) tables = [WorkflowInvocation_table, WorkflowInvocationStep_table] def upgrade(migrate_engine): print(__doc__) metadata.bind = migrate_engine metadata.reflect() for table in tables: create_table(table) def downgrade(migrate_engine): metadata.bind = migrate_engine metadata.reflect() for table in reversed(tables): drop_table(table)
[ { "point_num": 1, "id": "every_function_under_20_lines", "question": "Is every function in this file shorter than 20 lines?", "answer": true }, { "point_num": 2, "id": "every_function_has_docstring", "question": "Does every function in this file have a docstring?", "answer": fals...
3
lib/galaxy/model/migrate/versions/0041_workflow_invocation.py
lawrence14701/galaxy
import coffeewhale import time def main(): test_func() @coffeewhale.on_except def test_func(): print('start sleeping') time.sleep(1) print('after sleep') raise Exception() # coffeewhale.notify(url="https://hooks.slack.com/services/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", # result='hello world!') if __name__ == "__main__": main()
[ { "point_num": 1, "id": "every_function_has_docstring", "question": "Does every function in this file have a docstring?", "answer": false }, { "point_num": 2, "id": "every_function_under_20_lines", "question": "Is every function in this file shorter than 20 lines?", "answer": tru...
3
main.py
hongkunyoo/coffeewhale
from abc import ABC, abstractmethod from typing import List, Literal class StorageProvider(ABC): @abstractmethod def __init__(self, allow_db_create=False, if_table_exists: Literal['ignore', 'recreate'] = 'ignore'): pass ### MAIN INTERFACE ### # Function args are the split parts of a typical db (sql) query. # I've done this so it's easier to implement different concrete providers. # # fields ==> cols | aggregations # conds ==> where clause # modifer ==> projection | sort | group @abstractmethod def close_database(self) -> None: """Shuts down the database.""" pass # UPDATE/CREATE @abstractmethod def upsert(self, context: dict=None) -> None: """Updates or inserts a new user record with supplied data (cols + value dict).""" pass # READ @abstractmethod def query(self, context: dict=None) -> List[dict]: """Executes a query on users table and returns rows as list of dicts.""" pass # DELETE @abstractmethod def delete(self, context: dict=None) -> None: """Deletes record from users table.""" pass
[ { "point_num": 1, "id": "has_multiple_inheritance", "question": "Does any class in this file use multiple inheritance?", "answer": false }, { "point_num": 2, "id": "no_function_exceeds_5_params", "question": "Does every function in this file take 5 or fewer parameters (excluding self...
3
authlib/repo/provider/base_provider.py
jmrafael/Streamlit-Authentication
import RPi.GPIO as GPIO import logging log = logging.getLogger("gc.b") # Note choose a pin that has pull down on by default to avoid opening the door on reboot. DOORPIN = 17 ECHOPIN = 27 TRIGGERPIN = 22 REEDPIN = 23 def init(): """ Initializes GPIOS """ log.info("Setup GPIO") GPIO.setmode(GPIO.BCM) GPIO.setup(DOORPIN, GPIO.OUT) GPIO.setup(ECHOPIN, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) GPIO.setup(TRIGGERPIN, GPIO.OUT) GPIO.setup(REEDPIN, GPIO.IN, pull_up_down=GPIO.PUD_UP) def cleanup(): """ Cleans up GPIOS """ log.info("Clean up GPIOS") GPIO.cleanup()
[ { "point_num": 1, "id": "every_function_has_docstring", "question": "Does every function in this file have a docstring?", "answer": true }, { "point_num": 2, "id": "has_nested_function_def", "question": "Does this file contain any function defined inside another function?", "answ...
3
raspberry/src/board.py
mnordlund/GarageController
""" Example file on how to display a networkx graph on a browser """ import json import networkx as nx from networkx.readwrite import json_graph import http_server import random # https://www.alanzucconi.com/2015/11/03/recreational-maths-python/ # Converts a number in the list of its digits def int_to_list(n): # The number is firstly converted into a string using str(n) # map -> converts each character of the string into an integer return map(int, str(n)) # https://www.alanzucconi.com/2015/11/01/interactive-graphs-in-the-browser/ def toy_graph(): G = nx.DiGraph() for i in range(1, 1000): tree = list(set(list(int_to_list(random.randint(1, i))))) # Add the entire sequence to the tree for j in range(0, len(tree) - 1): G.add_edge(tree[j], tree[j + 1]) for n in G: G.node[n]['name'] = n d = json_graph.node_link_data(G) json.dump(d, open('graph/graph.json', 'w')) # The http_server is just a short piece of code that used to be in the # examples directory of the networkx library. http_server.load_url('graph/graph.html') if __name__ == '__main__': toy_graph()
[ { "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
program.py
dborbor/InteractiveGraph
try: from . import BASE, SESSION except ImportError: raise AttributeError from sqlalchemy import BigInteger, Column, Numeric, String, UnicodeText class Welcome(BASE): __tablename__ = "codwelcome" chat_id = Column(String(14), primary_key=True) previous_welcome = Column(BigInteger) reply = Column(UnicodeText) f_mesg_id = Column(Numeric) def __init__(self, chat_id, previous_welcome, reply, f_mesg_id): self.chat_id = str(chat_id) self.previous_welcome = previous_welcome self.reply = reply self.f_mesg_id = f_mesg_id Welcome.__table__.create(checkfirst=True) def get_welcome(chat_id): try: return SESSION.query(Welcome).get(str(chat_id)) finally: SESSION.close() def get_current_welcome_settings(chat_id): try: return SESSION.query(Welcome).filter(Welcome.chat_id == str(chat_id)).one() except BaseException: return None finally: SESSION.close() def add_welcome_setting(chat_id, previous_welcome, reply, f_mesg_id): to_check = get_welcome(chat_id) if not to_check: adder = Welcome(chat_id, previous_welcome, reply, f_mesg_id) SESSION.add(adder) SESSION.commit() return True rem = SESSION.query(Welcome).get(str(chat_id)) SESSION.delete(rem) SESSION.commit() adder = Welcome(chat_id, previous_welcome, reply, f_mesg_id) SESSION.commit() return False def rm_welcome_setting(chat_id): try: rem = SESSION.query(Welcome).get(str(chat_id)) if rem: SESSION.delete(rem) SESSION.commit() return True except BaseException: return False def update_previous_welcome(chat_id, previous_welcome): row = SESSION.query(Welcome).get(str(chat_id)) row.previous_welcome = previous_welcome SESSION.commit()
[ { "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
usercodex/sql_helper/welcome_sql.py
ipindanger/Codex-z
import os import pytest import time from linenotipy import Line @pytest.fixture(scope="module", autouse=True) def scope_module(): token = os.environ["line_notify_token"] yield Line(token=token) @pytest.fixture(scope="function", autouse=True) def line(scope_module): time.sleep(1) yield scope_module # @pytest.mark.skip def test_line_post_message(line): expected = "ok" actual = line.post(message="Hello, world.") assert expected == actual["message"] # @pytest.mark.skip def test_line_post_image(line): expected = "ok" actual = line.post(message="Hello, image.", imageFile="tests/test.png") assert expected == actual["message"] # @pytest.mark.skip def test_line_post_stamp(line): expected = "ok" actual = line.post(message="Hello, stamp.", stickerPackageId=3, stickerId=180) assert expected == actual["message"]
[ { "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
tests/test_linenotipy.py
10mohi6/line-notify-python
from pyramid_layout.layout import layout_config @layout_config(template='h:templates/base.pt') class BaseLayout(object): csp = None inline_webfont = True requirements = (('app', None),) def __init__(self, context, request): self.context = context self.request = request self.forms = {} def add_form(self, form): if form.formid in self.forms: raise ValueError('duplicate form id "%s"' % form.formid) self.forms[form.formid] = form def get_widget_requirements(self): requirements = [] requirements.extend(self.requirements) for form in self.forms.values(): requirements.extend(form.get_widget_requirements()) return requirements def get_widget_resources(self): requirements = self.get_widget_requirements() return self.request.registry.resources(requirements) @property def css_links(self): return self.get_widget_resources()['css'] @property def js_links(self): return self.get_widget_resources()['js'] @layout_config(name='sidebar', template='h:templates/base.pt') class SidebarLayout(BaseLayout): requirements = (('app', None), ('sidebar', None)) def includeme(config): config.include('pyramid_layout') config.scan(__name__)
[ { "point_num": 1, "id": "more_functions_than_classes", "question": "Does this file define more functions than classes?", "answer": true }, { "point_num": 2, "id": "every_function_has_docstring", "question": "Does every function in this file have a docstring?", "answer": false }...
3
h/layouts.py
gnott/h
import ray from copy import deepcopy from leaderboard.leaderboard_evaluator import LeaderboardEvaluator from leaderboard.utils.statistics_manager import StatisticsManager @ray.remote(num_cpus=1./8, num_gpus=1./4, max_restarts=100, max_task_retries=-1) class ScenarioRunner(): def __init__(self, args, scenario_class, scenario, route, checkpoint='simulation_results.json', town=None, port=1000, tm_port=1002, debug=False): args = deepcopy(args) # Inject args args.scenario_class = scenario_class args.town = town args.port = port args.trafficManagerPort = tm_port args.scenarios = scenario args.routes = route args.debug = debug args.checkpoint = checkpoint args.record = '' self.runner = LeaderboardEvaluator(args, StatisticsManager()) self.args = args def run(self): return self.runner.run(self.args)
[ { "point_num": 1, "id": "all_params_annotated", "question": "Does every function parameter in this file have a type annotation (excluding self/cls)?", "answer": false }, { "point_num": 2, "id": "has_multiple_inheritance", "question": "Does any class in this file use multiple inherita...
3
runners/scenario_runner.py
cgeller/WorldOnRails
# # softmax paddle model generator # import numpy as np import sys from save_model import saveModel def softmax(name: str, x, axis): import paddle as pdpd pdpd.enable_static() node_x = pdpd.static.data(name='x', shape=x.shape, dtype='float32') out = pdpd.nn.functional.softmax(x=node_x, axis=axis) cpu = pdpd.static.cpu_places(1) exe = pdpd.static.Executor(cpu[0]) # startup program will call initializer to initialize the parameters. exe.run(pdpd.static.default_startup_program()) outs = exe.run( feed={'x': x}, fetch_list=[out]) saveModel(name, exe, feedkeys=['x'], fetchlist=[out], inputs=[x], outputs=[outs[0]], target_dir=sys.argv[1]) return outs[0] def main(): data = np.array( [[[2.0, 3.0, 4.0, 5.0], [3.0, 4.0, 5.0, 6.0], [7.0, 8.0, 8.0, 9.0]], [[1.0, 2.0, 3.0, 4.0], [5.0, 6.0, 7.0, 8.0], [6.0, 7.0, 8.0, 9.0]]] ).astype(np.float32) softmax("softmax", data, axis=1) softmax("softmax_minus", data, axis=-1) if __name__ == "__main__": main()
[ { "point_num": 1, "id": "every_function_has_docstring", "question": "Does every function in this file have a docstring?", "answer": false }, { "point_num": 2, "id": "every_function_under_20_lines", "question": "Is every function in this file shorter than 20 lines?", "answer": tru...
3
src/core/tests/frontend/paddlepaddle/test_models/gen_scripts/generate_softmax.py
ytorzuk-altran/openvino
#!/usr/bin/env python3 from typing import Dict from iometrics.example import usage from iometrics.pytorch_lightning.callbacks import LOG_KEY_DISK_UTIL from iometrics.pytorch_lightning.callbacks import NetworkAndDiskStatsMonitor def test_all_metrics() -> None: last_row = usage(1) assert "0.0" in last_row def test_pytorch_lightning_epoch_start() -> None: net_disk_stats = NetworkAndDiskStatsMonitor() net_disk_stats.on_epoch_start(trainer=None, pl_module=None) first_logs: Dict[str, float] = net_disk_stats._get_new_logs() assert LOG_KEY_DISK_UTIL in first_logs assert 0.0 in first_logs.values() def test_pytorch_lightning_only_get_new_logs() -> None: net_disk_stats = NetworkAndDiskStatsMonitor() first_logs: Dict[str, float] = net_disk_stats._get_new_logs() assert LOG_KEY_DISK_UTIL in first_logs assert 0.0 in first_logs.values()
[ { "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": "every_function_under_20_lines", "question": "Is every function in this file shorter than 20 lines?", "an...
3
tests/test_iometrics.py
moritazy/iometrics
# 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 RoaRequest class ListDegradeControlsRequest(RoaRequest): def __init__(self): RoaRequest.__init__(self, 'Edas', '2017-08-01', 'ListDegradeControls') self.set_uri_pattern('/pop/v5/app/degradeControls') self.set_method('GET') def get_AppId(self): return self.get_query_params().get('AppId') def set_AppId(self,AppId): self.add_query_param('AppId',AppId)
[ { "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
aliyun-python-sdk-edas/aliyunsdkedas/request/v20170801/ListDegradeControlsRequest.py
sdk-team/aliyun-openapi-python-sdk
''' SIGNUS V1 post API ''' from flask import g from app.api.signus_v1 import signus_v1 as api from app.api.decorators import timer, login_required, login_optional from app.controllers.post import (post_like, post_unlike, post_view) @api.route("/post/like/<string:post_oid>", methods=["PATCH"]) @timer @login_required def signus_v1_post_like(post_oid): ''' 게시글 좋아요 ''' return { "msg": "success", "result": post_like(g.mongo_cur, post_oid, g.user) } @api.route("/post/unlike/<string:post_oid>", methods=["PATCH"]) @timer @login_required def signus_v1_post_unlike(post_oid): ''' 게시글 좋아요 취소 ''' return { "msg": "success", "result": post_unlike(g.mongo_cur, post_oid, g.user) } @api.route("/post/view/<string:post_oid>", methods=["PATCH"]) @timer @login_optional def signus_v1_post_view(post_oid): ''' 게시글 조회수 ''' if 'user' in g: result = post_view(g.mongo_cur, post_oid, g.user) else: result = post_view(g.mongo_cur, post_oid) return { "msg": "success", "result": result }
[ { "point_num": 1, "id": "no_function_exceeds_5_params", "question": "Does every function in this file take 5 or fewer parameters (excluding self/cls)?", "answer": true }, { "point_num": 2, "id": "every_function_has_docstring", "question": "Does every function in this file have a docs...
3
SIGNUS/app/api/signus_v1/post.py
837477/SIGNUS
#! /Users/gabriel.hernandez/.virtualenvs/better/bin/python from lifxlan import LifxLAN import time aqua = (180, 94.31, 100) orag = (37, 100, 100) pink = (308, 81.18, 100) max_range = 65535 hue_range = 360 sat_bri_r = 100 FPS = 60 # dt is the time delta in seconds (float). class LaserCatTheme(): def __init__(self): self.client = LifxLAN() self.lights = self.client.get_lights() self.colors = [aqua, orag, pink] self.speed = 0.025 def convert_hsb_to_65k_range(self, h, s, b): return ((h * max_range / hue_range), (s * max_range / sat_bri_r), (b * max_range / sat_bri_r), 3500) def set_theme(self, offset=0): for i, light in enumerate(self.lights): try: light.set_color(self.convert_hsb_to_65k_range(*self.colors[(i + offset) % len(self.colors)])) except: print('some shit went wrong yo, try and learn what. maybe...') def game_logic(self, dt): self.set_theme(int(self.speed * dt)) if __name__=="__main__": instance = LaserCatTheme() instance.set_theme() lastFrameTime = 0 while True: currentTime = time.time() dt = currentTime - lastFrameTime lastFrameTime = currentTime sleepTime = 1./FPS - (currentTime - lastFrameTime) if sleepTime > 0: time.sleep(sleepTime) instance.game_logic(dt)
[ { "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
laser-cat.py
webspinner/lifxlan-themes
from pairs.ir.block import pairs_block from pairs.ir.variables import VarDecl from pairs.sim.lowerable import Lowerable class VariablesDecl(Lowerable): def __init__(self, sim): super().__init__(sim) @pairs_block def lower(self): for v in self.sim.vars.all(): VarDecl(self.sim, v)
[ { "point_num": 1, "id": "more_functions_than_classes", "question": "Does this file define more functions than classes?", "answer": true }, { "point_num": 2, "id": "has_nested_function_def", "question": "Does this file contain any function defined inside another function?", "answe...
3
src/pairs/sim/variables.py
rafaelravedutti/pairs
from abc import ABC, abstractmethod from status import Status class State(ABC): def __init__(self, turret_controls, body_controls, status: Status): self.turret_controls = turret_controls self.body_controls = body_controls self.status = status @abstractmethod def perform(self): pass @abstractmethod def calculate_priority(self, is_current_state: bool): pass
[ { "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
src/states/state.py
Iain530/do-you-have-the-guts2018
from numba.cuda.testing import unittest, SerialMixin, skip_on_cudasim from numba import cuda from numba.core import config class MyError(Exception): pass regex_pattern = ( r'In function [\'"]test_exc[\'"], file [\:\.\/\\\-a-zA-Z_0-9]+, line \d+' ) class TestUserExc(SerialMixin, unittest.TestCase): def test_user_exception(self): @cuda.jit("void(int32)", debug=True) def test_exc(x): if x == 1: raise MyError elif x == 2: raise MyError("foo") test_exc[1, 1](0) # no raise with self.assertRaises(MyError) as cm: test_exc[1, 1](1) if not config.ENABLE_CUDASIM: self.assertRegexpMatches(str(cm.exception), regex_pattern) self.assertIn("tid=[0, 0, 0] ctaid=[0, 0, 0]", str(cm.exception)) with self.assertRaises(MyError) as cm: test_exc[1, 1](2) if not config.ENABLE_CUDASIM: self.assertRegexpMatches(str(cm.exception), regex_pattern) self.assertRegexpMatches(str(cm.exception), regex_pattern) self.assertIn("tid=[0, 0, 0] ctaid=[0, 0, 0]: foo", str(cm.exception)) 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": "more_functions_than_classes", "question": "Does this file define more functions than classes?", "answe...
3
numba/cuda/tests/cudapy/test_userexc.py
ARF1/numba
# Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT license. import unittest import ast from textwrap import dedent import inspect from typing import List, Tuple from pyis.onnx.transpiler.passes.type_infer import TypeInfer from pyis.onnx.transpiler.ast_printer import pformat_ast class SubModel: def __init__(self) -> None: pass def run(self, q: str) -> Tuple[str, List[int]]: return ('hello', [1, 2, 3]) class Model2: def __init__(self) -> None: self.sub_model = SubModel() def run(self, q: str): q_copy = q q_copy1, q_copy2 = q, q int1 = 42 float1 = 4.2 str1 = '42' o1, o2 = self.sub_model.run(str1) return (o1, o2) class TestResolveFunction(unittest.TestCase): def test_resolve_function_call(self): source = dedent(dedent(inspect.getsource(Model2.run))) t = ast.parse(source) m = Model2() pass1 = TypeInfer(m, t) pass1.run() pass1.print_type_dict() self.assertDictEqual(pass1.get_type_dict(), { "q": str, "q_copy": str, "q_copy1": str, "q_copy2": str, "int1": int, "float1": float, "str1": str, "o1": str, "o2": List[int] }) if __name__ == "__main__": unittest.main()
[ { "point_num": 1, "id": "all_function_names_snake_case", "question": "Are all function names in this file written in snake_case?", "answer": true }, { "point_num": 2, "id": "every_function_has_docstring", "question": "Does every function in this file have a docstring?", "answer":...
3
py/pyis-onnx/tests/test_transpiler/test_resolve_function.py
microsoft/python-inference-script
import logging class BaseResponseHandler: def on_execution(self, event): logging.debug(event) return event def on_exception(self, ex): logging.exception(str(ex)) raise def on_response(self, response): logging.debug(response) return response
[ { "point_num": 1, "id": "no_function_exceeds_5_params", "question": "Does every function in this file take 5 or fewer parameters (excluding self/cls)?", "answer": true }, { "point_num": 2, "id": "all_params_annotated", "question": "Does every function parameter in this file have a ty...
3
lambda_utils/response_handlers/__init__.py
Christoph-Schabert/lambda-utils
"""Helper definitions to glob .aar and .jar targets""" def create_aar_targets(aarfiles): for aarfile in aarfiles: name = "aars__" + aarfile[aarfile.rindex("/") + 1:aarfile.rindex(".aar")] lib_deps.append(":" + name) android_prebuilt_aar( name = name, aar = aarfile, ) def create_jar_targets(jarfiles): for jarfile in jarfiles: name = "jars__" + jarfile[jarfile.rindex("/") + 1:jarfile.rindex(".jar")] lib_deps.append(":" + name) prebuilt_jar( name = name, binary_jar = jarfile, )
[ { "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
Examples/ReactNativeKakaoExample/android/app/build_defs.bzl
namdq97/react-native-kakao-login
import seaborn as sns import numpy as np import pandas as pd import matplotlib.pyplot as plt class BoxPlot: def __init__( self, title, x_label, y_label, ): self.title = title self.x_label = x_label self.y_label = y_label self.data = pd.DataFrame() def add_data(self, data, label): self.data[label] = data def show(self): sns.boxplot(data=self.data, width=0.5, fliersize=2) plt.title(self.title) plt.xlabel(self.x_label) plt.ylabel(self.y_label) plt.show()
[ { "point_num": 1, "id": "no_function_exceeds_5_params", "question": "Does every function in this file take 5 or fewer parameters (excluding self/cls)?", "answer": true }, { "point_num": 2, "id": "every_function_has_docstring", "question": "Does every function in this file have a docs...
3
boxplot.py
guodashun/training-curve-vis
# pylint: disable=useless-super-delegation import json from concurrent.futures import ThreadPoolExecutor, Future import boto3 from oautom import get_logger from oautom.execution.execution import Execution class LambdaExecution(Execution): def __init__(self, name: str, flow: 'Flow', lambda_function: str, payload: dict = {}): super().__init__(name, flow) self._future = None # type: Future self._lambda_arn = lambda_function self._payload = payload def run(self): super().run() # self._logger.info(f"lambda: {self._lambda_arn}") with ThreadPoolExecutor(max_workers=1) as executor: self._future = executor.submit(_run_lambda, self._lambda_arn, self._payload) def check(self) -> bool: return self._future.done() def _run_lambda(lambda_function: str, payload: dict): logger = get_logger() logger.info(f"lambda: {lambda_function}") client = boto3.client('lambda') client.invoke( FunctionName=lambda_function, InvocationType='RequestResponse', LogType='None', Payload=json.dumps(payload), )
[ { "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
oautom/execution/lambda_execution.py
FabienArcellier/oautom
from collections import Counter import numpy as np from sklearn.metrics import accuracy_score, confusion_matrix def __majority(arr): counter = Counter(arr) value, _ = counter.most_common(1)[0] return value def clustering_accuracy(y_true, y_clustering): clustering_labels = list(set(y_clustering)) new_labels = np.zeros_like(y_clustering) for clustering_label in clustering_labels: locator = y_clustering == clustering_label locations = np.argwhere(locator) real_labels = y_true[locations].ravel() major_label = __majority(real_labels) new_labels[locator] = major_label return accuracy_score(y_true, new_labels) def confusion_matrix_majority(y_true, y_clustering): clustering_labels = list(set(y_clustering)) new_labels = np.zeros_like(y_clustering) for clustering_label in clustering_labels: locator = y_clustering == clustering_label locations = np.argwhere(locator) real_labels = y_true[locations].ravel() major_label = __majority(real_labels) new_labels[locator] = major_label return confusion_matrix(y_true, new_labels)
[ { "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
util/metric.py
smartdolphin/variational-autoencoder
from sparknlp.annotator import * class BertSentence: @staticmethod def get_default_model(): return BertSentenceEmbeddings.pretrained() \ .setInputCols("sentence") \ .setOutputCol("sentence_embeddings") @staticmethod def get_pretrained_model(name, language, bucket=None): return BertSentenceEmbeddings.pretrained(name,language,bucket) \ .setInputCols('sentence') \ .setOutputCol("sentence_embeddings")
[ { "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
nlu/components/embeddings/sentence_bert/BertSentenceEmbedding.py
milyiyo/nlu
from decimal import Decimal, ROUND_HALF_UP from django.test import TestCase from .utils import create_test_expenses from ..models import Expense from ..reports import summary_overall class ReportsTestCase(TestCase): """Test reports utilities for the expenses""" def setUp(self) -> None: """Set up for the reports utilities tests""" create_test_expenses() def test_summary_overall(self) -> None: """Test if summary_overall properly sums amount of expenses""" queryset = Expense.objects.all() result = summary_overall(queryset) self.assertEqual( result['overall'], Decimal(150.55).quantize(Decimal('0.01'), rounding=ROUND_HALF_UP) )
[ { "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
project/expenses/tests/test_reports.py
MaciejChoromanski/parleto-recruitment-task
# -*- coding: utf-8 -*- from bs4 import BeautifulSoup import pandas as pd # Likely coming from # https://www.google.com/maps/d/viewer?mid=151Itl_57S7UlpC7P-TdfvT2Pz7Y class KMLConverter(object): def __init__(self, filepath): self.filepath = filepath self.postes = [] self.parse() def clean_key(self, key): return { u'DÉPARTEMENT': 'departement', 'NB DE SAUVETEURS SNSM': 'nb_sauveteurs', 'CP': 'code_postal', 'VILLE': 'ville', }[key] def parse_coordinates(self, value): if value is None: return None, None parts = map(float, value.text.split(',')) latitude, longitude = parts[1], parts[0] return latitude, longitude def parse(self): with open(self.filepath, 'r') as f: soup = BeautifulSoup(f, 'xml') for placemark in soup.kml.Document.Folder.find_all('Placemark'): poste = {} poste['nom'] = placemark.find('name').text.strip() poste['latitude'], poste['longitude'] = self.parse_coordinates( placemark.find('coordinates') ) for data in placemark.ExtendedData.find_all('Data'): key, value = data['name'], data.text.strip() if key != 'gx_media_links': cleaned_key = self.clean_key(key) if cleaned_key == 'nb_sauveteurs': poste[cleaned_key] = int(float(value)) else: poste[cleaned_key] = value self.postes.append(poste) def to_csv(self, filepath): df = pd.DataFrame(self.postes) df = df.sort_values(by='code_postal').reset_index(drop=True) df.index += 1 df.to_csv(filepath, encoding='utf-8', index=True, index_label='id')
[ { "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
collecte/postes_plage_snsm/convert.py
entrepreneur-interet-general/predisauvetage
import numpy as np import cv2 import matplotlib.pyplot as plt import matplotlib.image as mpimg import pickle class Line(): def __init__(self,n): self.n=n self.detected =False #Polynomial coefficients of the lines self.A=[] self.B=[] self.C=[] #Running average of coefficients self.A_avg=0. self.B_avg=0. self.C_avg=0. def obtain_fit(self): return (self.A_avg,self.B_avg,self.C_avg) def update_fit(self,fit_coeffs): """Obtain the fit coefficients from the latest frame and apply over each of 2nd polynomial coefficients for the purpose of smoothing """ full_Q= len(self.A) >= self.n #Append line fit coefficients self.A.append(fit_coeffs[0]) self.B.append(fit_coeffs[1]) self.C.append(fit_coeffs[2]) if full_Q: _=self.A.pop(0) _=self.B.pop(0) _=self.C.pop(0) # Compute the average of the polynomial coefficients self.A_avg = np.mean(self.A) self.B_avg = np.mean(self.B) self.C_avg = np.mean(self.C) return (self.A_avg,self.B_avg,self.C_avg)
[ { "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": "all_function_names_snake_case", "question": "Are all function names in this file written in snake_case?", ...
3
line.py
kavach-feature/Advanced_lane_finding
from keras.models import load_model from glob import glob from metrics import auc, precision, recall, f1 def save_json(model, path): model_json = model.to_json() with open(path, "w") as json_file: json_file.write(model_json) def save_weights(model, path): model.save_weights(path) def resave_model(model_path, save_path): model = load_model(model_path, custom_objects={"auc": auc, "precision": precision, "recall": recall, "f1": f1}) save_json(model, save_path + '/model.json') save_weights(model, save_path + '/model.h5') if __name__ == '__main__': model_folders = glob('./model/saved_models/*') for model_folder in model_folders: models = sorted(glob(model_folder + '/*.hdf5')) last_model = models[-1] resave_model(last_model, model_folder) model_name = model_folder[model_folder.rfind('/') + 1:] print('Model {} resaved!'.format(model_name))
[ { "point_num": 1, "id": "no_function_exceeds_5_params", "question": "Does every function in this file take 5 or fewer parameters (excluding self/cls)?", "answer": true }, { "point_num": 2, "id": "every_function_has_docstring", "question": "Does every function in this file have a docs...
3
learning/model/keras_model_resave.py
eugene-vasilev/Automatic-Tool-Annotation-for-CATARACT-Surgery
""" Nonlinearities """ # sigmoid from theano.tensor.nnet import sigmoid # softmax (row-wise) from theano.tensor.nnet import softmax # tanh from theano.tensor import tanh # rectify # The following is faster than lambda x: T.maximum(0, x) # Thanks to @SnippyHolloW for pointing this out. # See: https://github.com/SnippyHolloW/abnet/blob/807aeb9/layers.py#L15 def rectify(x): return (x + abs(x)) / 2.0 # linear def linear(x): return x identity = linear
[ { "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
lasagne/nonlinearities.py
dimatura/nntools
# 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 DescribeDomainsBySourceRequest(RpcRequest): def __init__(self): RpcRequest.__init__(self, 'Cdn', '2014-11-11', 'DescribeDomainsBySource') def get_Sources(self): return self.get_query_params().get('Sources') def set_Sources(self,Sources): self.add_query_param('Sources',Sources) def get_SecurityToken(self): return self.get_query_params().get('SecurityToken') def set_SecurityToken(self,SecurityToken): self.add_query_param('SecurityToken',SecurityToken) def get_OwnerId(self): return self.get_query_params().get('OwnerId') def set_OwnerId(self,OwnerId): self.add_query_param('OwnerId',OwnerId)
[ { "point_num": 1, "id": "more_functions_than_classes", "question": "Does this file define more functions than classes?", "answer": true }, { "point_num": 2, "id": "all_params_annotated", "question": "Does every function parameter in this file have a type annotation (excluding self/cl...
3
aliyun-python-sdk-cdn/aliyunsdkcdn/request/v20141111/DescribeDomainsBySourceRequest.py
sdk-team/aliyun-openapi-python-sdk
#!/usr/bin/env python3 #import chardet import sys def readline_safe(): line = None while line == None: try: line = sys.stdin.readline() except: pass return line def main(): line = readline_safe() while line: if not line.startswith('CVE-') or line.split(',')[1] != 'Entry': line = readline_safe() continue desc_begin = line.find('\"') + 1 desc_len = line[desc_begin:].find('\"') while line[desc_begin + desc_len:desc_begin + desc_len + 2] == '\"\"': desc_len += line[desc_begin + desc_len + 2:].find('\"') + 2 print(line[desc_begin:desc_begin + desc_len].replace('\"\"', '\"')) print() line = readline_safe() main()
[ { "point_num": 1, "id": "every_function_under_20_lines", "question": "Is every function in this file shorter than 20 lines?", "answer": true }, { "point_num": 2, "id": "every_function_has_docstring", "question": "Does every function in this file have a docstring?", "answer": fals...
3
training_data/old/cve/cve_parser.py
rbenic-fer/security-report-generation
import pytest from pytest_mock import mocker from hamcrest import * import numpy as np from src.objects.quantum_system import SystemType from src.objects.qudit import Qudit from src.dirac_notation.constants import * @pytest.mark.parametrize('input', [ ( comp_ket_x(0, 4) ) ]) def test_init(input): system = Qudit(input) assert_that(system.children_systems, equal_to(None)) assert_that(system.system_type, equal_to(SystemType.simple)) @pytest.mark.parametrize('input', [ ( ket_0 ) ]) def test_init_fail(input): try: system = Qudit(input) pytest.fail() except AssertionError: pass @pytest.mark.parametrize('input_1,input_2', [ ( comp_ket_x(0, 8), comp_ket_x(0, 4) ) ]) def test_children_systems_1(input_1, input_2): system = Qudit(input_1) child_system = Qudit(input_2) system.children_systems = [child_system] assert_that(system.children_systems, equal_to([child_system])) assert_that(system.system_type, equal_to(SystemType.product)) @pytest.mark.parametrize('input', [ ( comp_ket_x(0, 8) ) ]) def test_children_systems_2(input): system = Qudit(input) system.children_systems = [] system.children_systems = None assert_that(system.children_systems, equal_to(None)) assert_that(system.system_type, equal_to(SystemType.simple))
[ { "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
tests/src/objects/test_qudit.py
KaroliShp/Quantumformatics
# # @lc app=leetcode id=349 lang=python3 # # [349] Intersection of Two Arrays # # @lc code=start class Solution: def binarySearch(self, nums: List[int], target: int) -> int: left = 0 right = len(nums) - 1 while left <= right: middle = (left + right) // 2 if nums[middle] == target: return middle elif nums[middle] < target: left = middle + 1 else: right = middle - 1 return -1 def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]: """ assume n, m are the length of lists and n < m sort the shorter list, O(nlogn) iterate longer list to search item in shorter list, O(mlogn) check if the value is in intersection list, O(n) time complexity : O(nlogn) + O(mlogn) + O(n) space complexity: O(nlogn) """ intersectList = [] if len(nums1) < len(nums2): nums1.sort() for v in nums2: pos = self.binarySearch(nums1, v) if pos != -1 and v not in intersectList: intersectList.append(v) else: nums2.sort() for v in nums1: pos = self.binarySearch(nums2, v) if pos != -1 and v not in intersectList: intersectList.append(v) return intersectList # @lc code=end
[ { "point_num": 1, "id": "every_function_under_20_lines", "question": "Is every function in this file shorter than 20 lines?", "answer": false }, { "point_num": 2, "id": "every_function_has_docstring", "question": "Does every function in this file have a docstring?", "answer": fal...
3
leetcode/349.intersection-of-two-arrays.py
zhongqi1112/Hulk
""" Routines to join all pdb files into one pdb file These routines were developed by: Rodrigo Antonio Faccioli - rodrigo.faccioli@usp.br / rodrigo.faccioli@gmail.com Leandro Oliveira Bortot - leandro.bortot@usp.br / leandro.obt@gmail.com """ import os import sys """ This function obtains all pdb files in mypath """ def get_PROT_IND_files_pdb(mypath): only_pdb_file = [] for root, dirs, files in os.walk(mypath): for file in files: #if file.endswith(".pdb"): if file.find("PROT_IND_") >=0: f_path = os.path.join(root,file) only_pdb_file.append(f_path) return only_pdb_file def main(): main_pdb_path = sys.argv[1] model = int(1) str_model = "MODEL #### \n" all_pdbs_path_file_name = os.path.join(main_pdb_path, "all_pdb.pdb") all_pdbs_file = open(all_pdbs_path_file_name, "w") pdb_files = get_PROT_IND_files_pdb(main_pdb_path) for pdb in pdb_files: #preparing Model aux_model = str_model.replace("####", str(model)) all_pdbs_file.write(aux_model) #Reading pdb files aux_pdb_file = open(pdb, "r") all_pdbs_file.write(aux_pdb_file.read()) aux_pdb_file.close() #Finishing Model all_pdbs_file.write("TER \n") all_pdbs_file.write("ENDMDL \n") #Next model model = model + 1 all_pdbs_file.close() main()
[ { "point_num": 1, "id": "every_function_has_docstring", "question": "Does every function in this file have a docstring?", "answer": false }, { "point_num": 2, "id": "every_function_under_20_lines", "question": "Is every function in this file shorter than 20 lines?", "answer": fal...
3
scripts/analysis/join_pdbs_one_pdb.py
michelleduarte/2pg_cartesian
import sys import numpy as np from scipy.stats import multivariate_normal sys.path.append('./../../') from src.HMC.hmcparameter import HMCParameter class VelParam(HMCParameter): def __init__(self, init_val): super().__init__(np.array(init_val)) dim = np.array(init_val).shape self.mu = np.zeros(dim) self.sigma = 1 def gen_init_value(self): self.value = multivariate_normal.rvs(self.mu, self.sigma) def get_energy_grad(self): return self.value def get_energy(self): return np.dot(self.value, self.value) / 2 def get_energy_for_value(self, value): return np.dot(value, value) / 2
[ { "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/LocalChoiceModel/vel_param.py
noashin/local_global_attention_model
__author__ = 'Pavel Ageyev' class Groups: def __init__(self, name , header, footer): self.name=name self.header=header self.footer=footer class Formfields: def __init__(self, firstName, lastName, companyName, email, mobile): self.firstName=firstName self.lastName=lastName self.companyName=companyName self.email=email self.mobile=mobile
[ { "point_num": 1, "id": "more_functions_than_classes", "question": "Does this file define more functions than classes?", "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
groupproperties.py
rolef/PyHomework
import logging import os import boto3 from lib.cleanup_resource_handler import CleanupResourceHandler from lib.queue_handler import QueueHandler logging.getLogger().setLevel(logging.INFO) def queue_handler(event, context): """ Handler for the event queue lambda trigger """ ec2_client = boto3.client('ec2') dynamodb_resource = boto3.resource('dynamodb') route53_client = boto3.client('route53') handler = QueueHandler(ec2_client=ec2_client, dynamodb_resource=dynamodb_resource, route53_client=route53_client, environ=os.environ) return handler.handle(event, context) def cleanup_resource_handler(event, context): """ Event handler for the custom resource. """ route53_client = boto3.client('route53') handler = CleanupResourceHandler(route53_client=route53_client) handler.handle_event(event, context)
[ { "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
packages/@aws-cdk-containers/ecs-service-extensions/lib/extensions/assign-public-ip/lambda/index.py
RichiCoder1/aws-cdk
from base import BaseTest import os import stat import unittest import sys INTEGRATION_TESTS = os.environ.get('INTEGRATION_TESTS', False) class TestUmask(BaseTest): """ Test default umask """ DEFAULT_UMASK = 0o027 def setUp(self): super(BaseTest, self).setUp() self.output_file_permissions = 0o666 self.render_config_template(output_file_permissions=self.output_file_permissions) proc = self.start_beat() self.wait_until(lambda: self.output_lines() > 0, max_timeout=2) proc.check_kill_and_wait() @unittest.skipIf(sys.platform.startswith("win"), "umask is not available on Windows") def test_output_file_perms(self): """ Test that output file permissions respect default umask """ output_file_path = os.path.join(self.working_dir, "output", "mockbeat") perms = stat.S_IMODE(os.lstat(output_file_path).st_mode) self.assertEqual(perms, self.output_file_permissions & ~TestUmask.DEFAULT_UMASK)
[ { "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
vendor/github.com/elastic/beats/libbeat/tests/system/test_umask.py
lstyles/nsgflowlogsbeat
class Model(object): """Base class for classification models.""" def __init__(self, path, **kwargs): self.path = path self.data = kwargs.get("data", []) self.labels = kwargs.get("labels", []) self.tokens = kwargs.get("tokens", []) self.predicted = kwargs.get("predicted", []) self.subtypes = kwargs.get("subtypes", []) self.scores = kwargs.get("scores", []) def reset(self): self.sids = [] self.sentences = [] self.data = [] self.labels = [] self.sids = [] self.tokens = [] self.results = [] self.predicted = [] self.scores = []
[ { "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
Scripts/classification/model.py
lasigeBioTM/ULISBOA-at-SemEval-2017
def preto(): return '\0331;30m' def vermelho(): return '\033[1;31m' def verde(): return '\033[1;32m' def amarelo(): return '\033[1;33m' def azul(): return '\033[1;34m' def magenta(): return '\033[1;35m' def ciano(): return '\033[1;36m' def cinzaclaro(): return '\033[1;37m' def cinzaescuro(): return '\033[1;90m' def vermelhoclaro(): return '\033[1;91m' def verdeclaro(): return '\033[1;92m' def amareloclaro(): return '\033[1;93m' def azulclaro(): return '\033[1;94m' def magentaclaro(): return '\033[1;95m' def cianoclaro(): return '\033[1;96m' def branco(): return '\033[1;97m' def retirarcor(): return '\033[m'
[ { "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
GDT/ferramentas/cores/__init__.py
GustavoHenriqueSchmitz/GDT
# -*- coding: utf-8 -*- """Test human2bytes function.""" import pytest from pcof import bytesconv @pytest.mark.parametrize( "size, unit, result", [ (1, "KB", "1024.00"), (1, "MB", "1048576.00"), (1, "GB", "1073741824.00"), (1, "TB", "1099511627776.00"), (1, "PB", "1125899906842624.00"), (1, "EB", "1152921504606846976.00"), ], ) def test_human2bytes(size, unit, result): assert bytesconv.human2bytes(size, unit) == result @pytest.mark.parametrize( "size, unit, precision, result", [ (1, "KB", 0, "1024"), (2, "GB", 0, "2147483648"), (2, "GB", 1, "2147483648.0"), (2, "GB", 3, "2147483648.000"), ], ) def test_human2bytes_precision(size, unit, precision, result): assert bytesconv.human2bytes(size, unit, precision=precision) == result @pytest.mark.parametrize( "size, unit, base, result", [ (1, "KB", 1000, "1000.00"), (1, "MB", 1000, "1000000.00"), (1, "GB", 1000, "1000000000.00"), (1, "TB", 1000, "1000000000000.00"), (4, "TB", 1000, "4000000000000.00"), (1, "PB", 1000, "1000000000000000.00"), (1, "EB", 1000, "1000000000000000000.00"), ], ) def test_human2bytes_base(size, unit, base, result): assert bytesconv.human2bytes(size, unit, base=base) == result def test_human2bytes_raise(): with pytest.raises(ValueError, match="value is not a number"): bytesconv.human2bytes("notnumber", "KB") with pytest.raises( ValueError, match="invalid unit. It must be KB, MB, GB, TB, PB, EB, ZB" ): bytesconv.human2bytes(1, "XX") # vim: ts=4
[ { "point_num": 1, "id": "all_function_names_snake_case", "question": "Are all function names in this file written in snake_case?", "answer": true }, { "point_num": 2, "id": "every_function_under_20_lines", "question": "Is every function in this file shorter than 20 lines?", "answ...
3
tests/test_bytesconv_human2bytes.py
thobiast/pcof
""" Main part of nuqql. """ import logging import os import signal import nuqql.backend import nuqql.config import nuqql.ui logger = logging.getLogger(__name__) # main loop of nuqql def main_loop() -> str: """ Main loop of nuqql. """ logger.debug("entering main loop") try: # init and start all backends nuqql.backend.start_backends() # loop as long as user does not quit while nuqql.ui.handle_input(): # update buddies nuqql.backend.update_buddies() # handle network input nuqql.backend.handle_network() finally: # shut down backends nuqql.backend.stop_backends() # quit nuqql return "" def _set_esc_delay() -> None: """ Configure ESC delay for curses """ os.environ.setdefault("ESCDELAY", nuqql.config.get("escdelay")) # main entry point def run() -> None: """ Main entry point of nuqql """ # does not go to nuqql log file logger.debug("starting nuqql") # parse command line arguments nuqql.config.parse_args() # ignore SIGINT signal.signal(signal.SIGINT, signal.SIG_IGN) # configure esc delay for curses _set_esc_delay() # initialize ui and run main_loop nuqql.ui.init(main_loop)
[ { "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": "every_function_has_docstring", "question": "Does every function in this file have a docstring?", "answer...
3
nuqql/main.py
hwipl/nuqql
import ipaddress from dataclasses import dataclass from typing import Optional, Union from caldera.util.ints import uint16, uint64 from caldera.util.streamable import Streamable, streamable @dataclass(frozen=True) @streamable class PeerInfo(Streamable): host: str port: uint16 def is_valid(self, allow_private_subnets=False) -> bool: ip: Optional[Union[ipaddress.IPv6Address, ipaddress.IPv4Address]] = None try: ip = ipaddress.IPv6Address(self.host) except ValueError: ip = None if ip is not None: if ip.is_private and not allow_private_subnets: return False return True try: ip = ipaddress.IPv4Address(self.host) except ValueError: ip = None if ip is not None: if ip.is_private and not allow_private_subnets: return False return True return False # Functions related to peer bucketing in new/tried tables. def get_key(self): try: ip = ipaddress.IPv6Address(self.host) except ValueError: ip_v4 = ipaddress.IPv4Address(self.host) ip = ipaddress.IPv6Address(int(ipaddress.IPv6Address("2002::")) | (int(ip_v4) << 80)) key = ip.packed key += bytes([self.port // 0x100, self.port & 0x0FF]) return key def get_group(self): # TODO: Port everything from Bitcoin. ipv4 = 1 try: ip = ipaddress.IPv4Address(self.host) except ValueError: ip = ipaddress.IPv6Address(self.host) ipv4 = 0 if ipv4: group = bytes([1]) + ip.packed[:2] else: group = bytes([0]) + ip.packed[:4] return group @dataclass(frozen=True) @streamable class TimestampedPeerInfo(Streamable): host: str port: uint16 timestamp: uint64
[ { "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": fals...
3
caldera/types/peer_info.py
wolfrage76/caldera-blockchain
""" Couette Flow """ import numpy as np from lettuce.unit import UnitConversion from lettuce.boundary import BounceBackBoundary, EquilibriumBoundaryPU class CouetteFlow2D(object): def __init__(self, resolution, reynolds_number, mach_number, lattice): self.resolution = resolution self.units = UnitConversion( lattice, reynolds_number=reynolds_number, mach_number=mach_number, characteristic_length_lu=resolution, characteristic_length_pu=1, characteristic_velocity_pu=1 ) def analytic_solution(self, x, t=0): # TODO raise NotImplementedError def initial_solution(self, x): return np.array([0*x[0]], dtype=float), np.array([0*x[0],0*x[1]], dtype=float) @property def grid(self): x = np.linspace(0, 1, num=self.resolution, endpoint=False) y = np.linspace(0, 1, num=self.resolution, endpoint=False) return np.meshgrid(x, y, indexing='ij') @property def boundaries(self): x, y = self.grid return [EquilibriumBoundaryPU(np.abs(y-1) < 1e-6, self.units.lattice, self.units, np.array([1.0, 0.0])), BounceBackBoundary(np.abs(y) < 1e-6, self.units.lattice)]
[ { "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
lettuce/flows/couette.py
MartinKliemank/lettuce
""" Created on Fri Oct 29 18:54:18 2021 @author: Krishna Nuthalapati """ import numpy as np def iou(boxA, boxB): # determine the (x, y)-coordinates of the intersection rectangle xA = max(boxA[0], boxB[0]) yA = max(boxA[1], boxB[1]) xB = min(boxA[2], boxB[2]) yB = min(boxA[3], boxB[3]) # compute the area of intersection rectangle interArea = max(0, xB - xA + 1) * max(0, yB - yA + 1) # compute the area of both the prediction and ground-truth # rectangles boxAArea = (boxA[2] - boxA[0] + 1) * (boxA[3] - boxA[1] + 1) boxBArea = (boxB[2] - boxB[0] + 1) * (boxB[3] - boxB[1] + 1) # compute the intersection over union by taking the intersection # area and dividing it by the sum of prediction + ground-truth # areas - the interesection area iou_score = interArea / float(boxAArea + boxBArea - interArea) # return the intersection over union value return iou_score def nms(boxes, scores, thresh): num_boxes = boxes.shape[0] indices = np.zeros((num_boxes), dtype=int) # print("PRINTING : ", num_boxes) for i in range(num_boxes): if indices[i] == -1: continue for j in range(i+1, num_boxes): if indices[j] == -1: continue base_box = boxes[i] curr_box = boxes[j] iou_score = iou(base_box, curr_box) if iou_score >= thresh: if scores[i]>scores[j]: indices[i] = 1 indices[j] = -1 continue indices[j] = 1 indices[i] = -1 idxs = np.where(indices == 1)[0] return idxs
[ { "point_num": 1, "id": "every_function_under_20_lines", "question": "Is every function in this file shorter than 20 lines?", "answer": false }, { "point_num": 2, "id": "no_function_exceeds_5_params", "question": "Does every function in this file take 5 or fewer parameters (excluding...
3
Object detection and depth estimation/catkin_ws/src/f110-fall2018-skeltons/labs/wall_following/scripts/utils/other.py
UF-f1tenth/F1tenth-UFL
import json import numpy as np from PIL import Image def load_json(f): with open(f, 'r') as fp: return json.load(fp) def save_json(obj, f, ensure_ascii=True, indent=None): with open(f, 'w') as fp: json.dump(obj, fp, ensure_ascii=ensure_ascii, indent=indent) def load_image(f, mode='RGB'): with Image.open(f) as image: return np.array(image.convert(mode))
[ { "point_num": 1, "id": "has_nested_function_def", "question": "Does this file contain any function defined inside another function?", "answer": false }, { "point_num": 2, "id": "no_function_exceeds_5_params", "question": "Does every function in this file take 5 or fewer parameters (...
3
labelmeutils/utils/io.py
narumiruna/labelme-utils
from unittest import TestCase from collective.solr.parser import SolrFlare from collective.solr.flare import PloneFlare class FlareTests(TestCase): def testRelevanceFormatting(self): def score(**kw): return PloneFlare(SolrFlare(**kw)).data_record_normalized_score_ self.assertEqual(score(), "n.a.") self.assertEqual(score(score=0.04567), "4.6") self.assertEqual(score(score="0.04567"), "4.6") self.assertEqual(score(score="0.1"), "10.0")
[ { "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
src/collective/solr/tests/test_flare.py
IMIO/collective.solr
""" The Hamming distance between two integers is the number of positions at which the corresponding bits are different. Now your job is to find the total Hamming distance between all pairs of the given numbers. Example: Input: 4, 14, 2 Output: 6 Explanation: In binary representation, the 4 is 0100, 14 is 1110, and 2 is 0010 (just showing the four bits relevant in this case). So the answer will be: HammingDistance(4, 14) + HammingDistance(4, 2) + HammingDistance(14, 2) = 2 + 2 + 2 = 6. Note: Elements of the given array are in the range of 0 to 10^9 Length of the array will not exceed 10^4. """ class Solution: def totalHammingDistance(self, nums: List[int]) -> int: def update_bits_count(n, track): for i in range(32): tmp = n & (1 << i) if tmp != 0: track[i] += 1 track = [0] * 32 for n in nums: update_bits_count(n, track) l = len(nums) ret = 0 for n in track: ret += (l - n) * n return ret
[ { "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
questions/total-hamming-distance/Solution.py
marcus-aurelianus/leetcode-solutions
import os import pytest from . import run from .conditions import has_http def test_unit(cmake, unittest): cwd = cmake( ["sentry_test_unit"], {"SENTRY_BACKEND": "none", "SENTRY_TRANSPORT": "none"} ) env = dict(os.environ) run(cwd, "sentry_test_unit", ["--no-summary", unittest], check=True, env=env) @pytest.mark.skipif(not has_http, reason="tests need http transport") def test_unit_transport(cmake, unittest): cwd = cmake(["sentry_test_unit"], {"SENTRY_BACKEND": "none"}) env = dict(os.environ) run(cwd, "sentry_test_unit", ["--no-summary", unittest], check=True, env=env)
[ { "point_num": 1, "id": "all_params_annotated", "question": "Does every function parameter in this file have a type annotation (excluding self/cls)?", "answer": false }, { "point_num": 2, "id": "every_function_under_20_lines", "question": "Is every function in this file shorter than ...
3
tests/test_unit.py
lmdsp/sentry-native
from typing import Any, BinaryIO from kale.util.struct_stream import StructStream class int8(StructStream): PACK = "!b" class uint8(StructStream): PACK = "!B" class int16(StructStream): PACK = "!h" class uint16(StructStream): PACK = "!H" class int32(StructStream): PACK = "!l" class uint32(StructStream): PACK = "!L" class int64(StructStream): PACK = "!q" class uint64(StructStream): PACK = "!Q" class uint128(int): @classmethod def parse(cls, f: BinaryIO) -> Any: read_bytes = f.read(16) assert len(read_bytes) == 16 n = int.from_bytes(read_bytes, "big", signed=False) assert n <= (2 ** 128) - 1 and n >= 0 return cls(n) def stream(self, f): assert self <= (2 ** 128) - 1 and self >= 0 f.write(self.to_bytes(16, "big", signed=False)) class int512(int): # Uses 65 bytes to fit in the sign bit @classmethod def parse(cls, f: BinaryIO) -> Any: read_bytes = f.read(65) assert len(read_bytes) == 65 n = int.from_bytes(read_bytes, "big", signed=True) assert n <= (2 ** 512) - 1 and n >= -(2 ** 512) return cls(n) def stream(self, f): assert self <= (2 ** 512) - 1 and self >= -(2 ** 512) f.write(self.to_bytes(65, "big", signed=True))
[ { "point_num": 1, "id": "all_params_annotated", "question": "Does every function parameter in this file have a type annotation (excluding self/cls)?", "answer": false }, { "point_num": 2, "id": "more_functions_than_classes", "question": "Does this file define more functions than clas...
3
kale/util/ints.py
inan0812/kale-blockchain
""" To understand why this file is here, please read: http://cookiecutter-django.readthedocs.io/en/latest/faq.html#why-is-there-a-django-contrib-sites-directory-in-cookiecutter-django """ from django.conf import settings from django.db import migrations def update_site_forward(apps, schema_editor): """Set site domain and name.""" Site = apps.get_model("sites", "Site") Site.objects.update_or_create( id=settings.SITE_ID, defaults={ "domain": "jinseong.co", "name": "instagram-clone", }, ) def update_site_backward(apps, schema_editor): """Revert site domain and name to default.""" Site = apps.get_model("sites", "Site") Site.objects.update_or_create( id=settings.SITE_ID, defaults={"domain": "example.com", "name": "example.com"} ) class Migration(migrations.Migration): dependencies = [("sites", "0002_alter_domain_unique")] operations = [migrations.RunPython(update_site_forward, update_site_backward)]
[ { "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
instagram_clone/contrib/sites/migrations/0003_set_site_domain_and_name.py
eugene94/IG_clone
import pytest import json class TestRbdMirrors(object): @pytest.mark.no_docker def test_rbd_mirror_is_installed(self, node, host): assert host.package("rbd-mirror").is_installed def test_rbd_mirror_service_enabled_and_running(self, node, host): service_name = "ceph-rbd-mirror@rbd-mirror.{hostname}".format( hostname=node["vars"]["inventory_hostname"] ) s = host.service(service_name) assert s.is_enabled assert s.is_running def test_rbd_mirror_is_up(self, node, host, setup): hostname = node["vars"]["inventory_hostname"] cluster = setup["cluster_name"] container_binary = setup["container_binary"] daemons = [] if node['docker']: container_exec_cmd = '{container_binary} exec ceph-rbd-mirror-{hostname}'.format( # noqa E501 hostname=hostname, container_binary=container_binary) else: container_exec_cmd = '' hostname = node["vars"]["inventory_hostname"] cluster = setup['cluster_name'] cmd = "sudo {container_exec_cmd} ceph --name client.bootstrap-rbd-mirror --keyring /var/lib/ceph/bootstrap-rbd-mirror/{cluster}.keyring --cluster={cluster} --connect-timeout 5 -f json -s".format( # noqa E501 container_exec_cmd=container_exec_cmd, hostname=hostname, cluster=cluster ) output = host.check_output(cmd) status = json.loads(output) daemon_ids = [i for i in status["servicemap"]["services"] ["rbd-mirror"]["daemons"].keys() if i != "summary"] for daemon_id in daemon_ids: daemons.append(status["servicemap"]["services"]["rbd-mirror"] ["daemons"][daemon_id]["metadata"]["hostname"]) assert hostname in daemons
[ { "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
tests/functional/tests/rbd-mirror/test_rbd_mirror.py
u-kosmonaft-u/ceph-ansible
#!/usr/local/bin/python # Code Fights Efficient Comparison Problem import time def main(): x, y, L, R = 9, 9, 1, 10000 print("Procedure 1") t1 = time.clock() procedure1(x, y, L, R) print(time.clock() - t1) print("Procedure 2") t2 = time.clock() procedure2(x, y, L, R) print(time.clock() - t2) print("Procedure 3") t3 = time.clock() procedure3(x, y, L, R) print(time.clock() - t3) def procedure1(x, y, L, R): return L < x**y <= R def procedure2(x, y, L, R): return x**y > L and x**y <= R def procedure3(x, y, L, R): return x**y in range(L + 1, R + 1) if __name__ == '__main__': main()
[ { "point_num": 1, "id": "no_function_exceeds_5_params", "question": "Does every function in this file take 5 or fewer parameters (excluding self/cls)?", "answer": true }, { "point_num": 2, "id": "every_function_has_docstring", "question": "Does every function in this file have a docs...
3
CodeFights/efficientComparison.py
HKuz/Test_Code
#! /usr/bin/env from .pkt_dispatch import PacketDispatcher from scapy.all import rdpcap class PacketFileDispatcher(PacketDispatcher): '''Definition of PacketDispatcher for files of packets. Args: pkt_src: str - network interface (wlan0, eth0, lo, ...) filtr: str - tcpdump-like filters (BPF) ''' def __init__(self, pkt_src=""): ''' ''' super(PacketFileDispatcher, self).__init__(pkt_src) self._pkt_iter = (x for x in rdpcap(self.pkts_src)) def __next__(self): ''' ''' return self._pkt_iter.__next__() def __len__(self): ''' ''' nr = 0 for pkt in rdpcap(self.pkts_src): nr += 1 return nr
[ { "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
dispatch/pkt_file_dispatch.py
grn-bogo/net_eye
import os import sys from flask_migrate import Migrate, MigrateCommand from flask_script import Manager base_dir = os.path.dirname(os.path.abspath(__file__)) def main(): command = sys.argv[1] if command == "db": from client.database import db from client.factory import create_app app = create_app() manager = Manager(app) Migrate( app, db, directory=os.path.join( os.path.abspath(os.path.dirname(__file__)), "client", "database", "migrations", ), ) manager.add_command("db", MigrateCommand) return manager.run() else: if command == "shell": return system("docker-compose build web && docker-compose run --rm web sh") if command == "up": return system("docker-compose build web && docker-compose up") if command == "initdb": return system( "docker-compose build web " "&& docker-compose run web python manage.py db upgrade" ) if command == "psql": return system("psql -h postgres -U postgres -w postgres") def system(command): print(f"+ {command}") return os.system(command) if __name__ == "__main__": sys.exit(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
manage.py
meko0019/Stellar-SMS
import math_helpers from problems.problem import Problem class Problem021(Problem): def __init__(self): super().__init__() self._cache = {} def calculate_answer(self) -> int: answer = 0 n = 10000 primes = math_helpers.primes_below(n) for i in range(2, n): sum_1 = self.sum_proper_divisors(i, primes) sum_2 = self.sum_proper_divisors(sum_1, primes) if i == sum_2 and i != sum_1: answer += i self.print_detail(f"amicable number: {i} ({sum_1}); sum = {answer}") return answer def sum_proper_divisors(self, n: int, primes: [int]) -> int: if n in self._cache: return self._cache[n] value = sum(math_helpers.divisors(n, True, primes)) self._cache[n] = value return value
[ { "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
ProjectEulerPython/problems/problem_021.py
geo-desic/project-euler
import pandas as pd import re data = pd.read_csv("BIPMetadata_current.csv") def format_date(date_column): # formatting the date data to display as yyyy-mm-dd new_dates = [] for date in date_column: month = date[0:date.find('/')] date = date[date.find('/')+1:] day = date[0:date.find('/')] year = date[date.find('/')+1:] if (len(month) == 1): month = "0" + month if (len(day) == 1): day = "0" + day if (len(year) == 2): year = "20" + year newDate = year + "-" + month + "-" + day print(newDate) new_dates.append(newDate) return new_dates def truncate(column, length): # truncates given column to given length and returns new column new_d = [] for d in column: if (len(d) > length): d = d[0:length] new_d.append(d) return new_d # source: https://stackoverflow.com/questions/9662346/python-code-to-remove-html-tags-from-a-string def cleanhtml(column): new_desc = [] for d in column: cleanr = re.compile('<.*?>|&([a-z0-9]+|#[0-9]{1,6}|#x[0-9a-f]{1,6});') cleantext = re.sub(cleanr, '', d) new_desc.append(' '.join(cleantext.split())) return new_desc def remove_spaces(column): new_sql = [] for d in column: new_sql.append(' '.join(d.split())) return new_sql new_created = format_date(data["created"]) print("UPDATAED") new_updated = format_date(data["updated"]) new_query = remove_spaces(data["sql_query"]) new_query = truncate(new_query, 5000) new_description = truncate(data["description"], 500) new_description = cleanhtml(new_description) data["created"] = new_created data["updated"] = new_updated data["sql_query"] = new_query data["description"] = new_description data.to_csv("BIPMetadata_cleaned.csv", index=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": "has_nested_function_def", "question": "Does this file contain any function defined insid...
3
server/db/Data/data_cleaner.py
katekaseth/Project_One
""" AStar search author: Ashwin Bose (@atb033) """ class AStar(): def __init__(self, env): self.agent_dict = env.agent_dict self.admissible_heuristic = env.admissible_heuristic self.is_at_goal = env.is_at_goal self.get_neighbors = env.get_neighbors def reconstruct_path(self, came_from, current): total_path = [current] while current in came_from.keys(): current = came_from[current] total_path.append(current) return total_path[::-1] def search(self, agent_name): """ low level search """ initial_state = self.agent_dict[agent_name]["start"] step_cost = 1 closed_set = set() open_set = {initial_state} came_from = {} g_score = {} g_score[initial_state] = 0 f_score = {} f_score[initial_state] = self.admissible_heuristic(initial_state, agent_name) while open_set: temp_dict = {open_item:f_score.setdefault(open_item, float("inf")) for open_item in open_set} current = min(temp_dict, key=temp_dict.get) if self.is_at_goal(current, agent_name): return self.reconstruct_path(came_from, current) open_set -= {current} closed_set |= {current} neighbor_list = self.get_neighbors(current) for neighbor in neighbor_list: if neighbor in closed_set: continue tentative_g_score = g_score.setdefault(current, float("inf")) + step_cost if neighbor not in open_set: open_set |= {neighbor} elif tentative_g_score >= g_score.setdefault(neighbor, float("inf")): continue came_from[neighbor] = current g_score[neighbor] = tentative_g_score f_score[neighbor] = g_score[neighbor] + self.admissible_heuristic(neighbor, agent_name) return False
[ { "point_num": 1, "id": "more_functions_than_classes", "question": "Does this file define more functions than classes?", "answer": true }, { "point_num": 2, "id": "all_params_annotated", "question": "Does every function parameter in this file have a type annotation (excluding self/cl...
3
centralized/cbs/a_star.py
KSHITIJBITHEL/multi_agent_path_planning
import json import socket def is_jsonable(obj): try: json.dumps(obj) return True except (TypeError, OverflowError, ValueError): return False def sanitize_meta(meta): keys_to_sanitize = [] for key, value in meta.items(): if not is_jsonable(value): keys_to_sanitize.append(key) if keys_to_sanitize: for key in keys_to_sanitize: del meta[key] meta['__errors'] = 'These keys have been sanitized: ' + ', '.join( keys_to_sanitize) return meta def get_ip(): s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) try: # doesn't even have to be reachable s.connect(('10.255.255.255', 1)) ip = s.getsockname()[0] except Exception: ip = '127.0.0.1' finally: s.close() return ip
[ { "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
logdna/utils.py
nimbinatus/python
"""Test DeltaPySimulator functionality pre-execution.""" import unittest import deltalanguage as dl from deltalanguage.test._graph_lib import (getg_const_chain, getg_optional_queues) class DeltaQueueCreationTest(unittest.TestCase): """Test that the simulator creates queues properly.""" def test_queue_types(self): """Test that queues of correct types are created (or not) depending on the type of the source and destination nodes. """ graph = getg_const_chain() dl.DeltaPySimulator(graph) self.assertEqual(len(graph.nodes[0].out_queues), 0) self.assertEqual(len(graph.nodes[1].out_queues), 1) self.assertEqual(len(graph.nodes[2].out_queues), 1) self.assertEqual(type(graph.nodes[1].out_queues['output']), dl.runtime.ConstQueue) self.assertEqual(type(graph.nodes[2].out_queues['output']), dl.runtime.DeltaQueue) def test_queue_optionality(self): """Test that queues inhere correct optionality depending on the type of the destination node. """ graph = getg_optional_queues() dl.DeltaPySimulator(graph) self.assertEqual(graph.nodes[0].out_queues['output'].optional, True) self.assertEqual(graph.nodes[1].out_queues['output'].optional, False) if __name__ == "__main__": unittest.main()
[ { "point_num": 1, "id": "has_multiple_inheritance", "question": "Does any class in this file use multiple inheritance?", "answer": false }, { "point_num": 2, "id": "more_functions_than_classes", "question": "Does this file define more functions than classes?", "answer": true },...
3
deltalanguage/test/runtime/test_runtime.py
riverlane/deltalanguage
import debile.master.utils as utils import unittest import mock class MasterUtilsTestCase(unittest.TestCase): def test_init_config(self): config = utils._init_config('tests/resources/master.yaml') self.assertEquals(config['database'], 'sqlite:////srv/debile/debile.db') self.assertIsNotNone(config['fedmsg']) self.assertIsNotNone(config['xmlrpc']) self.assertIsNotNone(config['repo']) self.assertIsNotNone(config['keyrings']) @mock.patch('debile.master.utils.create_engine') @mock.patch('debile.master.utils.Session.configure') def test_init_sqlalchemy(self, mock_configure, mock_engine): config = {'database':'sqlite:////srv/debile/debile.db'} utils._init_sqlalchemy(config) self.assertTrue(mock_engine.called) self.assertTrue(mock_configure.called) args, kwargs = mock_engine.call_args self.assertEquals(args, ('sqlite:////srv/debile/debile.db',)) self.assertFalse(kwargs['implicit_returning'])
[ { "point_num": 1, "id": "has_multiple_inheritance", "question": "Does any class in this file use multiple inheritance?", "answer": false }, { "point_num": 2, "id": "more_functions_than_classes", "question": "Does this file define more functions than classes?", "answer": true },...
3
tests/test_master_utils.py
tcc-unb-fga/debile
""" domonic.webapi.dragndrop ==================================== https://developer.mozilla.org/en-US/docs/Web/API/HTML_Drag_and_Drop_API """ from domonic.events import DragEvent class DataTransfer: def __init__(self): self.data = {} self.types = [] self.files = [] self.items = [] self.dropEffect = "" self.effectAllowed = "" def clearData(self, type): self.data[type] = "" self.types.remove(type) def getData(self, type): return self.data[type] def setData(self, type, data): self.data[type] = data self.types.append(type) def setDragImage(self, image, x, y): pass def addElement(self, element): self.items.append(element) # def addFile(self, file): # self.files.append(file) # class DataTransferItem: # def __init__(self, type, data): # self.type = type # self.data = data # def getAsString(self): # return self.data # def getAsFile(self): # return self.data # def getAsFileSystemHandle(self): # return self.data # def webkitGetAsEntry(self): # return self.data
[ { "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
domonic/webapi/dragndrop.py
byteface/domonic
from ..model import Model from . import loadDefaultParams as dp from . import timeIntegration as ti class ThalamicMassModel(Model): """ Two population thalamic model Reference: Costa, M. S., Weigenand, A., Ngo, H. V. V., Marshall, L., Born, J., Martinetz, T., & Claussen, J. C. (2016). A thalamocortical neural mass model of the EEG during NREM sleep and its response to auditory stimulation. PLoS computational biology, 12(9). """ name = "thalamus" description = "Two population thalamic mass model" init_vars = [ "V_t_init", "V_r_init", "Q_t_init", "Q_r_init", "Ca_init", "h_T_t_init", "h_T_r_init", "m_h1_init", "m_h2_init", "s_et_init", "s_gt_init", "s_er_init", "s_gr_init", "ds_et_init", "ds_gt_init", "ds_er_init", "ds_gr_init", ] state_vars = [ "V_t", "V_r", "Q_t", "Q_r", "Ca", "h_T_t", "h_T_r", "m_h1", "m_h2", "s_et", "s_gt", "s_er", "s_gr", "ds_et", "ds_gt", "ds_er", "ds_gr", ] output_vars = ["V_t", "V_r", "Q_t", "Q_r"] default_output = "Q_t" input_vars = [] default_input = None def __init__(self, params=None, seed=None): self.seed = seed # the integration function must be passed integration = ti.timeIntegration # load default parameters if none were given if params is None: params = dp.loadDefaultParams() # Initialize base class Model super().__init__(integration=integration, params=params) def randomICs(self): ics = dp.generateRandomICs() for idx, iv in enumerate(self.init_vars): self.params[iv] = ics[idx]
[ { "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
neurolib/models/thalamus/model.py
Ronjaa95/neurolib
#boggle matrix analysis main app def find_adjacent_nodes(row_index, col_index): adjacent_nodes = [] temp_num_pair = [] count = 0 while count < 9: if count == 0: temp_num_pair = [row_index-1, col_index-1] elif count == 1: temp_num_pair = [row_index-1, col_index] elif count == 2: temp_num_pair = [row_index-1, col_index+1] elif count == 3: temp_num_pair = [row_index, col_index+1] elif count == 4: temp_num_pair = [row_index+1, col_index+1] elif count == 5: temp_num_pair = [row_index+1, col_index] elif count == 6: temp_num_pair = [row_index+1, col_index-1] elif count == 1: temp_num_pair = [row_index, col_index-1] adjacent_nodes.append(temp_num_pair) count += 1 print(adjacent_nodes) def find_center_nodes(): row_index = 0 col_index = 0 while row_index < 3: while col_index < 3: if row_index != 0 and row_index != 2: if col_index != 0 and col_index != 2: print(matrix_values[row_index][col_index]) find_adjacent_nodes(row_index, col_index) col_index += 1 row_index += 1 col_index = 0 matrix_values = [ [1,2,3], [4,5,6], [7,8,9] ] print(matrix_values) print('') find_center_nodes()
[ { "point_num": 1, "id": "every_function_under_20_lines", "question": "Is every function in this file shorter than 20 lines?", "answer": false }, { "point_num": 2, "id": "every_function_has_docstring", "question": "Does every function in this file have a docstring?", "answer": fal...
3
app.py
chalvors/boggle_matrix_analysis
#!/usr/bin/env python3 # Copyright (c) 2017-2019 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test the RPC call related to the uptime command. Test corresponds to code in rpc/server.cpp. """ import time from test_framework.test_framework import FlocoinTestFramework from test_framework.util import assert_raises_rpc_error class UptimeTest(FlocoinTestFramework): def set_test_params(self): self.num_nodes = 1 self.setup_clean_chain = True def run_test(self): self._test_negative_time() self._test_uptime() def _test_negative_time(self): assert_raises_rpc_error(-8, "Mocktime can not be negative: -1.", self.nodes[0].setmocktime, -1) def _test_uptime(self): wait_time = 10 self.nodes[0].setmocktime(int(time.time() + wait_time)) assert self.nodes[0].uptime() >= wait_time if __name__ == '__main__': UptimeTest().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
test/functional/rpc_uptime.py
adymoloca/flocoin
import os from typing import ( Any, Sequence, List ) def ensure_list(value: Any) -> List: # if isinstance(value, Sequence) and not isinstance(value, str): if hasattr(value, '__iter__') and not isinstance(value, str): return list(value) else: return [value] def files_exist(files: Sequence[str]) -> bool: return len(files) != 0 and all([os.path.exists(f) for f in files]) def hash_dict(obj: dict): from hashlib import md5 obj = {k: obj[k] for k in sorted(obj)} return md5(str(obj).encode()).hexdigest() def set_property(obj, name, prop_function): """Add property :obj:`prop_function` to :obj:`obj`. :obj:`prop_function` must be a function taking only one argument, i.e., :obj:`obj`. Args: obj (object): object on which the property has to be added. name (str): the name of the property. prop_function (function): function taking only :obj:`obj` as argument. """ class_name = obj.__class__.__name__ new_class = type(class_name, (obj.__class__,), {name: property(prop_function)}) obj.__class__ = new_class
[ { "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
tsl/utils/python_utils.py
TorchSpatiotemporal/tsl
import time import numpy as np import torch def to_tensor(tensor): if isinstance(tensor, np.ndarray): tensor = torch.from_numpy(tensor) if torch.cuda.is_available(): return torch.autograd.Variable(tensor).cuda() return torch.autograd.Variable(tensor) def set_default_device_cuda(): """Sets the default device (cpu or cuda) used for all tensors.""" if torch.cuda.is_available() == False: tensor = torch.FloatTensor torch.set_default_tensor_type(tensor) return False else: # device_name == "cuda": tensor = torch.cuda.FloatTensor # pylint: disable=E1101 torch.set_default_tensor_type(tensor) return True def estimate_run_time(start_time, n_steps, step): time_elapsed = int(time.time() - start_time) time_left = (time_elapsed * ((n_steps - step) / (step + 1))) summary = {"elapsed": time_elapsed, "left": time_left} return summary
[ { "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
running_modes/utils/general.py
lilleswing/Reinvent-1
# -*- coding: utf-8 -*- """ This code is auto generated from troposphere_mate.code_generator.__init__.py scripts. """ import sys if sys.version_info.major >= 3 and sys.version_info.minor >= 5: # pragma: no cover from typing import Union, List, Any import troposphere.detective from troposphere import Template, AWSHelperFn from troposphere_mate.core.mate import preprocess_init_kwargs, Mixin from troposphere_mate.core.sentiel import REQUIRED, NOTHING class Graph(troposphere.detective.Graph, Mixin): def __init__(self, title, # type: str template=None, # type: Template validation=True, # type: bool **kwargs): processed_kwargs = preprocess_init_kwargs( title=title, template=template, validation=validation, **kwargs ) super(Graph, self).__init__(**processed_kwargs) class MemberInvitation(troposphere.detective.MemberInvitation, Mixin): def __init__(self, title, # type: str template=None, # type: Template validation=True, # type: bool GraphArn=REQUIRED, # type: Union[str, AWSHelperFn] MemberEmailAddress=REQUIRED, # type: Union[str, AWSHelperFn] MemberId=REQUIRED, # type: Union[str, AWSHelperFn] DisableEmailNotification=NOTHING, # type: bool Message=NOTHING, # type: Union[str, AWSHelperFn] **kwargs): processed_kwargs = preprocess_init_kwargs( title=title, template=template, validation=validation, GraphArn=GraphArn, MemberEmailAddress=MemberEmailAddress, MemberId=MemberId, DisableEmailNotification=DisableEmailNotification, Message=Message, **kwargs ) super(MemberInvitation, self).__init__(**processed_kwargs)
[ { "point_num": 1, "id": "every_function_has_docstring", "question": "Does every function in this file have a docstring?", "answer": false }, { "point_num": 2, "id": "every_class_has_docstring", "question": "Does every class in this file have a docstring?", "answer": false }, ...
3
troposphere_mate/detective.py
tsuttsu305/troposphere_mate-project
from brownie import SimpleStorage, accounts def test_deploy(): # Arrange account = accounts[0] # Act simple_storage = SimpleStorage.deploy({"from": account}) starting_value = simple_storage.retrieve() expected = 0 # Assert assert starting_value == expected def testupdating_storage(): # Arrange account = accounts[0] simple_storage = SimpleStorage.deploy({"from": account}) # Act store_value = 100 transaction = simple_storage.store(store_value, {"from": account}) updated_value = simple_storage.retrieve() # Assert assert updated_value == store_value
[ { "point_num": 1, "id": "every_function_under_20_lines", "question": "Is every function in this file shorter than 20 lines?", "answer": true }, { "point_num": 2, "id": "every_function_has_docstring", "question": "Does every function in this file have a docstring?", "answer": fals...
3
tests/test_simple_storage.py
jayantpatil/brownie-simple-storage
# -*- coding: utf-8 -*- """Family module for Wikivoyage.""" from __future__ import absolute_import, unicode_literals __version__ = '$Id: f762c76d91e13629122c6ee944de08a2221cd193 $' # The new wikivoyage family that is hosted at wikimedia from pywikibot import family class Family(family.SubdomainFamily, family.WikimediaFamily): """Family class for Wikivoyage.""" name = 'wikivoyage' def __init__(self): """Constructor.""" self.languages_by_size = [ 'en', 'de', 'fr', 'it', 'nl', 'pt', 'pl', 'ru', 'he', 'es', 'vi', 'sv', 'zh', 'el', 'ro', 'uk', 'fa', ] super(Family, self).__init__() # Global bot allowed languages on # https://meta.wikimedia.org/wiki/Bot_policy/Implementation#Current_implementation self.cross_allowed = ['es', 'ru', ] def shared_data_repository(self, code, transcluded=False): """Return the shared data repository for this site.""" return ('wikidata', 'wikidata')
[ { "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
pywikibot/families/wikivoyage_family.py
metakgp/pywikibot
# Copyright (C) 2010 Ion Torrent Systems, Inc. All Rights Reserved import sys def parseLog(logText): metrics = {} # Get Headings for beadfind for line in logText: if "=" in line: name = line.strip().split("=") key = name[0].strip() value = name[1].strip() metrics[key] = value return metrics def generateMetrics(beadPath): f = open(beadPath, "r") beadRaw = f.readlines() f.close() data = parseLog(beadRaw) return data if __name__ == "__main__": f = open(sys.argv[1], "r") processParams = f.readlines() f.close() data = parseLog(processParams) print(data)
[ { "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
pipeline/python/ion/reports/parseBeadfind.py
konradotto/TS
# -*- coding: utf-8 -*- import sys sys.setrecursionlimit(10**6) def input(): return sys.stdin.readline().strip() import math import collections from collections import deque, Counter, defaultdict from bisect import bisect_left, bisect from copy import deepcopy import itertools from heapq import heappush, heappop, heapify import statistics INF = 10**20 mod = 10**9 + 7 from decimal import Decimal import string # import numpy as np # alp = list(string.ascii_letters[0:26]) # map(int,input().split()) def dijkstra(start, n): # (始点, ノード数) dist = [-1] * n hq = [(0, start)] # (distance, node) dist[start] = 0 seen = [False] * n # ノードが確定済みかどうか while hq: v = heappop(hq)[1] # ノードを pop する seen[v] = True for to, cost in adj[v]: # ノード v に隣接しているノードに対して if (seen[to] == False and dist[v] + cost < dist[to]) or (seen[to] == False and dist[to] == -1): dist[to] = dist[v] + cost heappush(hq, (dist[to], to)) return dist # ノード数, エッジ数, 始点ノード, 終点ノード # n,m,x,y = map(int, input().split()) n, q = map(int, input().split()) m = n - 1 # adj[s]: ノード s に隣接する(ノード, 重み)をリストで持つ adj = [[] for _ in range(n)] for i in range(m): a, b = map(int, input().split()) a -= 1 b -= 1 adj[a].append((b, 1)) adj[b].append((a, 1)) dis_k = dijkstra(0, n) for i in range(q): c, d = map(int, input().split()) c -= 1 d -= 1 print("Town" if (dis_k[c] + dis_k[d]) % 2 == 0 else "Road")
[ { "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
src/data/40.py
NULLCT/LOMC
import time import pca9685 from utility import * class DCMotors: def __init__(self, i2c, address=0x40, freq=50): self.pca9685 = pca9685.PCA9685(i2c, address) self.pca9685.freq(freq) self.m1_speed = 0 self.m2_speed = 0 def _pin(self, pin, value=None): if value is None: return bool(self.pca9685.pwm(pin)[0]) if value: self.pca9685.pwm(pin, 4096, 0) else: self.pca9685.pwm(pin, 0, 0) def speed(self, index, value=None): #_DC_MOTORS = ((10, 12, 11), (15, 13, 14)) if index == 0: pwm, in2, in1 = (15, 13, 14) else: pwm, in2, in1 = (10, 12, 11) if value is None: value = self.pca9685.duty(pwm) if self._pin(in2) and not self._pin(in1): value = -value return value value = max(min(100, value),-100) if index == 0 : self.m1_speed = value else: self.m2_speed = value if value > 0: # Forward self._pin(in2, False) self._pin(in1, True) elif value < 0: # Backward self._pin(in1, False) self._pin(in2, True) else: # Release self._pin(in1, False) self._pin(in2, False) self.pca9685.duty(pwm, int(translate(abs(value), 0, 100, 0, 3500))) # use 3500 to limit robot speed (save battery) while pca9685 max pwm is 4095 motor = DCMotors(i2c)
[ { "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
ports/esp32/modules/motor.py
AITT-VN/micropython
import factory from django.contrib.auth.hashers import check_password from django.urls import reverse from faker import Faker from rest_framework import status from rest_framework.test import APITestCase from src.users.models import User from tests.users.factories import UserFactory fake = Faker() class TestUserListTestCase(APITestCase): """ Tests /users list operations. """ def setUp(self): self.url = reverse("user-list") self.user_data = factory.build(dict, FACTORY_CLASS=UserFactory) def test_post_request_with_no_data_fails(self): response = self.client.post(self.url, {}) self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST) def test_post_request_with_valid_data_succeeds(self): response = self.client.post(self.url, self.user_data) self.assertEqual(response.status_code, status.HTTP_201_CREATED) user = User.objects.get(pk=response.data.get("id")) self.assertEqual(user.username, self.user_data.get("username")) self.assertEqual( check_password(self.user_data.get("password"), user.password), True ) class TestUserDetailTestCase(APITestCase): """ Tests /users detail operations. """ def setUp(self): self.user = UserFactory() self.url = reverse("user-detail", kwargs={"pk": self.user.pk}) self.client.credentials(HTTP_AUTHORIZATION=f"Token {self.user.auth_token}") def test_get_request_returns_a_given_user(self): response = self.client.get(self.url) self.assertEqual(response.status_code, status.HTTP_200_OK) def test_put_request_updates_a_user(self): new_first_name = fake.first_name() payload = {"first_name": new_first_name} response = self.client.put(self.url, payload) self.assertEqual(response.status_code, status.HTTP_200_OK) user = User.objects.get(pk=self.user.id) self.assertEqual(user.first_name, new_first_name)
[ { "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
tests/users/test_views.py
SerhatTeker/django-rest-todo
def foo(): a = 5 return 10 + a def bar(): a = 1e6 return a / 5.0 def tests(): assert foo() == 15 assert bar() == 2e5 tests() if hasattr(foo, "__jit__"): print("Has jit") foo.__jit__() tests()
[ { "point_num": 1, "id": "has_nested_function_def", "question": "Does this file contain any function defined inside another function?", "answer": false }, { "point_num": 2, "id": "every_function_has_docstring", "question": "Does every function in this file have a docstring?", "ans...
3
tests/snippets/jit.py
BasixKOR/RustPython
from charms.reactive import Endpoint, when, set_flag, clear_flag import charmhelpers.core.hookenv as hookenv from charmhelpers.core.hookenv import log class GearmanRequires(Endpoint): @when('endpoint.{endpoint_name}.joined') def joined(self): # if any(unit.received['port'] for unit in self.all_joined_units): set_flag(self.expand_name('available')) @when('endpoint.{endpoint_name}.changed') def changed(self): # if any(unit.received['port'] for unit in self.all_joined_units): set_flag(self.expand_name('available')) def address(self): """Get the address to access Gearman over.""" for relation in self.relations: for unit in relation.joined_units: log("Unit: {}".format(unit.received)) address = unit.received['ingress-address'] if address is not None: return address
[ { "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
interfaces/gearman/requires.py
centauri-charmers/charm-zuul-executor
from kivy.uix.splitter import Splitter, SplitterStrip from kivy.lang import Builder from kivy.core.window import Window from kivy.properties import BooleanProperty from kivystudio.behaviors import HoverBehavior Builder.load_string(''' #: import Factory kivy.factory.Factory <StudioSplitter>: strip_cls: Factory.StudioSplitterStrip strip_size: '4dp' <StudioSplitterStrip> background_down: '' background_normal: '' background_color: .12,.12,.12,1 ''') class StudioSplitter(Splitter): pass class StudioSplitterStrip(HoverBehavior, SplitterStrip): moving = BooleanProperty(False) def on_hover(self, *args): if self.hover: Window.set_system_cursor('size_we') else: if not self.moving: Window.set_system_cursor('arrow') def on_press(self): self.moving = True def on_touch_up(self, touch): if self.moving: Window.set_system_cursor('arrow') self.moving = False return super(StudioSplitterStrip, self).on_touch_up(touch) if __name__ == "__main__": root = Builder.load_string(''' BoxLayout: Button: id: w1 size_hint_x: None width: 200 StudioSplitter: min_size: self.parent.width-200 max_size: max(self.parent.width*0.8, dp(130)) on_right: self.right=root.right; w1.width = root.width-self.width Button: text: 'Spit' ''') from kivy.base import runTouchApp runTouchApp(root)
[ { "point_num": 1, "id": "has_multiple_inheritance", "question": "Does any class in this file use multiple inheritance?", "answer": true }, { "point_num": 2, "id": "every_class_has_docstring", "question": "Does every class in this file have a docstring?", "answer": false }, { ...
3
kivystudio/widgets/splitter.py
hashfx/kivystudio
from .activation_checkpoint import checkpoint from .common import print_rank_0, sync_model_param_in_dp, is_dp_rank_0, is_tp_rank_0, is_no_pp_or_last_stage from .cuda import get_current_device, synchronize, empty_cache, set_to_cuda from .memory import report_memory_usage from .timer import MultiTimer, Timer _GLOBAL_MULTI_TIMER = MultiTimer(on=False) def get_global_multitimer(): return _GLOBAL_MULTI_TIMER def set_global_multitimer_status(mode: bool): _GLOBAL_MULTI_TIMER.set_status(mode) __all__ = ['checkpoint', 'print_rank_0', 'sync_model_param_in_dp', 'get_current_device', 'synchronize', 'empty_cache', 'set_to_cuda', 'report_memory_usage', 'Timer', 'MultiTimer', 'get_global_multitimer', 'set_global_multitimer_status', 'is_dp_rank_0', 'is_tp_rank_0', 'is_no_pp_or_last_stage' ]
[ { "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
colossalai/utils/__init__.py
rahulgupta9202/ColossalAI
import cocotb from cocotb.clock import Clock from cocotb.triggers import RisingEdge, FallingEdge, ClockCycles import random async def reset(dut): dut.RESET_N <= 0 await ClockCycles(dut.EXTERNAL_CLK, 20) dut.RESET_N <= 1 await ClockCycles(dut.EXTERNAL_CLK, 1) @cocotb.test() async def spi_video_ram_test(dut): clock = Clock(dut.EXTERNAL_CLK, 10, units="us") cocotb.fork(clock.start()) random.seed(0) await reset(dut) while (dut.writing_to_vram_mode==1): await ClockCycles(dut.EXTERNAL_CLK, 1) await ClockCycles(dut.EXTERNAL_CLK, 1) for i in range(0, 10): await RisingEdge(dut.display_active) dut.SRAM_SIO0 = 0 dut.SRAM_SIO1 = 0 dut.SRAM_SIO2 = 0 dut.SRAM_SIO3 = 1 await ClockCycles(dut.EXTERNAL_CLK, 2000)
[ { "point_num": 1, "id": "has_nested_function_def", "question": "Does this file contain any function defined inside another function?", "answer": false }, { "point_num": 2, "id": "every_function_under_20_lines", "question": "Is every function in this file shorter than 20 lines?", ...
3
test/fpga/spi_video_ram_test/spi_video_ram_test.py
mbalestrini/hack_soc
"""Figures management command to run course MAU metrics for all courses, all Sites. """ from __future__ import print_function from __future__ import absolute_import from textwrap import dedent from django.core.management.base import BaseCommand from figures.tasks import ( populate_all_mau ) class Command(BaseCommand): """Task runner to kick off Figures celery tasks """ help = dedent(__doc__).strip() def add_arguments(self, parser): parser.add_argument('--no-delay', action='store_true', default=False, help='Disable the celery "delay" directive') def handle(self, *args, **options): print('Starting Figures MAU metrics for all Sites...') if options['no_delay']: populate_all_mau() else: populate_all_mau.delay() print('Done.')
[ { "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
figures/management/commands/run_figures_mau_metrics.py
Groove-eLearning/figures
import os import resources_portal.models # noqa from flask import Flask from flask_migrate import Migrate from flask_restful import Api from resources_portal.db import db from resources_portal.views import user migrate = Migrate() def initialize_routes(api: Api): api.add_resource(user.UsersApi, "/users") api.add_resource(user.UserApi, "/users/<user_id>") def set_database_URI(app: Flask): database_URI_template = "postgresql://{DB_USER}:{DB_PASSWORD}@{DB_HOST}:{DB_PORT}/{DB_NAME}" app.config["SQLALCHEMY_DATABASE_URI"] = database_URI_template.format( DB_USER=app.config["DB_USER"], DB_PASSWORD=app.config["DB_PASSWORD"], DB_HOST=os.environ["DB_HOST"], DB_PORT=app.config["DB_PORT"], DB_NAME=app.config["DB_NAME"], ) def create_app(test_config=None): # create and configure the app app = Flask(__name__) app.config.from_envvar("RESOURCES_PORTAL_CONFIG_FILE") set_database_URI(app) api = Api(app) initialize_routes(api) # ensure the instance folder exists try: os.makedirs(app.instance_path) except OSError: pass db.init_app(app) migrate.init_app(app, db) from resources_portal.schemas import ma ma.init_app(app) return app
[ { "point_num": 1, "id": "no_function_exceeds_5_params", "question": "Does every function in this file take 5 or fewer parameters (excluding self/cls)?", "answer": true }, { "point_num": 2, "id": "all_params_annotated", "question": "Does every function parameter in this file have a ty...
3
resources_portal/__init__.py
AlexsLemonade/python-flask-demo
# -*- coding: utf-8 -*- # # 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 __future__ import unicode_literals from builtins import object from typing import Set class WeightRule(object): DOWNSTREAM = 'downstream' UPSTREAM = 'upstream' ABSOLUTE = 'absolute' _ALL_WEIGHT_RULES = set() # type: Set[str] @classmethod def is_valid(cls, weight_rule): return weight_rule in cls.all_weight_rules() @classmethod def all_weight_rules(cls): if not cls._ALL_WEIGHT_RULES: cls._ALL_WEIGHT_RULES = { getattr(cls, attr) for attr in dir(cls) if not attr.startswith("_") and not callable(getattr(cls, attr)) } return cls._ALL_WEIGHT_RULES
[ { "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
airflow/utils/weight_rule.py
shrutimantri/airflow
# Petit exercice utilisant la bibliothèque graphique tkinter from tkinter import * from random import randrange # --- définition des fonctions gestionnaires d'événements : --- def drawline(): "Tracé d'une ligne dans le canevas can1" global x1, y1, x2, y2, coul can1.create_line(x1,y1,x2,y2,width=2,fill=coul) # modification des coordonnées pour la ligne suivante : y2, y1 = y2+10, y1-10 def changecolor(): "Changement aléatoire de la couleur du tracé" global coul pal = ['purple', 'cyan', 'maroon', 'green', 'red', 'blue', 'orange', 'yellow'] c = randrange(8) # => génère un nombre aléatoire de 0 à 7 coul = pal[c] # ------ Programme principal ------- # les variables suivantes seront utilisées de manière globale : x1, y1, x2, y2 = 10, 190, 190, 10 # coordonnées de la ligne coul = 'dark green' # couleur de la ligne # Création du widget principal ("maître") : fen1 = Tk() # création des widgets "esclaves" : can1 = Canvas(fen1, bg='dark grey', height=200, width=200) can1.pack(side=LEFT) bou1 = Button(fen1, text='Quitter', command=fen1.quit) bou1.pack(side=BOTTOM) bou2 = Button(fen1, text='Tracer une ligne', command=drawline) bou2.pack() bou3 = Button(fen1, text='Autre couleur', command=changecolor) bou3.pack() fen1.mainloop() # démarrage du réceptionnaire d’événements fen1.destroy() # destruction (fermeture) de la fenêtre
[ { "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
Exemples cours 6/TK_Line.py
geocot/coursPython
import tkinter as tk from tkinter.ttk import * def f(): frame=tk.Tk() frame.geometry('1500x1500') c=tk.Canvas(frame,bg="white",height=1300,width=1200) return c,frame def circle(): c,e=f() c.create_oval(20,20,200,200,outline="red") c.pack() e.mainloop() def rect(): c,e=f() c.create_rectangle(10,10,100,60,outline="red") c.pack() e.mainloop() def oval(): c,e=f() c.create_oval(20,20,200,100,outline="red") c.pack() e.mainloop() def hline(): c,e=f() c.create_line(100,50,500,50) c.pack() e.mainloop() def vline(): c,e=f() c.create_line(100,100,100,50) c.pack() e.mainloop() def arc(): c,e=f() c.create_arc(20,150,125,30,fill="blue") c.pack() e.mainloop() def poly(): c,e=f() c.create_polygon(20,150,125,30,70,500,fill="blue") c.pack() e.mainloop() def text(): c,e=f() c.create_text(200,150,text="hello") c.pack() e.mainloop() def image(): c,e=f() im=tk.PhotoImage(file=r"C:\Users\hp\Pictures\Camera Roll\WIN_20201007_11_16_53_Pro.jpg") c.create_image(500,500,image=im) c.pack() e.mainloop()
[ { "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
guimodulecanvas.py
anmol1455/python
import unittest from logging import Logger, getLogger from numpy import ndarray, power, allclose from numpy.random import randn from freq_used.logging_utils import set_logging_basic_config from optmlstat.functions.function_base import FunctionBase from optmlstat.functions.example_functions import get_sum_of_square_function, get_sum_function logger: Logger = getLogger() class TestBasicFunctions(unittest.TestCase): num_inputs: int = 30 num_data_points: int = 100 x_array_2d: ndarray @classmethod def setUpClass(cls) -> None: set_logging_basic_config(__file__) cls.x_array_2d = randn(cls.num_data_points, cls.num_inputs) def test_sum_of_squares_function(self): y_array_1d: ndarray = TestBasicFunctions._get_y_array_1d( get_sum_of_square_function(TestBasicFunctions.num_inputs) ) true_y_array_1d: ndarray = power(TestBasicFunctions.x_array_2d, 2.0).sum(axis=1) logger.info(y_array_1d.shape) logger.info(true_y_array_1d.shape) logger.info(allclose(y_array_1d, true_y_array_1d)) self.assertTrue(allclose(y_array_1d, true_y_array_1d)) def test_sum_function(self): y_array_1d: ndarray = TestBasicFunctions._get_y_array_1d(get_sum_function(TestBasicFunctions.num_inputs)) true_y_array_1d: ndarray = power(TestBasicFunctions.x_array_2d, 1.0).sum(axis=1) logger.info(y_array_1d.shape) logger.info(true_y_array_1d.shape) logger.info(allclose(y_array_1d, true_y_array_1d)) self.assertTrue(allclose(y_array_1d, true_y_array_1d)) @classmethod def _get_y_array_1d(cls, function: FunctionBase) -> ndarray: return function.get_y_values_2d(cls.x_array_2d).ravel() if __name__ == "__main__": unittest.main()
[ { "point_num": 1, "id": "has_multiple_inheritance", "question": "Does any class in this file use multiple inheritance?", "answer": false }, { "point_num": 2, "id": "every_function_under_20_lines", "question": "Is every function in this file shorter than 20 lines?", "answer": true...
3
optmlstat/test/test_basic_functions.py
sungheeyun/optmlstat
from typing import Any from fastapi import APIRouter from fastapi import Depends from fastapi import status from sitreps_server import crud from sitreps_server import schemas from sqlalchemy.orm import Session from .deps import get_db router = APIRouter() @router.get("/") def read_code_coverage( db: Session = Depends(get_db), skip: int = 0, limit: int = 100, ) -> Any: """ Retrieve items. """ item = crud.code_coverage.get_multi(db, skip=skip, limit=limit) return item @router.post("/", status_code=status.HTTP_201_CREATED) def create_code_coverage( *, db: Session = Depends(get_db), item_in: schemas.CodeCoverageCreate, ) -> Any: """ Create new item. """ item = crud.code_coverage.create(db=db, obj_in=item_in) return item
[ { "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
sitreps_server/api/v1/code_coverage.py
digitronik/sitreps-server