source string | points list | n_points int64 | path string | repo string |
|---|---|---|---|---|
# Copyright 2020 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Chromium presubmit script for src/components/autofill.
See http://dev.chromium.org/developers/how-tos/depottools/presubmit-scripts
for more details on the presubmit API built into depot_tools.
"""
def _CheckNoBaseTimeCalls(input_api, output_api):
"""Checks that no files call base::Time::Now() or base::TimeTicks::Now()."""
pattern = input_api.re.compile(
r'(base::(Time|TimeTicks)::Now)\(\)',
input_api.re.MULTILINE)
files = []
for f in input_api.AffectedSourceFiles(input_api.FilterSourceFile):
if (f.LocalPath().startswith('components/autofill/') and
not f.LocalPath().endswith("PRESUBMIT.py")):
contents = input_api.ReadFile(f)
if pattern.search(contents):
files.append(f)
if len(files):
return [ output_api.PresubmitPromptWarning(
'Consider to not call base::Time::Now() or base::TimeTicks::Now() ' +
'directly but use AutofillClock::Now() and '+
'Autofill::TickClock::NowTicks(), respectively. These clocks can be ' +
'manipulated through TestAutofillClock and TestAutofillTickClock '+
'for testing purposes, and using AutofillClock and AutofillTickClock '+
'throughout Autofill code makes sure Autofill tests refers to the '+
'same (potentially manipulated) clock.',
files) ]
return []
def _CommonChecks(input_api, output_api):
"""Checks common to both upload and commit."""
results = []
results.extend(_CheckNoBaseTimeCalls(input_api, output_api))
return results
def CheckChangeOnUpload(input_api, output_api):
results = []
results.extend(_CommonChecks(input_api, output_api))
return results
def CheckChangeOnCommit(input_api, output_api):
results = []
results.extend(_CommonChecks(input_api, output_api))
return results
| [
{
"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 | components/autofill/PRESUBMIT.py | sarang-apps/darshan_browser |
#!/usr/bin/python
#
# Copyright 2019 Polyaxon, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# coding: utf-8
"""
Polyaxon SDKs and REST API specification.
Polyaxon SDKs and REST API specification. # noqa: E501
OpenAPI spec version: 1.0.0
Contact: contact@polyaxon.com
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from __future__ import absolute_import
import unittest
import polyaxon_sdk
from polyaxon_sdk.models.v1_list_queues_response import (
V1ListQueuesResponse,
) # noqa: E501
from polyaxon_sdk.rest import ApiException
class TestV1ListQueuesResponse(unittest.TestCase):
"""V1ListQueuesResponse unit test stubs"""
def setUp(self):
pass
def tearDown(self):
pass
def testV1ListQueuesResponse(self):
"""Test V1ListQueuesResponse"""
# FIXME: construct object with mandatory attributes with example values
# model = polyaxon_sdk.models.v1_list_queues_response.V1ListQueuesResponse() # noqa: E501
pass
if __name__ == "__main__":
unittest.main()
| [
{
"point_num": 1,
"id": "has_multiple_inheritance",
"question": "Does any class in this file use multiple inheritance?",
"answer": false
},
{
"point_num": 2,
"id": "has_nested_function_def",
"question": "Does this file contain any function defined inside another function?",
"answ... | 3 | sdks/python/http_client/v1/test/test_v1_list_queues_response.py | hackerwins/polyaxon |
# © Copyright 2021 HP Development Company, L.P.
import json
import pprint
from re import subn
from utils import SubCrawlColors
from .default_storage import DefaultStorage
class ExampleStorage(DefaultStorage):
cfg = None
logger = None
def __init__(self, config, logger):
self.cfg = config
self.logger = logger
def load_scraped_domains(self):
return []
def store_result(self, result_data):
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": "all_params_annotated",
"question": "Does every function parameter in this file have a ty... | 3 | crawler/storage/example_storage.py | hpthreatresearch/subcrawl |
import unicodedb_shim as unicodedb
from data import Position
class CStream(object):
def __init__(self, source, index=0, col=0, lno=1):
self.col = col
self.index = index
self.lno = lno
self.source = source
def advance(self):
c = self.current
self.index += 1
self.col += 1
if c == u'\n':
self.lno += 1
self.col = 0
return c
@property
def current(self):
return self.source[self.index]
def pair_ahead(self, table):
if self.index + 1 < len(self.source):
return self.source[self.index:self.index+2] in table
return False
@property
def filled(self):
return self.index < len(self.source)
@property
def position(self):
return Position(self.col, self.lno)
def is_sym(self):
if self.filled:
ch = self.current
return unicodedb.isalpha(ord(ch)) or ch == '_'
return False
def is_digit(self):
if self.filled:
return self.current in u'0123456789'
return False
def is_hex(self):
if self.filled:
return self.current in u'0123456789abcdefABCDEF'
return False
def is_space(self):
if self.filled:
return unicodedb.isspace(ord(self.current))
return False
| [
{
"point_num": 1,
"id": "no_function_exceeds_5_params",
"question": "Does every function in this file take 5 or fewer parameters (excluding self/cls)?",
"answer": true
},
{
"point_num": 2,
"id": "more_functions_than_classes",
"question": "Does this file define more functions than cla... | 3 | compiler/lever_parser/reader/stream.py | cheery/lever |
"""
Utility functions
"""
import numpy as np
def set_all_args(obj, argdict):
for k in argdict.keys():
if hasattr(obj, k):
setattr(obj, k, argdict[k])
else:
print("Warning: parameter name {} not found!".format(k))
def div0(a,b):
with np.errstate(divide='ignore', invalid='ignore'):
c = np.true_divide(a, b)
c = np.nan_to_num(c)
return c
| [
{
"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 | utility.py | cyber-meow/Robotic_state_repr_learning |
try:
xrange
except:
xrange = range
def totalvalue(comb):
' Totalise a particular combination of items'
totwt = totval = 0
for item, wt, val in comb:
totwt += wt
totval += val
return (totval, -totwt) if totwt <= 400 else (0, 0)
items = (
("map", 9, 150), ("compass", 13, 35), ("water", 153, 200), ("sandwich", 50, 160),
("glucose", 15, 60), ("tin", 68, 45), ("banana", 27, 60), ("apple", 39, 40),
("cheese", 23, 30), ("beer", 52, 10), ("suntan cream", 11, 70), ("camera", 32, 30),
("t-shirt", 24, 15), ("trousers", 48, 10), ("umbrella", 73, 40),
("waterproof trousers", 42, 70), ("waterproof overclothes", 43, 75),
("note-case", 22, 80), ("sunglasses", 7, 20), ("towel", 18, 12),
("socks", 4, 50), ("book", 30, 10),
)
def knapsack01_dp(items, limit):
table = [[0 for w in range(limit + 1)] for j in range(len(items) + 1)]
for j in range(1, len(items) + 1):
item, wt, val = items[j-1]
for w in range(1, limit + 1):
if wt > w:
table[j][w] = table[j-1][w]
else:
table[j][w] = max(table[j-1][w],
table[j-1][w-wt] + val)
result = []
w = limit
for j in range(len(items), 0, -1):
was_added = table[j][w] != table[j-1][w]
if was_added:
item, wt, val = items[j-1]
result.append(items[j-1])
w -= wt
return result
bagged = knapsack01_dp(items, 400)
print(("Bagged the following items\n " +
'\n '.join(sorted(item for item,_,_ in bagged))))
val, wt = totalvalue(bagged)
print(("for a total value of %i and a total weight of %i" % (val, -wt)))
| [
{
"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 | lang/Python/knapsack-problem-0-1-2.py | ethansaxenian/RosettaDecode |
from pydocmd.preprocessors.rst import Preprocessor as RSTPreprocessor
from pydocmd.preprocessors.google import Preprocessor as GooglePreprocessor
class Preprocessor(object):
"""
This class implements the preprocessor for restructured text and google.
"""
def __init__(self, config=None):
self.config = config
self._google_preprocessor = GooglePreprocessor(config)
self._rst_preprocessor = RSTPreprocessor(config)
def is_google_format(self, docstring):
"""
Check if `docstring` is written in Google docstring format
https://sphinxcontrib-napoleon.readthedocs.io/en/latest/example_google.html
"""
lines = [line.strip() for line in docstring.split('\n')]
google_section_names = self._google_preprocessor.get_section_names()
for section_name in google_section_names:
if section_name in lines:
return True
return False
def preprocess_section(self, section):
"""
Preprocessors a given section into it's components.
"""
if self.is_google_format(section.content):
return self._google_preprocessor.preprocess_section(section)
return self._rst_preprocessor.preprocess_section(section)
@staticmethod
def _append_section(lines, key, sections):
section = sections.get(key)
if not section:
return
if lines and lines[-1]:
lines.append('')
# add an extra line because of markdown syntax
lines.extend(['**{}**:'.format(key), ''])
lines.extend(section)
| [
{
"point_num": 1,
"id": "all_function_names_snake_case",
"question": "Are all function names in this file written in snake_case?",
"answer": true
},
{
"point_num": 2,
"id": "no_function_exceeds_5_params",
"question": "Does every function in this file take 5 or fewer parameters (exclu... | 3 | pydocmd/preprocessors/smart.py | vemel/pydoc-markdown |
'''
You can use this as a boilerplate for your test framework.
Define your customized library methods in a master class like this.
Then have all your test classes inherit it.
BaseTestCase will inherit SeleniumBase methods from BaseCase.
'''
from seleniumbase import BaseCase
class BaseTestCase(BaseCase):
def setUp(self):
super(BaseTestCase, self).setUp()
# Add custom setUp code for your tests AFTER the super().setUp()
def tearDown(self):
# Add custom tearDown code for your tests BEFORE the super().tearDown()
super(BaseTestCase, self).tearDown()
def login_to_site(self):
# <<< Placeholder for actual code. Add your code here. >>>
# Add frequently used methods like this in your base test case class.
# This reduces the amount of duplicated code in your tests.
# If the UI changes, the fix only needs to be applied in one place.
pass
def example_method(self):
# <<< Placeholder for actual code. Add your code here. >>>
pass
'''
# Now you can do something like this in your test files:
from base_test_case import BaseTestCase
class MyTests(BaseTestCase):
def test_example(self):
self.login_to_site()
self.example_method()
'''
| [
{
"point_num": 1,
"id": "has_nested_function_def",
"question": "Does this file contain any function defined inside another function?",
"answer": false
},
{
"point_num": 2,
"id": "all_function_names_snake_case",
"question": "Are all function names in this file written in snake_case?",... | 3 | examples/boilerplates/base_test_case.py | vineeshvinnu/SeleniumBase |
# AUTO-GENERATED by tools/checkspecs.py - DO NOT EDIT
from __future__ import unicode_literals
from ..registration import MultiResolutionAffineRegistration
def test_MultiResolutionAffineRegistration_inputs():
input_map = dict(
args=dict(argstr='%s', ),
environ=dict(
nohash=True,
usedefault=True,
),
fixedImage=dict(
argstr='%s',
position=-2,
),
fixedImageMask=dict(argstr='--fixedImageMask %s', ),
fixedImageROI=dict(argstr='--fixedImageROI %s', ),
metricTolerance=dict(argstr='--metricTolerance %f', ),
movingImage=dict(
argstr='%s',
position=-1,
),
numIterations=dict(argstr='--numIterations %d', ),
numLineIterations=dict(argstr='--numLineIterations %d', ),
resampledImage=dict(
argstr='--resampledImage %s',
hash_files=False,
),
saveTransform=dict(
argstr='--saveTransform %s',
hash_files=False,
),
stepSize=dict(argstr='--stepSize %f', ),
stepTolerance=dict(argstr='--stepTolerance %f', ),
)
inputs = MultiResolutionAffineRegistration.input_spec()
for key, metadata in list(input_map.items()):
for metakey, value in list(metadata.items()):
assert getattr(inputs.traits()[key], metakey) == value
def test_MultiResolutionAffineRegistration_outputs():
output_map = dict(
resampledImage=dict(),
saveTransform=dict(),
)
outputs = MultiResolutionAffineRegistration.output_spec()
for key, metadata in list(output_map.items()):
for metakey, value in list(metadata.items()):
assert getattr(outputs.traits()[key], metakey) == value
| [
{
"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 | nipype/interfaces/slicer/legacy/tests/test_auto_MultiResolutionAffineRegistration.py | felixsc1/nipype |
# Copyright 2018, OpenCensus Authors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from opencensus.stats import execution_context
from opencensus.stats.measure_to_view_map import MeasureToViewMap
from opencensus.stats.measurement_map import MeasurementMap
class StatsRecorder(object):
"""Stats Recorder provides methods to record stats against tags
"""
def __init__(self):
if execution_context.get_measure_to_view_map() == {}:
execution_context.set_measure_to_view_map(MeasureToViewMap())
self.measure_to_view_map = execution_context.get_measure_to_view_map()
def new_measurement_map(self):
"""Creates a new MeasurementMap in order to record stats
:returns a MeasurementMap for recording multiple measurements
"""
return MeasurementMap(self.measure_to_view_map)
| [
{
"point_num": 1,
"id": "every_function_under_20_lines",
"question": "Is every function in this file shorter than 20 lines?",
"answer": true
},
{
"point_num": 2,
"id": "has_multiple_inheritance",
"question": "Does any class in this file use multiple inheritance?",
"answer": false... | 3 | opencensus/stats/stats_recorder.py | Flared/opencensus-python |
"""
Special Pythagorean triplet.
A Pythagorean triplet is a set of three natural numbers, a < b < c, for which,
a**2 + b**2 = c**2
For example, 3**2 + 4**2 = 9 + 16 = 25 = 5**2.
There exists exactly one Pythagorean triplet for which a + b + c = 1000.
Find the product abc.
"""
from datetime import datetime
from functools import wraps
def time_delta(func):
wraps(func)
def inner(*args):
t_init = datetime.now()
ret = func(*args)
t_final = datetime.now() - t_init
print(f'{t_final.seconds}s | {t_final.microseconds}us')
return ret
return inner
def gen_num():
n = 1
while True:
yield n
n += 1
@time_delta
def pythagorean_triplet(r):
for b in gen_num():
for a in range(1, b):
c = (a**2 + b**2)**(1/2)
if c % 1 == 0:
if (a+b+int(c)) == r:
return a, b, int(c)
a, b, c = pythagorean_triplet(1000)
res = a * b * c
print(res) | [
{
"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 | project_euler/ex9_special_pythagorean_triplet.py | ralphribeiro/uri-projecteuler |
"""
Module: 'json' on micropython-v1.10-pyboard
"""
# MCU: {'ver': 'v1.10', 'build': '', 'platform': 'pyboard', 'port': 'pyboard', 'machine': 'PYBv1.1 with STM32F405RG', 'release': '1.10.0', 'nodename': 'pyboard', 'name': 'micropython', 'family': 'micropython', 'sysname': 'pyboard', 'version': '1.10.0'}
# Stubber: 1.5.4
from typing import Any
def dump(*args, **kwargs) -> Any:
...
def dumps(*args, **kwargs) -> Any:
...
def load(*args, **kwargs) -> Any:
...
def loads(*args, **kwargs) -> Any:
...
| [
{
"point_num": 1,
"id": "every_function_has_docstring",
"question": "Does every function in this file have a docstring?",
"answer": false
},
{
"point_num": 2,
"id": "all_return_types_annotated",
"question": "Does every function in this file have a return type annotation?",
"answe... | 3 | stubs/micropython-v1_10-pyboard/json.py | mattytrentini/micropython-stubs |
#!/usr/bin/env python
# coding=utf8
from copy import deepcopy
class Deque:
def __init__(self):
self.data = []
def addFront(self, item):
self.data.insert(0, item)
def addTail(self, item):
self.data.append(item)
def removeFront(self):
if self.size() == 0:
return None
else:
value = deepcopy(self.data[0])
del self.data[0]
return value
def removeTail(self):
if self.size() == 0:
return None
else:
value = deepcopy(self.data[-1])
del self.data[-1]
return value
def size(self):
return len(self.data)
def check_palindrome(check_value):
deque = Deque()
# Reading data into deque
for c in check_value:
deque.addTail(c)
# Comparing each symbol on both sides, if not equal - not palindrome
while deque.size() > 1:
if deque.removeTail() != deque.removeFront():
return False
# If all check was succeeded, string is a palindrome
return True
| [
{
"point_num": 1,
"id": "every_function_under_20_lines",
"question": "Is every function in this file shorter than 20 lines?",
"answer": true
},
{
"point_num": 2,
"id": "all_params_annotated",
"question": "Does every function parameter in this file have a type annotation (excluding se... | 3 | palindrome_check.py | igelfiend/Python.Structures.Deque |
import sha3
import ethereum
def sig_to_vrs(sig):
# sig_bytes = bytes.fromhex(sig[2:])
r = int(sig[2:66], 16)
s = int(sig[66:130], 16)
v = int(sig[130:], 16)
return v,r,s
def hash_personal_message(msg):
padded = "\x19Ethereum Signed Message:\n" + str(len(msg)) + msg
return sha3.keccak_256(bytes(padded, 'utf8')).digest()
def recover_to_addr(msg, sig):
msghash = hash_personal_message(msg)
vrs = sig_to_vrs(sig)
return '0x' + sha3.keccak_256(ethereum.utils.ecrecover_to_pub(msghash, *vrs)).hexdigest()[24:]
| [
{
"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 | web3auth/utils.py | Axellatron/django-web3-auth |
import joblib
import pandas as pd
class ExtraTreesClassifier:
def __init__(self):
path_to_artifacts = "../../research/"
self.values_fill_missing = joblib.load(path_to_artifacts +
"train_mode.joblib")
self.encoders = joblib.load(path_to_artifacts + "encoders.joblib")
self.model = joblib.load(path_to_artifacts + "extra_trees.joblib")
def preprocessing(self, input_data):
# JSON to pandas DataFrame
input_data = pd.DataFrame(input_data, index=[0])
# fill missing values
input_data.fillna(self.values_fill_missing)
# convert categoricals
for column in [
"workclass",
"education",
"marital-status",
"occupation",
"relationship",
"race",
"sex",
"native-country",
]:
categorical_convert = self.encoders[column]
input_data[column] = categorical_convert.transform(
input_data[column])
return input_data
def predict(self, input_data):
return self.model.predict_proba(input_data)
def postprocessing(self, input_data):
label = "<=50K"
if input_data[1] > 0.5:
label = ">50K"
return {"probability": input_data[1], "label": label, "status": "OK"}
def compute_prediction(self, input_data):
try:
input_data = self.preprocessing(input_data)
prediction = self.predict(input_data)[0] # only one sample
prediction = self.postprocessing(prediction)
except Exception as e:
return {"status": "Error", "message": str(e)}
return prediction | [
{
"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 | backend/server/apps/ml/income_classifier/extra_trees.py | omkarudawant/ML-Service |
import pytest
from sanic import Sanic
from sanic_jwt import exceptions, Initialize
class MyCustomDict(dict):
async def to_dict(self):
raise Exception("i am not supposed to be called")
@pytest.yield_fixture
def app_with_dict_test():
the_user = MyCustomDict(user_id=1)
async def retrieve_user(request, payload, *args, **kwargs):
return the_user
async def authenticate(request, *args, **kwargs):
username = request.json.get("username", None)
password = request.json.get("password", None)
if not username or not password:
raise exceptions.AuthenticationFailed(
"Missing username or password."
)
user = the_user
return user
sanic_app = Sanic()
sanicjwt = Initialize(
sanic_app, authenticate=authenticate, retrieve_user=retrieve_user
)
yield (sanic_app, sanicjwt)
class TestEndpointsAsync(object):
@pytest.yield_fixture
def authenticated_response(self, app_with_dict_test):
app, sanicjwt = app_with_dict_test
_, response = app.test_client.post(
"/auth", json={"username": "foo", "password": "bar"}
)
assert response.status == 200
yield response
def test_me_endpoint(self, app_with_dict_test, authenticated_response):
app, sanicjwt = app_with_dict_test
access_token = authenticated_response.json.get(
sanicjwt.config.access_token_name(), None
)
_, response = app.test_client.get(
"/auth/me",
headers={"Authorization": "Bearer {}".format(access_token)},
)
assert response.status == 200
assert response.json.get("me").get("user_id") == 1
| [
{
"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 | tests/test_endpoints_dict_first.py | bastiendonjon/sanic-jwt |
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def getPoint(self):
return (self.x, self.y)
| [
{
"point_num": 1,
"id": "more_functions_than_classes",
"question": "Does this file define more functions than classes?",
"answer": true
},
{
"point_num": 2,
"id": "every_function_has_docstring",
"question": "Does every function in this file have a docstring?",
"answer": false
}... | 3 | src/trafficSimulator/point.py | Naor-Yekutiely/trafficSimulator |
from typing import Tuple
import numpy as np
from games.level import Level
class Game:
"""
A game can be played (by a human/agent/etc).
It requires a level and has some rules.
"""
def __init__(self, level: Level):
self.level = level
self.current_pos = np.array([0, 0])
def step(self, action: int) -> Tuple[bool, float]:
"""Should Step in the environment given the action.
Args:
action int
Returns:
done, reward
"""
raise NotImplementedError()
def reset(self, level: Level):
"""Resets this env given the level. The player now starts at the original spot again.
Args:
level (Level): The level to use.
"""
self.level = level
self.current_pos = np.array([0, 0]) | [
{
"point_num": 1,
"id": "all_params_annotated",
"question": "Does every function parameter in this file have a type annotation (excluding self/cls)?",
"answer": true
},
{
"point_num": 2,
"id": "no_function_exceeds_5_params",
"question": "Does every function in this file take 5 or few... | 3 | src/games/game.py | Michael-Beukman/NEATNoveltyPCG |
import pygame
import numpy as np
import logger
cp_logger = logger.get_logger(__name__)
class Joystick:
def __init__(self, control_board_api):
self._control_board_api = control_board_api
if self._control_board_api:
self._non_normalize_function = self._control_board_api.get_joystick_direction
self._click_func = self._control_board_api.get_button
else:
self._non_normalize_function = _get_keyboard_direction
self._click_func = _get_keyboard_click
def get_normalize_direction(self):
ax, ay = self._non_normalize_function()
if ax == 0 and ay == 0:
return None
vector = np.array([ax, ay])
normalized_vector = vector / np.linalg.norm(vector)
return normalized_vector.tolist()
def get_click(self):
return self._click_func()
def _get_keyboard_click():
keys = pygame.key.get_pressed()
return keys[pygame.K_c]
def _get_keyboard_direction():
keys = pygame.key.get_pressed()
ax, ay = 0, 0
if keys[pygame.K_UP]:
ay -= 1
if keys[pygame.K_DOWN]:
ay += 1
if keys[pygame.K_LEFT]:
ax += 1
if keys[pygame.K_RIGHT]:
ax -= 1
return ax, ay | [
{
"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 | Managers/joystick.py | xqgex/CrazyFlie |
# Copyright 2022 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# Call Retail API to search for a products in a catalog using only search query.
#
import re
import subprocess
from search_simple_query import search
def test_search_simple_query_pass():
output = str(subprocess.check_output("python search_simple_query.py", shell=True))
assert re.match(".*search request.*", output)
assert re.match(".*search response.*", output)
# check the response contains some products
assert re.match(".*results.*id.*", output)
def test_search_simple_query_response():
response = search()
assert len(response.results) == 10
product_title = response.results[0].product.title
assert re.match(".*Hoodie.*", product_title)
| [
{
"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 | samples/interactive-tutorials/search/search_simple_query_test.py | tetiana-karasova/python-retail |
#
# Copyright 2015 SUSE LLC
#
# 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.
"""
Philips HUE lamps module for proxy.
.. versionadded:: 2015.8.3
"""
import sys
__virtualname__ = "hue"
__proxyenabled__ = ["philips_hue"]
def _proxy():
"""
Get proxy.
"""
return __proxy__
def __virtual__():
"""
Start the Philips HUE only for proxies.
"""
if not _proxy():
return False
def _mkf(cmd_name, doc):
"""
Nested function to help move proxy functions into sys.modules
"""
def _cmd(*args, **kw):
"""
Call commands in proxy
"""
proxyfn = "philips_hue." + cmd_name
return __proxy__[proxyfn](*args, **kw)
return _cmd
import salt.proxy.philips_hue as hue
for method in dir(hue):
if method.startswith("call_"):
setattr(
sys.modules[__name__],
method[5:],
_mkf(method, getattr(hue, method).__doc__),
)
del hue
return _proxy() and __virtualname__ or False
| [
{
"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 | salt/modules/philips_hue.py | markgras/salt |
"""Log Number of Parameters after session creation"""
from typing import Tuple, List
import logging
import tensorflow as tf
from deepr.utils import mlflow
LOGGER = logging.getLogger(__name__)
class NumParamsHook(tf.train.SessionRunHook):
"""Log Number of Parameters after session creation"""
def __init__(self, use_mlflow: bool):
self.use_mlflow = use_mlflow
def after_create_session(self, session, coord):
super().after_create_session(session, coord)
num_global, num_trainable = get_num_params()
LOGGER.info(f"Number of parameters (global) = {num_global}")
LOGGER.info(f"Number of parameters (trainable) = {num_trainable}")
if self.use_mlflow:
mlflow.log_metrics({"num_params_global": num_global, "num_params_trainable": num_trainable})
def get_num_params() -> Tuple[int, int]:
"""Get number of global and trainable parameters
Returns
-------
Tuple[int, int]
num_global, num_trainable
"""
def _count(variables: List):
total = 0
for var in variables:
shape = var.get_shape()
var_params = 1
for dim in shape:
var_params *= dim.value
total += var_params
return total
num_global = _count(tf.global_variables())
num_trainable = _count(tf.trainable_variables())
return num_global, num_trainable
| [
{
"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 | deepr/hooks/num_params.py | Mbompr/deepr |
"""ADD autograde_enabled to assignment
Revision ID: 452a7485f568
Revises: 3d972cfa5be9
Create Date: 2021-04-27 20:45:32.938022
"""
import sqlalchemy as sa
from alembic import op
# revision identifiers, used by Alembic.
revision = "452a7485f568"
down_revision = "3d972cfa5be9"
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.add_column(
"assignment",
sa.Column("autograde_enabled", sa.Boolean(), nullable=True, default=True),
)
conn = op.get_bind()
with conn.begin():
conn.execute("update assignment set autograde_enabled = 1;")
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_column("assignment", "autograde_enabled")
# ### end Alembic commands ###
| [
{
"point_num": 1,
"id": "every_function_has_docstring",
"question": "Does every function in this file have a docstring?",
"answer": false
},
{
"point_num": 2,
"id": "every_function_under_20_lines",
"question": "Is every function in this file shorter than 20 lines?",
"answer": tru... | 3 | api/migrations/versions/452a7485f568_add_autograde_enabled_to_assignment.py | Racheltrq/Anubis |
"""
Test cfdi/utils/cfdi_amounts
"""
import os
import pytest
from tests.resources import scenarios
from cfdi.utils import cfdi_amounts as cfdia
@pytest.fixture(scope='session')
def dir_path():
return os.path.dirname(
os.path.realpath(__file__)
)
def test_get_directory_cfdi_amounts(dir_path):
for scenario in scenarios.CFDI_AMOUNTS:
abs_dir_path = os.path.join(
dir_path, scenario['payload']['dir_path']
)
result = cfdia.get_directory_cfdi_amounts(
abs_dir_path
)
print(result)
if scenario['error']:
assert result['status'] == 1
assert result['info'] is None
assert result['subtotal_cfdi_amount'] is None
assert result['discount_cfdi_amount'] is None
assert result['iva_cfdi_amount'] is None
assert result['total_cfdi_amount'] is None
assert isinstance(result['error'], Exception)
else:
assert result['status'] == 0
assert isinstance(result['info'], list)
assert isinstance(result['subtotal_cfdi_amount'], float)
assert isinstance(result['discount_cfdi_amount'], float)
assert isinstance(result['iva_cfdi_amount'], float)
assert isinstance(result['total_cfdi_amount'], float)
assert result['iva_cfdi_amount'] == \
scenario['iva_cfdi_amount']
assert result['total_cfdi_amount'] == \
scenario['total_cfdi_amount']
assert result['subtotal_cfdi_amount'] == \
scenario['subtotal_cfdi_amount']
| [
{
"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 | tests/test_utils_cfdi_amounts.py | joules457/cfdi-iva-snippet |
# -*- coding:utf-8 -*-
import os
import time
from collections import OrderedDict
import cv2
import numpy as np
__all__ = ['reader', 'preprocess_v']
def preprocess_v(img, w, h):
img = cv2.resize(img, (w, h), cv2.INTER_LINEAR).astype(np.float32)
img_mean = np.array([0.5, 0.5, 0.5]).reshape((3, 1, 1))
img_std = np.array([0.5, 0.5, 0.5]).reshape((3, 1, 1))
img = img.transpose((2, 0, 1)) / 255
img -= img_mean
img /= img_std
return img
def reader(images=None, paths=None):
"""
Preprocess to yield image.
Args:
images (list(numpy.ndarray)): images data, shape of each is [H, W, C]
paths (list[str]): paths to images.
Yield:
each (collections.OrderedDict): info of original image, preprocessed image.
"""
component = list()
if paths:
for im_path in paths:
each = OrderedDict()
assert os.path.isfile(im_path), "The {} isn't a valid file path.".format(im_path)
#print(im_path)
im = cv2.imread(im_path).astype('float32')
each['org_im'] = im
each['org_im_path'] = im_path
each['org_im_shape'] = im.shape
component.append(each)
if images is not None:
assert type(images) is list, "images should be a list."
for im in images:
each = OrderedDict()
each['org_im'] = im
each['org_im_path'] = 'ndarray_time={}'.format(round(time.time(), 6) * 1e6)
each['org_im_shape'] = im.shape
component.append(each)
for element in component:
img = element['org_im'].copy()
img = cv2.resize(img, (192, 192)).astype(np.float32)
img_mean = np.array([0.5, 0.5, 0.5]).reshape((3, 1, 1))
img_std = np.array([0.5, 0.5, 0.5]).reshape((3, 1, 1))
img = img.transpose((2, 0, 1)) / 255
img -= img_mean
img /= img_std
element['image'] = img
yield element
| [
{
"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": "any_function_over_40_lines",
"question": "Is any function in this file longer than 40 lines?",
"answer": true
... | 3 | modules/image/semantic_segmentation/humanseg_mobile/data_feed.py | chunzhang-hub/PaddleHub |
from django.shortcuts import render, HttpResponseRedirect, get_object_or_404
from cartapp.models import Cart
from mainapp.models import Product
from django.contrib.auth.decorators import login_required
@login_required
def view(request):
return render(request, 'cartapp/cart.html', context = {
'cart': Cart.objects.filter(user=request.user)
})
@login_required
def add(request, product_id):
product = get_object_or_404(Product, pk=product_id)
cart_items = Cart.objects.filter(user=request.user, product=product)
if cart_items:
cart = cart_items.first()
else:
cart = Cart(user=request.user, product=product)
cart.quantity += 1
cart.save()
return HttpResponseRedirect(request.META.get('HTTP_REFERER'))
@login_required
def remove(request, cart_item_id):
cart = get_object_or_404( Cart, pk=cart_item_id )
cart.delete()
return HttpResponseRedirect(request.META.get('HTTP_REFERER'))
@login_required
def edit(request, cart_item_id, quantity):
quantity = quantity
cart_item = Cart.objects.get(pk=cart_item_id)
if quantity > 0:
cart_item.quantity = quantity
cart_item.save()
else:
cart_item.delete()
return render(request, 'cartapp/include/inc_cart_edit.html') | [
{
"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 | geekshop/cartapp/views.py | A1eksAwP/GB-Internet-Store |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.constant.ParamConstants import *
class AlipayOpenMiniAmpeMiniappUnbindModel(object):
def __init__(self):
self._mini_app_id = None
self._mobile_app_id = None
self._scene_code = None
@property
def mini_app_id(self):
return self._mini_app_id
@mini_app_id.setter
def mini_app_id(self, value):
self._mini_app_id = value
@property
def mobile_app_id(self):
return self._mobile_app_id
@mobile_app_id.setter
def mobile_app_id(self, value):
self._mobile_app_id = value
@property
def scene_code(self):
return self._scene_code
@scene_code.setter
def scene_code(self, value):
self._scene_code = value
def to_alipay_dict(self):
params = dict()
if self.mini_app_id:
if hasattr(self.mini_app_id, 'to_alipay_dict'):
params['mini_app_id'] = self.mini_app_id.to_alipay_dict()
else:
params['mini_app_id'] = self.mini_app_id
if self.mobile_app_id:
if hasattr(self.mobile_app_id, 'to_alipay_dict'):
params['mobile_app_id'] = self.mobile_app_id.to_alipay_dict()
else:
params['mobile_app_id'] = self.mobile_app_id
if self.scene_code:
if hasattr(self.scene_code, 'to_alipay_dict'):
params['scene_code'] = self.scene_code.to_alipay_dict()
else:
params['scene_code'] = self.scene_code
return params
@staticmethod
def from_alipay_dict(d):
if not d:
return None
o = AlipayOpenMiniAmpeMiniappUnbindModel()
if 'mini_app_id' in d:
o.mini_app_id = d['mini_app_id']
if 'mobile_app_id' in d:
o.mobile_app_id = d['mobile_app_id']
if 'scene_code' in d:
o.scene_code = d['scene_code']
return o
| [
{
"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 | alipay/aop/api/domain/AlipayOpenMiniAmpeMiniappUnbindModel.py | antopen/alipay-sdk-python-all |
import torch
from torch.autograd import Function
from torch import nn
import torch.nn.functional as F
def op_copy(optimizer):
for param_group in optimizer.param_groups:
param_group['lr0'] = param_group['lr']
return optimizer
def lr_scheduler(optimizer, iter_num, max_iter, gamma=10, power=0.75):
decay = (1 + gamma * iter_num / max_iter) ** (-power)
for param_group in optimizer.param_groups:
param_group['lr'] = param_group['lr0'] * decay
param_group['weight_decay'] = 1e-3
param_group['momentum'] = 0.9
param_group['nesterov'] = True
return optimizer
def init_weights(m):
classname = m.__class__.__name__
if classname.find('Conv2d') != -1 or classname.find('ConvTranspose2d') != -1:
nn.init.kaiming_uniform_(m.weight)
nn.init.zeros_(m.bias)
elif classname.find('BatchNorm') != -1:
nn.init.normal_(m.weight, 1.0, 0.02)
nn.init.zeros_(m.bias)
elif classname.find('Linear') != -1:
nn.init.xavier_normal_(m.weight)
nn.init.zeros_(m.bias)
class KanNet(nn.Module):
def __init__(self, output=1, bottleneck_dim=256, type="linear"):
super(KanNet, self).__init__()
self.type = type
if type == 'wn':
self.fc = weightNorm(nn.Linear(bottleneck_dim, output), name="weight")
self.fc.apply(init_weights)
else:
self.fc = nn.Linear(bottleneck_dim, output)
self.fc.apply(init_weights)
def forward(self, x):
x = self.fc(x)
return x
def get_weight(self):
return self.fc.weight
def get_bias(self):
return self.fc.bias | [
{
"point_num": 1,
"id": "all_function_names_snake_case",
"question": "Are all function names in this file written in snake_case?",
"answer": true
},
{
"point_num": 2,
"id": "no_function_exceeds_5_params",
"question": "Does every function in this file take 5 or fewer parameters (exclu... | 3 | models/algorithms.py | VuongLong/DANCE_W |
import addict
from act.scio.aliasregex import normalize
from act.scio.vocabulary import Vocabulary
from act.scio.plugin import BasePlugin, Result
from typing import Text, List
import configparser
import os.path
def normalize_ta(name: Text) -> Text:
return normalize(
name,
capitalize=True,
uppercase_abbr=["APT", "BRONZE", "IRON", "GOLD"],
)
class Plugin(BasePlugin):
name = "threatactor"
info = "Extracting references to known threat actors from a body of text"
version = "0.2"
dependencies: List[Text] = []
async def analyze(self, nlpdata: addict.Dict) -> Result:
ini = configparser.ConfigParser()
ini.read([os.path.join(self.configdir, "threatactor_pattern.ini")])
ini['threat_actor']['alias'] = os.path.join(self.configdir, ini['threat_actor']['alias'])
vocab = Vocabulary(ini['threat_actor'])
res = addict.Dict()
res.ThreatActors = vocab.regex_search(
nlpdata.content,
normalize_result=normalize_ta,
debug=self.debug)
return Result(name=self.name, version=self.version, result=res)
| [
{
"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 | act/scio/plugins/threatactor_pattern.py | martineian/act-scio2 |
# coding: utf-8
# cf.http://d.hatena.ne.jp/white_wheels/20100327/p3
import numpy as np
import matplotlib.pylab as plt
from mpl_toolkits.mplot3d import Axes3D
def _numerical_gradient_no_batch(f, x):
h = 1e-4 # 0.0001
grad = np.zeros_like(x)
for idx in range(x.size):
tmp_val = x[idx]
x[idx] = float(tmp_val) + h
fxh1 = f(x) # f(x+h)
x[idx] = tmp_val - h
fxh2 = f(x) # f(x-h)
grad[idx] = (fxh1 - fxh2) / (2*h)
x[idx] = tmp_val # 还原值
return grad
def numerical_gradient(f, X):
if X.ndim == 1:
return _numerical_gradient_no_batch(f, X)
else:
grad = np.zeros_like(X)
for idx, x in enumerate(X): # (0, seq[0]), (1, seq[1]), (2, seq[2]), ...
grad[idx] = _numerical_gradient_no_batch(f, x)
return grad
def function_2(x):
if x.ndim == 1:
return np.sum(x**2)
else:
return np.sum(x**2, axis=1)
def tangent_line(f, x):
d = numerical_gradient(f, x)
print(d)
y = f(x) - d*x
return lambda t: d*t + y
if __name__ == '__main__':
x0 = np.arange(-2, 2.5, 0.25)
x1 = np.arange(-2, 2.5, 0.25)
X, Y = np.meshgrid(x0, x1) # 构建平面方格18*18=324
X = X.flatten() # (324,1)
Y = Y.flatten()
grad = numerical_gradient(function_2, np.array([X, Y])) # 拼成一个数组
plt.figure()
plt.quiver(X, Y, -grad[0], -grad[1], angles="xy",color="#666666") # headwidth=10,scale=40,color="#444444") 绘制二维矢量场图
plt.xlim([-2, 2])
plt.ylim([-2, 2])
plt.xlabel('x0')
plt.ylabel('x1')
plt.grid()
plt.legend()
plt.draw()
plt.show() | [
{
"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 | ch04/gradient_2d.py | Yuansurex/deep_learning |
from promise import Promise, is_thenable
import six
from graphql.error import format_error as format_graphql_error
from graphql.error import GraphQLError
from graphene.types.schema import Schema
def default_format_error(error):
if isinstance(error, GraphQLError):
return format_graphql_error(error)
return {'message': six.text_type(error)}
def format_execution_result(execution_result, format_error):
if execution_result:
response = {}
if execution_result.errors:
response['errors'] = [
format_error(e) for e in execution_result.errors
]
if not execution_result.invalid:
response['data'] = execution_result.data
return response
class Client(object):
def __init__(self, schema, format_error=None, **execute_options):
assert isinstance(schema, Schema)
self.schema = schema
self.execute_options = execute_options
self.format_error = format_error or default_format_error
def format_result(self, result):
return format_execution_result(result, self.format_error)
def execute(self, *args, **kwargs):
executed = self.schema.execute(*args,
**dict(self.execute_options, **kwargs))
if is_thenable(executed):
return Promise.resolve(executed).then(self.format_result)
return self.format_result(executed)
| [
{
"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 | graphene/test/__init__.py | sebdiem/graphene |
from django.http import JsonResponse, HttpResponseRedirect
from rest_framework.decorators import api_view
from sdk.key_generation import generate_random_key
from sdk.storage import create_storage
from sdk.url import URL, ModelValidationError
storage = create_storage()
@api_view(['GET'])
def go_to(request, key, format=None):
url = storage.get(key)
if not url:
return JsonResponse(status=404, data={
'error': 'key not found'
})
return HttpResponseRedirect(redirect_to=url.address)
@api_view(['POST'])
def shorten(request, format=None):
raw_url = request.data.get('url')
if not raw_url:
return JsonResponse(status=400, data={
'error': 'missing url parameter'
})
try:
url = URL.parse(raw_url)
except ModelValidationError as e:
return JsonResponse(status=400, data={
'error': 'invalid URL',
'details': e.message
})
key = _store_url_and_get_key(url)
return JsonResponse(status=200, data={
'key': key
})
def _store_url_and_get_key(url):
while True:
key = generate_random_key()
if storage.set(key, url):
break
return key
| [
{
"point_num": 1,
"id": "every_function_has_docstring",
"question": "Does every function in this file have a docstring?",
"answer": false
},
{
"point_num": 2,
"id": "every_function_under_20_lines",
"question": "Is every function in this file shorter than 20 lines?",
"answer": tru... | 3 | backend/backend/views.py | mkorman9/python-build-system |
import multiprocessing
from gensim.models import Word2Vec
from gensim.models.word2vec import LineSentence
import time
def train():
# Model 1 - create morpheme-embeddings
start = time.time()
print(start)
inp1 = "../wiki-he-morph-FULL.txt"
out_model1 = "./wiki.he-morph.window10.word2vec.skipgram-model"
model1 = Word2Vec(LineSentence(inp1), sg = 1, # 0=CBOW , 1= SkipGram
size=100, window=10, min_count=5, workers=multiprocessing.cpu_count())
# trim unneeded model memory = use (much) less RAM
model1.init_sims(replace=True)
print(time.time()-start)
model1.save(out_model1)
model1.wv.save_word2vec_format(out_model1+'.vec', binary=False)
# Model 2 - create word-embeddings
start = time.time()
inp2 = "../wiki.he.text"
out_model2 = "./wiki.he-regular.window5.word2vec.skipgram-model"
model2 = Word2Vec(LineSentence(inp2), sg = 1, # 0=CBOW , 1= SkipGram
size=100, window=5, min_count=5, workers=multiprocessing.cpu_count())
# trim unneeded model memory = use (much) less RAM
model2.init_sims(replace=True)
print(time.time()-start)
model2.save(out_model2)
model2.wv.save_word2vec_format(out_model2+'.vec', binary=False)
def getModel(model = "wiki.he.word2vec.model"):
model = Word2Vec.load(model)
return model
if __name__ == '__main__':
train()
| [
{
"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 | Embeddings-preparation/word2vec/word2vec.py | danovia/Hebrew-punctuator2 |
import tkinter as tk
class GUI(tk.Frame):
def __init__(self,master=None):
super().__init__(master)
self.pack()
self.create_wigets()
def create_wigets(self):
self.hi_there = tk.Button(self)
self.hi_there["width"] = 15
self.hi_there["height"] = 10
self.hi_there["text"] = "Hello World\n(Click me)"
self.hi_there["command"] = self.say_hi
self.hi_there.pack(side="left")
self.quit = tk.Button(self,text="QUIT",fg="red",command=root.destroy)
self.quit.pack(side="right")
def say_hi(self):
print("Hi there,everyone")
root = tk.Tk()
app = GUI(master=root)
root.title("This is a test")
app.mainloop()
| [
{
"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 | gui.py | unchangedusername/SimpleMultithreadedDownloader |
import typing
import netmiko
import napalm_digineo_procurve.queries.interfaces
import napalm_digineo_procurve.queries.lldp_neighbors
import napalm_digineo_procurve.queries.device_info
import napalm_digineo_procurve.queries.system_info
import napalm_digineo_procurve.queries.uptime
def get_uptime(device: netmiko.BaseConnection) -> float:
return napalm_digineo_procurve.queries.uptime.query(device)
def get_system_information(
device: netmiko.BaseConnection
) -> napalm_digineo_procurve.queries.system_info.SystemInformation:
return napalm_digineo_procurve.queries.system_info.query(device)
def get_device_manufacturer_info(
device: netmiko.BaseConnection
) -> napalm_digineo_procurve.queries.device_info.DeviceInformation:
return napalm_digineo_procurve.queries.device_info.query(device)
def get_interfaces(
device: netmiko.BaseConnection
) -> typing.Sequence[napalm_digineo_procurve.queries.interfaces.Interface]:
return napalm_digineo_procurve.queries.interfaces.query(device)
def get_lldp_neighbors(
device: netmiko.BaseConnection
) -> typing.List[typing.Mapping[str, str]]:
return napalm_digineo_procurve.queries.lldp_neighbors.query(device)
| [
{
"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": "all_function_names_snake_case",
"question": "Are all function names in this file written in snake_case?",
... | 3 | src/napalm_digineo_procurve/device.py | digineo/napalm-digineo-procurve |
# Copyright 2018 REMME
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ------------------------------------------------------------------------
import ujson
from .constants import Status
def serialize(payload):
return ujson.dumps(payload)
def deserialize(payload):
return ujson.loads(payload)
def create_res_payload(status, data, id, type):
payload = {
'type': type,
'status': status.name.lower(),
}
if id:
payload['id'] = id
if type == 'message':
payload['data'] = data
del payload['status']
if type == 'error':
payload['description'] = data
return serialize(payload)
def validate_payload(payload):
if not payload.get('type'):
return Status.MISSING_TYPE
elif not payload.get('action'):
return Status.MISSING_ACTION
elif not payload.get('entity'):
return Status.MISSING_ENTITY
elif not payload.get('id'):
return Status.MISSING_ID
elif not payload.get('parameters'):
return Status.MISSING_PARAMETERS
| [
{
"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 | remme/ws/utils.py | REMME-ONU/remme-core-temp |
#!/usr/bin/python
#
# Copyright 2018-2022 Polyaxon, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import ujson
from polyaxon.utils.formatting import Printer, dict_tabulate, dict_to_tabulate
def get_entity_details(entity: any, entity_name: str):
if entity.description:
Printer.print_heading("{} description:".format(entity_name))
Printer.print("{}\n".format(entity.description))
if entity.settings:
Printer.print_heading("{} settings:".format(entity_name))
Printer.print(
"{}\n".format(
entity.settings.to_dict()
if hasattr(entity.settings, "to_dict")
else entity.settings
)
)
if entity.readme:
Printer.print_heading("{} readme:".format(entity_name))
Printer.print_md(entity.readme)
response = dict_to_tabulate(
entity.to_dict(),
humanize_values=True,
exclude_attrs=["description", "settings", "readme"],
)
Printer.print_heading("{} info:".format(entity_name))
dict_tabulate(response)
def handle_output(response: any, output: str):
if output == "json":
Printer.pprint(response)
return
if "path=" in output:
json_path = output.strip("path=")
with open(json_path, "w", encoding="utf8", newline="") as output_file:
output_file.write(ujson.dumps(response))
| [
{
"point_num": 1,
"id": "every_function_under_20_lines",
"question": "Is every function in this file shorter than 20 lines?",
"answer": false
},
{
"point_num": 2,
"id": "all_params_annotated",
"question": "Does every function parameter in this file have a type annotation (excluding s... | 3 | cli/polyaxon/cli/utils.py | polyaxon/cli |
import run as whython
import os
def main():
welcome()
while True:
try:
text = input("whython > ")
if text.strip() == "": continue
if text.strip() == "exit": print("Goodbye!"); return
result, error = whython.run("<stdin>", text)
if error: print(error.as_string())
elif result:
for element in result.elements:
try:
if element.value is not None:
print(element)
except AttributeError:
pass
except KeyboardInterrupt:
print("\nType 'Exit' to leave shell.")
def welcome():
print("Welcome to whython v1.3")
# Get info about saves
editing_location = os.path.abspath("editable_/editable.py")
print(f"Current save location for editing func/var names is: {editing_location}\n")
if __name__ == "__main__":
main() | [
{
"point_num": 1,
"id": "every_function_has_docstring",
"question": "Does every function in this file have a docstring?",
"answer": false
},
{
"point_num": 2,
"id": "has_nested_function_def",
"question": "Does this file contain any function defined inside another function?",
"ans... | 3 | whython/shell.py | NexInfinite/whython |
from features.arduino_features import BlackrockSerialDIORowByte, SerialDIORowByte
from riglib import experiment
class par(object):
def init(self):
pass
class F(BlackrockSerialDIORowByte, par):
pass
f = F()
f.init()
| [
{
"point_num": 1,
"id": "more_functions_than_classes",
"question": "Does this file define more functions than classes?",
"answer": false
},
{
"point_num": 2,
"id": "every_class_has_docstring",
"question": "Does every class in this file have a docstring?",
"answer": false
},
{... | 3 | tests/test_blackrock_rstart.py | sgowda/brain-python-interface |
import pytest
try:
from bots.stocks.due_diligence.supplier import supplier_command
except ImportError:
pytest.skip(allow_module_level=True)
@pytest.fixture(scope="module")
def vcr_config():
return {
"filter_headers": [("User-Agent", None)],
"filter_query_parameters": [
("period1", "MOCK_PERIOD_1"),
("period2", "MOCK_PERIOD_2"),
("date", "MOCK_DATE"),
],
}
@pytest.mark.vcr
@pytest.mark.bots
def test_supplier_command(recorder):
value = supplier_command("TSLA")
value["view"] = str(type(value["view"]))
value["embed"] = str(type(value["embed"]))
value["choices"] = str(type(value["choices"]))
recorder.capture(value)
@pytest.mark.vcr
@pytest.mark.bots
def test_supplier_command_invalid():
with pytest.raises(Exception):
supplier_command()
| [
{
"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/bots/stocks/due_diligence/test_supplier.py | tehcoderer/GamestonkTerminal |
import torch.nn as nn
from ..core.primitives import AbstractPrimitive
class ConvBNReLU(AbstractPrimitive):
def __init__(self, C_in, C_out, kernel_size, stride=1, affine=False):
super().__init__(locals())
pad = 0 if stride == 1 and kernel_size == 1 else 1
self.op = nn.Sequential(
nn.Conv2d(C_in, C_out, kernel_size, stride=stride, padding=pad, bias=False),
nn.BatchNorm2d(C_out, affine=affine),
nn.ReLU(inplace=False),
)
def forward(self, x, edge_data):
return self.op(x)
def get_embedded_ops(self):
return None
class DepthwiseConv(AbstractPrimitive):
"""
Depthwise convolution
"""
def __init__(self, C_in, C_out, kernel_size, stride, padding, affine=True):
super().__init__(locals())
self.op = nn.Sequential(
nn.Conv2d(
C_in,
C_in,
kernel_size=kernel_size,
stride=stride,
padding=padding,
groups=C_in,
bias=False,
),
nn.BatchNorm2d(C_in, affine=affine),
nn.ReLU(inplace=False),
)
def forward(self, x, edge_data):
return self.op(x)
def get_embedded_ops(self):
return None
| [
{
"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_class_has_docstring",
"question": "Does every class in this file have a docstring?",
"answer": false... | 3 | naslib/search_spaces/hierarchical/primitives.py | NUDTNASLab/NASLib |
#coding:utf-8
from flask import request, Flask
import time
import os
app = Flask(__name__)
@app.route("/", methods=['POST'])
def get_frame():
start_time = time.time()
upload_file = request.files['file']
old_file_name = upload_file.filename
if upload_file:
file_path = os.path.join('./imgtest/', old_file_name) #Server端的存放位置
upload_file.save(file_path)
print ("success")
if not os.path.isfile('imgtest/ltuschool.jpg'):
print('有近來喔')
os.rename('./imgtest/ltu.jpg','./imgtest/ltuschool.jpg')
print('file saved to %s' % file_path)
duration = time.time() - start_time
print('duration:[%.0fms]' % (duration*1000))
return 'success'
else:
return 'failed'
def transmission():
app.run("192.168.43.179", port=5000) #Server端的IP以及port
if __name__ == "__main__":
transmission() | [
{
"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_return_types_annotated",
"question": "Does every function in this file have a return type annotation?",
"an... | 3 | transmissionServer.py | crate19970523/yoloKnifeCallPolice- |
import unittest
import compgraph as cg
class GraphTests(unittest.TestCase):
def tearDown(self):
cg.Graph.clear_default()
def test_use_different_graph(self):
new_graph = cg.Graph()
with new_graph.as_default():
node = cg.Node(name='nodo1')
self.assertEqual(len(new_graph.nodes), 1)
self.assertEqual(len(cg.Graph.get_default().nodes), 0)
def test_no_name_collision_for_many_nodes(self):
N = 10000
for _ in range(N):
cg.Node()
self.assertEqual(len(cg.Graph.get_default().nodes), N)
def test_name_collision(self):
def make_two_nodes_with_same_name():
node1 = cg.Node(name='node')
node2 = cg.Node(name='node')
self.assertRaises(
cg.Graph.NameCollisionError,
make_two_nodes_with_same_name)
if __name__ == "__main__":
unittest.main()
| [
{
"point_num": 1,
"id": "more_functions_than_classes",
"question": "Does this file define more functions than classes?",
"answer": true
},
{
"point_num": 2,
"id": "has_multiple_inheritance",
"question": "Does any class in this file use multiple inheritance?",
"answer": false
},... | 3 | tests/graph_test.py | mbsantiago/compgraph |
import atheris
with atheris.instrument_imports():
import sys
import warnings
import mdformat
from mdformat._util import is_md_equal
# Suppress all warnings.
warnings.simplefilter("ignore")
def test_one_input(input_bytes: bytes) -> None:
# We need a Unicode string, not bytes
fdp = atheris.FuzzedDataProvider(input_bytes)
data = fdp.ConsumeUnicode(sys.maxsize)
try:
formatted_data = mdformat.text(data)
except BaseException:
print_err(data)
raise
if not is_md_equal(data, formatted_data):
print_err(data)
raise Exception("Formatted Markdown not equal!")
def print_err(data):
codepoints = [hex(ord(x)) for x in data]
sys.stderr.write(f"Input was {type(data)}:\n{data}\nCodepoints:\n{codepoints}\n")
sys.stderr.flush()
def main():
# For possible options, see https://llvm.org/docs/LibFuzzer.html#options
fuzzer_options = sys.argv
atheris.Setup(fuzzer_options, test_one_input)
atheris.Fuzz()
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 | fuzzer/fuzz.py | jamesquilty/mdformat |
import torch
from torch_geometric.utils import k_hop_subgraph, subgraph
def test_subgraph():
edge_index = torch.tensor([
[0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6],
[1, 0, 2, 1, 3, 2, 4, 3, 5, 4, 6, 5],
])
edge_attr = torch.Tensor([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])
idx = torch.tensor([3, 4, 5], dtype=torch.long)
mask = torch.tensor([0, 0, 0, 1, 1, 1, 0], dtype=torch.bool)
indices = [3, 4, 5]
for subset in [idx, mask, indices]:
out = subgraph(subset, edge_index, edge_attr)
assert out[0].tolist() == [[3, 4, 4, 5], [4, 3, 5, 4]]
assert out[1].tolist() == [7, 8, 9, 10]
out = subgraph(subset, edge_index, edge_attr, relabel_nodes=True)
assert out[0].tolist() == [[0, 1, 1, 2], [1, 0, 2, 1]]
assert out[1].tolist() == [7, 8, 9, 10]
def test_k_hop_subgraph():
edge_index = torch.tensor([
[0, 1, 2, 3, 4, 5],
[2, 2, 4, 4, 6, 6],
])
subset, edge_index, mapping, edge_mask = k_hop_subgraph(
6, 2, edge_index, relabel_nodes=True)
assert subset.tolist() == [2, 3, 4, 5, 6]
assert edge_index.tolist() == [[0, 1, 2, 3], [2, 2, 4, 4]]
assert mapping.tolist() == [4]
assert edge_mask.tolist() == [False, False, True, True, True, True]
edge_index = torch.tensor([
[1, 2, 4, 5],
[0, 1, 5, 6],
])
subset, edge_index, mapping, edge_mask = k_hop_subgraph([0, 6], 2,
edge_index,
relabel_nodes=True)
assert subset.tolist() == [0, 1, 2, 4, 5, 6]
assert edge_index.tolist() == [[1, 2, 3, 4], [0, 1, 4, 5]]
assert mapping.tolist() == [0, 5]
assert edge_mask.tolist() == [True, True, True, True]
| [
{
"point_num": 1,
"id": "has_nested_function_def",
"question": "Does this file contain any function defined inside another function?",
"answer": false
},
{
"point_num": 2,
"id": "every_function_under_20_lines",
"question": "Is every function in this file shorter than 20 lines?",
... | 3 | test/utils/test_subgraph.py | LingxiaoShawn/pytorch_geometric |
# Copyright 2021 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""
Recomputation IPU Keras layers
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
"""
from tensorflow.python.keras.engine.base_layer import Layer
from tensorflow.python.ipu.ops import pipelining_ops
class RecomputationCheckpoint(Layer):
"""
Layer for checkpointing values in a computational pipeline stage.
When recomputation is enabled, these values will not be recomputed and they
will be stored in memory instead.
This layer can reduce memory liveness peaks when using recomputation if
there are too many activations which need to be recomputed before the
backpropagation operations can be executed.
This layer should be used with the
`RecomputationMode.RecomputeAndBackpropagateInterleaved` pipelining
recomputation mode.
Note that this layer has no effect when used with the
`RecomputationMode.RecomputeThenBackpropagate` pipelining
recomputation mode.
"""
def __init__(self, **kwargs):
super().__init__(**kwargs)
def call(self, inputs, **kwargs):
"""
Checkpoint the input tensors.
Args:
inputs: A tensor or a structure of tensors which should be checkpointed.
Returns:
A tensor or a structure of tensors which matches shape and type of
`inputs`.
"""
return pipelining_ops.recomputation_checkpoint(inputs, name=self.name)
def get_config(self):
return {}
| [
{
"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 | tensorflow/python/ipu/keras/layers/recomputation.py | chenzhengda/tensorflow |
from os import mkdir
from bottle import route, get, request, static_file, run
from settings import PORT, DIR_CACHE, DIR_GRAPH
from crypkograph import render_graph
@route('/')
@route('/index.html')
def serve_html():
return static_file('index.html', '.')
@route('/static/<filename:path>')
def serve_static(filename):
return static_file(filename, 'static')
@route('/generated/<filename:re:.*\.gv\.(png|pdf)>')
def serve_generated(filename):
ext = filename.split('.')[-1]
if ext == 'png':
return static_file(filename, DIR_GRAPH, mimetype='image/png')
elif ext == 'pdf':
return static_file(filename, DIR_GRAPH, download=filename)
# /api/render?owner_addr={owner_addr}
@get('/api/render')
def render():
owner_addr = request.query['owner_addr']
if not owner_addr:
raise Exception()
render_graph(owner_addr, subdir=DIR_GRAPH)
if __name__ == '__main__':
try:
mkdir(DIR_CACHE)
except FileExistsError:
pass
run(host='0.0.0.0', port=PORT)
| [
{
"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 | main.py | yuntan/crypkograph |
"""Module with git related utilities."""
import git
class GitRepoVersionInfo:
"""
Provides application versions information based on the tags and commits in the repo
"""
def __init__(self, path: str):
"""
Create an instance of GitRepoVersionInfo
:param path: The path to search for git information. It searches for '.git' in this folder or any parent
folder.
"""
self._is_repo = False
try:
self._repo = git.Repo(path, search_parent_directories=True)
self._is_repo = True
except git.exc.InvalidGitRepositoryError:
self._repo = None
@property
def is_git_repo(self) -> bool:
"""
Checks if the path given in constructor is a sub-path of a valid git repo.
:return: Boolean true, if repo was found.
"""
return self._is_repo
def get_git_version(self, strip_v_in_version: bool = True) -> str:
"""
Gets application version in the format [last-tag]-[last-commit-sha].
:param strip_v_in_version: If the version tag starts with 'v' (like 'v1.2.3),
this chooses if the 'v' should be stripped, so the resulting tag is '1.2.3'.
If there's a "-", "." or "_" separator after "v", it is removed as well.
:return: The version string
"""
if not self._is_repo:
raise git.exc.InvalidGitRepositoryError()
tags = sorted(self._repo.tags, key=lambda t: t.commit.committed_date)
latest_tag = None if len(tags) == 0 else tags[-1]
ver = "0.0.0" if latest_tag is None else latest_tag.name
if strip_v_in_version and ver.startswith("v"):
txt_ver = ver.lstrip("v")
txt_ver = txt_ver.lstrip("-_.")
else:
txt_ver = ver
sha = self._repo.head.commit.hexsha
if latest_tag is not None and sha == latest_tag.commit.hexsha:
return txt_ver
return f"{txt_ver}-{sha}"
| [
{
"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 | step_exec_lib/utils/git.py | giantswarm/step-exec-lib |
from conans import ConanFile, CMake, tools
import os, platform
named_type_version = os.getenv('NAMED_TYPE_VERSION', '1.0')
class NamedTypeConan(ConanFile):
name = "named-type"
license = "MIT"
url = "https://github.com/BentouDev/conan-named-type"
version = named_type_version
description = "NamedType can be used to declare a strong type with a typedef-like syntax"
no_copy_source = True
exports_sources = ["named-type-source/*"]
def package_id(self):
self.info.header_only()
def package(self):
self.copy(pattern="*.hpp", dst="include", src="named-type-source") | [
{
"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 | conanfile.py | BentouDev/conan-named-type |
# pylint: skip-file
import getpass
import shlex
from subprocess import PIPE # nosec
from django.core.management.base import BaseCommand
from django.utils.autoreload import run_with_reloader
import psutil
def restart_celery():
for proc in psutil.process_iter():
if proc.username() != getpass.getuser(): # skip processes not owned by user
continue
if proc.name() != "celery":
continue
# SIGTERM should only be sent to parent process, never to children processes
# see: https://github.com/celery/celery/issues/2700#issuecomment-259716123
if not proc.children():
continue
celery_proc = proc # found parent celery process
celery_proc.terminate()
break
cmd = "celery worker -A ideabox_backend -l INFO"
psutil.Popen(shlex.split(cmd), stdout=PIPE)
class Command(BaseCommand):
def handle(self, *args, **kwargs):
print("Starting celery worker with autoreload")
run_with_reloader(restart_celery)
| [
{
"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 | backend/common/management/commands/celery.py | www-norma-dev/idea-box-backend |
import pytest
from qc_utils import QCMetricRecord
from wgbs_pipeline.calculate_average_coverage import (
calculate_average_coverage,
calculate_genome_size,
get_samtools_stats,
make_qc_record,
)
@pytest.mark.filesystem
def test_get_samtools_stats(mocker):
mocker.patch("pysam.stats", return_value="SN\tfoo:\t3\n")
result = get_samtools_stats("bam_path", threads=3)
assert result == {"foo": 3}
def test_calculate_genome_size(mocker):
mocker.patch("builtins.open", mocker.mock_open(read_data="foo\t1\nbar\t5\n"))
result = calculate_genome_size("path")
assert result == 6
def test_calculate_average_coverage():
result = calculate_average_coverage(
genome_size=10, aligned_read_count=3, read_length=3
)
assert isinstance(result, dict)
assert result["average_coverage"] == pytest.approx(0.9)
def test_make_qc_record():
metric_1 = ("foo", {"bar": "baz"})
metric_2 = ("qux", {"quux": "corge"})
result = make_qc_record([metric_1, metric_2])
assert result.to_ordered_dict()["foo"] == {"bar": "baz"}
assert result.to_ordered_dict()["qux"] == {"quux": "corge"}
assert isinstance(result, QCMetricRecord)
| [
{
"point_num": 1,
"id": "all_function_names_snake_case",
"question": "Are all function names in this file written in snake_case?",
"answer": true
},
{
"point_num": 2,
"id": "every_function_has_docstring",
"question": "Does every function in this file have a docstring?",
"answer":... | 3 | tests/python/test_calculate_average_coverage.py | procha2/wgbs-pipeline |
import json
from typing import List
import numpy
from ..Spectrum import Spectrum
def save_as_json(spectrums: List[Spectrum], filename: str):
"""Save spectrum(s) as json file.
:py:attr:`~matchms.Spectrum.losses` of spectrum will not be saved.
Example:
.. code-block:: python
import numpy
from matchms import Spectrum
from matchms.exporting import save_as_json
# Create dummy spectrum
spectrum = Spectrum(mz=numpy.array([100, 200, 300], dtype="float"),
intensities=numpy.array([10, 10, 500], dtype="float"),
metadata={"charge": -1,
"inchi": '"InChI=1S/C6H12"',
"precursor_mz": 222.2})
# Write spectrum to test file
save_as_json(spectrum, "test.json")
Parameters
----------
spectrums:
Expected input is a list of :py:class:`~matchms.Spectrum.Spectrum` objects.
filename:
Provide filename to save spectrum(s).
"""
if not isinstance(spectrums, list):
# Assume that input was single Spectrum
spectrums = [spectrums]
# Write to json file
with open(filename, 'w', encoding="utf-8") as fout:
json.dump(spectrums, fout, cls=SpectrumJSONEncoder)
class SpectrumJSONEncoder(json.JSONEncoder):
# See https://github.com/PyCQA/pylint/issues/414 for reference
def default(self, o):
"""JSON Encoder which can encode a :py:class:`~matchms.Spectrum.Spectrum` object"""
if isinstance(o, Spectrum):
spec = o.clone()
peaks_list = numpy.vstack((spec.peaks.mz, spec.peaks.intensities)).T.tolist()
# Convert matchms.Spectrum() into dictionaries
spectrum_dict = {key: spec.metadata[key] for key in spec.metadata}
spectrum_dict["peaks_json"] = peaks_list
return spectrum_dict
return json.JSONEncoder.default(self, o)
| [
{
"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 | matchms/exporting/save_as_json.py | maximskorik/matchms |
import socket
from queue import Queue
import threading
target = ""
queue = Queue()
open_ports = []
def port_scan():
while not queue.empty():
try:
port = queue.get()
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((target, port))
open_ports.append(port)
except:
pass
def run_scanner(threads):
for port in range(1, 49152):
queue.put(port)
thread_list = []
for _ in range(threads):
thread = threading.Thread(target=port_scan)
thread_list.append(thread)
print("Please wait....", end="")
for thread in thread_list:
thread.start()
for thread in thread_list:
thread.join()
print("\r", end="") # Clear line
print("List port that have been detected:\n>", open_ports)
target = input("Input your target IP: ")
threads = int(input("Input thread you want to use: "))
run_scanner(threads)
| [
{
"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 | port_scanner/port_scanner.py | bagaswastu/misc_python |
from cas.common.models import BuildEnvironment
from typing import Mapping
import logging
class BaseCompiler:
"""
Base compiler class from which all compilers should extend.
"""
def __init__(self, env: BuildEnvironment, config: Mapping, platform: str):
self._env = env
self._config = config
self._platform = platform
self._logger = logging.getLogger(self.__class__.__module__)
def bootstrap(self) -> bool:
"""
Compiles any dependencies required for the configure stage.
"""
return True
def clean(self) -> bool:
"""
Removes all output files of the project.
"""
raise NotImplementedError()
def configure(self) -> bool:
"""
Generates the necessary files to build the project.
"""
return NotImplementedError()
def build(self) -> bool:
"""
Compiles the project.
"""
raise NotImplementedError()
| [
{
"point_num": 1,
"id": "all_params_annotated",
"question": "Does every function parameter in this file have a type annotation (excluding self/cls)?",
"answer": true
},
{
"point_num": 2,
"id": "every_function_under_20_lines",
"question": "Is every function in this file shorter than 2... | 3 | cas/common/buildsys/shared.py | ChaosInitiative/CAS |
from typing import Optional
from pytorch_lightning.core.optimizer import is_lightning_optimizer
from pytorch_lightning.plugins.training_type.ddp_spawn import DDPSpawnPlugin
from pytorch_lightning.utilities import _FAIRSCALE_AVAILABLE, rank_zero_only
if _FAIRSCALE_AVAILABLE:
from fairscale.optim import OSS
from pytorch_lightning.overrides.fairscale import LightningShardedDataParallel
class DDPSpawnShardedPlugin(DDPSpawnPlugin):
def configure_ddp(self):
self._wrap_optimizers()
self._model = LightningShardedDataParallel(
self.model, sharded_optimizer=self.lightning_module.trainer.optimizers
)
def _reinit_optimizers_with_oss(self):
optimizers = self.lightning_module.trainer.optimizers
for x, optimizer in enumerate(optimizers):
if is_lightning_optimizer(optimizer):
optimizer = optimizer._optimizer
if not isinstance(optimizer, OSS):
optim_class = type(optimizer)
zero_optimizer = OSS(params=optimizer.param_groups, optim=optim_class, **optimizer.defaults)
optimizers[x] = zero_optimizer
del optimizer
trainer = self.lightning_module.trainer
trainer.optimizers = trainer.convert_to_lightning_optimizers(optimizers)
def _wrap_optimizers(self):
trainer = self.model.trainer
if trainer.testing:
return
self._reinit_optimizers_with_oss()
def optimizer_state(self, optimizer: 'OSS') -> Optional[dict]:
if is_lightning_optimizer(optimizer):
optimizer = optimizer._optimizer
if isinstance(optimizer, OSS):
optimizer.consolidate_state_dict()
return self._optim_state_dict(optimizer)
@rank_zero_only
def _optim_state_dict(self, optimizer):
"""
Retrieves state dict only on rank 0, which contains the entire optimizer state after calling
:meth:`consolidate_state_dict`.
"""
return optimizer.state_dict()
| [
{
"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 | pytorch_lightning/plugins/training_type/sharded_spawn.py | peblair/pytorch-lightning |
import unittest
from unittest import TestCase
from src.utils.cross_validation_utils import CrossValidationMetricsResultPrinter
from unittest.mock import patch
class TestModelMetricsGenerator(TestCase):
@patch('builtins.print')
def test_should_print_metric_values(self, mock_print):
results = {'test_accuracy': [1, 2, 3], 'fit_time': [0.00212, 0.34455, 2.3234]}
printer = CrossValidationMetricsResultPrinter()
printer.print_metrics_values(results)
self.assertTrue(mock_print.called)
@patch('builtins.print')
def test_should_print_metrics_report(self, mock_print):
results = {'test_accuracy': [1, 2, 3], 'fit_time': [0.00212, 0.34455, 2.3234]}
printer = CrossValidationMetricsResultPrinter()
printer.print_metrics_report(results)
self.assertTrue(mock_print.called)
if __name__ == '__main__':
unittest.main()
| [
{
"point_num": 1,
"id": "every_function_has_docstring",
"question": "Does every function in this file have a docstring?",
"answer": false
},
{
"point_num": 2,
"id": "has_multiple_inheritance",
"question": "Does any class in this file use multiple inheritance?",
"answer": false
... | 3 | test/utils/CrossValidationUtilsTest.py | gusAGR/machine-learning-tfg |
# Copyright (C) 2017 Google Inc.
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
"""Factories for ggrc models.
These are factories for generating regular ggrc models. The factories create a
model and log a post event with the model revision. These do not however
trigger signals. For tests that rely on proper signals being triggered, we must
use the object generator in the ggrc.generator module.
"""
# pylint: disable=too-few-public-methods,missing-docstring,old-style-class
# pylint: disable=no-init
import factory
from ggrc import db
from ggrc import models
from ggrc.login import noop
from ggrc.fulltext import get_indexer
class ModelFactory(factory.Factory, object):
@classmethod
def _create(cls, target_class, *args, **kwargs):
instance = target_class(*args, **kwargs)
db.session.add(instance)
if isinstance(instance, models.CustomAttributeValue):
cls._log_event(instance.attributable)
if hasattr(instance, "log_json"):
cls._log_event(instance)
if getattr(db.session, "single_commit", True):
db.session.commit()
return instance
@classmethod
def _log_event(cls, instance):
indexer = get_indexer()
db.session.flush()
user = cls._get_user()
revision = models.Revision(
instance, user.id, 'created', instance.log_json())
event = models.Event(
modified_by=user,
action="POST",
resource_id=instance.id,
resource_type=instance.type,
context=instance.context,
revisions=[revision],
)
db.session.add(revision)
db.session.add(event)
indexer.update_record(indexer.fts_record_for(instance), commit=False)
@staticmethod
def _get_user():
user = models.Person.query.first()
if not user:
user = models.Person(
name=noop.default_user_name,
email=noop.default_user_email,
)
db.session.add(user)
db.session.flush()
return user
| [
{
"point_num": 1,
"id": "has_multiple_inheritance",
"question": "Does any class in this file use multiple inheritance?",
"answer": false
},
{
"point_num": 2,
"id": "all_function_names_snake_case",
"question": "Are all function names in this file written in snake_case?",
"answer":... | 3 | test/integration/ggrc/models/model_factory.py | Killswitchz/ggrc-core |
# Copyright The PyTorch Lightning team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import pytorch_lightning as pl
from flash.core.finetuning import FlashBaseFinetuning
class Seq2SeqFreezeEmbeddings(FlashBaseFinetuning):
"""Freezes the embedding layers during Seq2Seq training."""
def __init__(self, model_type: str, train_bn: bool = True):
super().__init__("", train_bn)
self.model_type = model_type
def freeze_before_training(self, pl_module: pl.LightningModule) -> None:
is_t5 = self.model_type in ["t5", "mt5"]
model = pl_module.model if is_t5 else pl_module.model.model
self.freeze(modules=model.shared, train_bn=self.train_bn)
for layer in (model.encoder, model.decoder):
self.freeze(layer.embed_tokens)
if not is_t5:
self.freeze(layer.embed_positions)
| [
{
"point_num": 1,
"id": "all_params_annotated",
"question": "Does every function parameter in this file have a type annotation (excluding self/cls)?",
"answer": true
},
{
"point_num": 2,
"id": "more_functions_than_classes",
"question": "Does this file define more functions than class... | 3 | flash/text/seq2seq/core/finetuning.py | Darktex/lightning-flash |
import unittest
import complejo
import math
class TestComplejo(unittest.TestCase):
def test_conjugado(self):
c = complejo.Complejo(2.0,5.0)
c.conjugado()
self.assertEqual(c.imaginario, -5.0)
c = complejo.Complejo(2.0,-2.8)
c.conjugado()
self.assertEqual(c.imaginario, 2.8)
def test_norma(self):
c = complejo.Complejo(0,1.0)
c.calcula_norma()
self.assertEqual(c.norma, 1.0)
c = complejo.Complejo(1.0,0.0)
c.calcula_norma()
self.assertEqual(c.norma, 1.0)
c = complejo.Complejo(5.0,5.0)
c.calcula_norma()
self.assertAlmostEqual(c.norma, math.sqrt(50.0))
def test_pow(self):
c = complejo.Complejo(0, 1.0)
d = c.pow(2)
self.assertAlmostEqual(d.real,-1.0)
self.assertAlmostEqual(d.imaginario,0.0)
c = complejo.Complejo(1.0, 1.0)
d = c.pow(6)
self.assertAlmostEqual(d.real,0.0)
self.assertAlmostEqual(d.imaginario,-math.sqrt(-8.0))
if __name__ == '__main__':
unittest.main()
| [
{
"point_num": 1,
"id": "more_functions_than_classes",
"question": "Does this file define more functions than classes?",
"answer": true
},
{
"point_num": 2,
"id": "every_function_has_docstring",
"question": "Does every function in this file have a docstring?",
"answer": false
}... | 3 | pruebas.py | dlara10/DanielLara_Ejercicio20 |
from pyquilted.quilted.section import Section
class Work(Section):
"""The work section in a quilted resume
The work object is a complex section. It contains blocks of jobs
and optionally a list of slugs. As a section it mixes in the
sectionable functionality.
"""
def __init__(self, blocks=None, slugs=None, icon=None):
self.label = 'Work'
self.icon = icon or 'fa-briefcase'
self.blocks = blocks or []
self.compact = False
def add_job(self, job):
self.blocks.append(vars(job))
def add_slugs(self, slugs):
self.slugs = slugs
class Job:
"""The job block in the work section"""
def __init__(self, dates=None, location=None, company=None, title=None,
slugs=None, previously=None, **kwargs):
self.dates = dates
self.location = location
self.company = company
self.title = title
self.slugs = slugs
self.history = History(previously=previously).to_dict()
class Slugs():
"""The additional list of slugs in the work section"""
def __init__(self, slugs=None):
self.blocks = slugs
class History():
def __init__(self, previously=None):
self.previously = previously
def to_dict(self):
if self.previously:
return vars(self)
return None
| [
{
"point_num": 1,
"id": "every_class_has_docstring",
"question": "Does every class in this file have a docstring?",
"answer": false
},
{
"point_num": 2,
"id": "all_params_annotated",
"question": "Does every function parameter in this file have a type annotation (excluding self/cls)?"... | 3 | pyquilted/quilted/work.py | cocoroutine/pyquilted |
sample = [(2, 5), (1, 2), (4, 4), (2, 3), (2, 1)]
def last(n):
return n[-1]
def tupleSort(items):
sorted_items = sorted(items, key=last)
return sorted_items
print(tupleSort(sample)) | [
{
"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": "every_function_has_docstring",
"question": "Does every function in this file have a docstring?",
"answe... | 3 | Python/w3resource/Challenge6.py | TakaIzuki/school-work |
import logging
class NullHandler(logging.Handler):
"""
Workaround to support Python 2.6
NullHandler was officially added to the logging package in Python 2.7
"""
def emit(self, record):
pass
class MockHandler(logging.Handler):
def __init__(self, *args, **kwargs):
self.reset()
logging.Handler.__init__(self, *args, **kwargs)
def emit(self, record):
self.messages[record.levelname.lower()].append(record.getMessage())
def reset(self):
self.messages = {
'debug': [],
'info': [],
'warning': [],
'error': [],
'critical': [],
}
| [
{
"point_num": 1,
"id": "has_multiple_inheritance",
"question": "Does any class in this file use multiple inheritance?",
"answer": false
},
{
"point_num": 2,
"id": "every_class_has_docstring",
"question": "Does every class in this file have a docstring?",
"answer": false
},
{... | 3 | tests/models.py | chop-dbhi/varify |
'''
Given a string s and an integer k, reverse the first k characters for every 2k characters counting
from the start of the string.
If there are fewer than k characters left, reverse all of them. If there are less than 2k but
greater than or equal to k characters, then reverse the first k characters and left the other as original.
Example 1:
Input: s = "abcdefg", k = 2
Output: "bacdfeg"
Example 2:
Input: s = "abcd", k = 2
Output: "bacd"
Constraints:
1 <= s.length <= 104
s consists of only lowercase English letters.
1 <= k <= 104
'''
class Solution:
def reverseStr(self, s: str, k: int) -> str:
def reverse_substring(sub):
res = list(sub)
left, right = 0, len(res)-1
while left <= right:
res[left], res[right] = res[right], res[left]
left += 1
right -= 1
return res
res = list(s)
for i in range(0, len(res), 2*k):
res[i:i+k] = reverse_substring(res[i:i+k])
return ''.join(res)
| [
{
"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 | string/541. Reverse String II.py | JunzhongLin/leetcode_practice |
from cement import App, Controller, ex
from boxmetrics.core.info.cpu import CPUInst as infoCPU
class CPU(Controller):
class Meta:
label = "cpu"
stacked_on = "info"
stacked_type = "nested"
description = "Get CPU info"
arguments = [
(
["-D", "--details"],
{"help": "enable per cpu details", "action": "store_true"},
)
]
def _default(self):
"""Default action if no sub-command is passed."""
self.app.render(infoCPU.all(self.app.pargs.details))
@ex(
help="get cpu usage",
arguments=[
(
["-D", "--details"],
{"help": "show per cpu usage", "action": "store_true"},
)
],
)
def percent(self):
self.app.render(infoCPU.percent(self.app.pargs.details))
@ex(
help="get cpu frequence",
arguments=[
(
["-D", "--details"],
{"help": "show per cpu frequence (unix only)", "action": "store_true"},
)
],
)
def frequence(self):
self.app.log.info("cpu frequence")
self.app.render(infoCPU.frequence(self.app.pargs.details))
@ex(
help="number of cpu",
arguments=[
(["-l", "--logical"], {"help": "only logical cpu", "action": "store_true"}),
(
["-p", "--physical"],
{"help": "only physical cpu", "action": "store_true"},
),
],
)
def count(self):
if self.app.pargs.logical:
self.app.render(infoCPU.count_logical())
elif self.app.pargs.physical:
self.app.render(infoCPU.count_physical())
else:
self.app.render(infoCPU.count())
@ex(help="CPU stats")
def stats(self):
self.app.render(infoCPU.stats())
| [
{
"point_num": 1,
"id": "every_class_has_docstring",
"question": "Does every class 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": true
},... | 3 | boxmetrics/controllers/info/cpu.py | Laurent-PANEK/boxmetrics-cli |
# TunaBot Ext - Help
from discord.ext import commands
import discord
from aiofiles import open as async_open
from ujson import load, loads
from data import is_admin
JSON_PATH = "data/help.json"
class Help(commands.Cog):
def __init__(self, bot):
self.bot, self.tuna = bot, bot.data
with open(JSON_PATH, 'r') as f:
self.data = load(f)
@commands.command(aliases=["rh"])
@is_admin
async def reloadhelp(self, ctx):
async with async_open(JSON_PATH, "r") as f:
self.data = loads(f.read())
await ctx.reply("Ok")
@commands.command()
async def help(self, ctx, *, cmd=None):
title, description = None, None
if cmd:
keys = []
for category in self.data:
if cmd == category:
keys.append(category)
break
for c in self.data[category]:
if c == cmd:
keys.append(category)
keys.append(c)
break
if len(keys) == 2:
title = f"{cmd}のHELP"
description = self.data[keys[0]][keys[1]]
elif len(keys) == 1:
title = f"{cmd}のHELP"
description = "\n".join(f"`{key}`" for key in self.data[category])
else:
title, description = "HELP", "見つかりませんでした。"
else:
title, description = "HELP", "\n".join(f"`{key}`" for key in self.data)
await ctx.reply(embed=discord.Embed(title=title, description=description))
def setup(bot):
bot.add_cog(Help(bot))
| [
{
"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 | cog/help.py | tasuren/TunaBot |
import os
import tempfile
import logging
from azureml.core.model import Model
import pickle
import pandas as pd
from azureml.core import Run
import os
import mlflow
def init():
global model
model_dir =os.getenv('AZUREML_MODEL_DIR')
model_file = os.listdir(model_dir)[0]
model_path = os.path.join(os.getenv('AZUREML_MODEL_DIR'), model_file)
model = mlflow.sklearn.load_model(model_path)
def run(mini_batch):
print(f"run method start: {__file__}, run({mini_batch})")
resultList = []
# Set up logging
for batch in mini_batch:
# prepare each image
data = pd.read_json(batch)
predictions = model.predict(data)
data["prediction"] =predictions
resultList.append(data)
result = pd.concat(resultList)
return result
| [
{
"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 | src/workshop/core/scoring/batch_score.py | srkasuMsft/MLOpsTemplate |
import paramiko
from getpass import getpass
import time
class SSHConn:
def __init__(self, host, username, password):
self.host = host
self.username = username
self.password = password
def open(self):
remote_conn_pre = paramiko.SSHClient()
remote_conn_pre.set_missing_host_key_policy(paramiko.AutoAddPolicy())
remote_conn_pre.connect(
self.host,
username=self.username,
password=self.password,
look_for_keys=False,
allow_agent=False,
)
remote_conn = remote_conn_pre.invoke_shell()
self.remote_conn_pre = remote_conn_pre
self.ssh_conn = remote_conn
def verify_connection(self):
self.ssh_conn.send("\n\n")
time.sleep(1)
return self.ssh_conn.recv(20000).decode()
def disable_paging(self, cmd="terminal length 0\n"):
self.ssh_conn.send(cmd)
time.sleep(1)
return self.ssh_conn.recv(2000).decode()
if __name__ == "__main__":
# Establish connection
password = getpass()
my_conn = SSHConn(host="cisco1.lasthop.io", username="pyclass", password=password)
my_conn.open()
# Verify connection
output = my_conn.verify_connection()
print(output)
# Disable paging
output = my_conn.disable_paging()
print(output)
| [
{
"point_num": 1,
"id": "no_function_exceeds_5_params",
"question": "Does every function in this file take 5 or fewer parameters (excluding self/cls)?",
"answer": true
},
{
"point_num": 2,
"id": "more_functions_than_classes",
"question": "Does this file define more functions than cla... | 3 | learning_python/classes/collateral/video_why_classes/class_test.py | fallenfuzz/pynet |
"""Tests for FOOOF core.info."""
from fooof.core.info import *
###################################################################################################
###################################################################################################
def test_get_obj_desc(tfm):
desc = get_obj_desc()
objs = dir(tfm)
# Test that everything in dict is a valid component of the fooof object
for ke, va in desc.items():
for it in va:
assert it in objs
def test_get_data_indices():
indices_fixed = get_data_indices('fixed')
assert indices_fixed
for ke, va in indices_fixed.items():
if ke == 'knee':
assert not va
else:
assert isinstance(va, int)
indices_knee = get_data_indices('knee')
assert indices_knee
for ke, va in indices_knee.items():
assert isinstance(va, int)
| [
{
"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 | fooof/tests/test_core_info.py | anchandm/fooof |
"""
Part 1 of https://adventofcode.com/2020/day/9
"""
def read_data(filename: str) -> list:
with open(filename, "r") as f:
data = f.read().split("\n")
return data
def sum_to_n(n, options):
"""
Helper function adapted from Day 1 :)
"""
try:
for num in options:
complement = n - num
if complement in options:
first = num
second = complement
break
return first, second
except UnboundLocalError:
return False
if __name__ == "__main__":
data = [int(i) for i in read_data("input.txt")]
for i, num in enumerate(data):
prev25 = data[i - 25 : i]
if prev25:
if not sum_to_n(num, prev25):
print(
f"Solution: The first number that is not the sum of any two of the 25 numbers before it is {num}."
)
| [
{
"point_num": 1,
"id": "every_function_has_docstring",
"question": "Does every function in this file have a docstring?",
"answer": false
},
{
"point_num": 2,
"id": "has_nested_function_def",
"question": "Does this file contain any function defined inside another function?",
"ans... | 3 | day_09/part1.py | pawlodkowski/advent_of_code_2020 |
import os
# import torch
import argparse
import base64
import sys
import io
import torch
import torch.nn as nn
from torchvision import transforms
from torch.utils.data import DataLoader
from torch.utils.data.sampler import SubsetRandomSampler
def fullmodel2base64(model):
buffer = io.BytesIO()
torch.save(model, buffer)
bg = buffer.getvalue()
return base64.b64encode(bg).decode()
def base642fullmodel(modbase64):
inputrpc = bytes(modbase64.encode())
inputrpc_ = base64.b64decode(inputrpc)
loadmodel = torch.load(io.BytesIO(inputrpc_))
return loadmodel
model_list = []
f = open(sys.argv[1], "r")
models = f.read().split(",")
f.close()
print(models)
for m in models:
model_list.append(base642fullmodel(m))
new_model_state = model_list[0].state_dict()
#sum the weight of the model
for m in model_list[1:]:
state_m = m.state_dict()
for key in state_m:
new_model_state[key] += state_m[key]
#average the model weight
for key in new_model_state:
new_model_state[key] /= len(model_list)
new_model = model_list[0]
new_model.load_state_dict(new_model_state)
output = fullmodel2base64(new_model)
print(output)
| [
{
"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 | script/app/agg.py | Intelligent-Systems-Lab/ISL-BCFL |
from cirq import circuits, ops, protocols
import cirq
from cirq.contrib.qasm_import import circuit_from_qasm, qasm
import re
import os
from cirq import decompose
from cirq.circuits import Circuit
from pyvoqc.formatting.format_from_qasm import format_from_qasm
from pyvoqc.formatting.rzq_to_rz import rzq_to_rz
from pyvoqc.voqc import VOQC
from pyvoqc.exceptions import InvalidVOQCFunction,InvalidVOQCGate
from pyvoqc.cirq.decompose_cirq_gates import *
class CqVOQC:
def __init__(self, func = None):
self.functions = ["optimize", "not_propagation", "cancel_single_qubit_gates", "cancel_two_qubit_gates", "hadamard_reduction", "merge_rotations"]
self.func = func if func else ["optimize"]
for i in range(len(self.func)):
if ((self.func[i] in self.functions) == False):
raise InvalidVOQCFunction(str(self.func[i]), self.functions)
def optimize_circuit(self, circuit: circuits.Circuit):
#Write qasm file from circuit
circuit = Circuit(decompose(circuit, intercepting_decomposer=decompose_library,keep=need_to_keep))
qasm_str = cirq.qasm(circuit)
f = open("temp.qasm", "w")
f.write(qasm_str)
f.close()
#Call VOQC optimizations from input list and go from rzq to rz
t = self.function_call("temp.qasm")
rzq_to_rz("temp2.qasm")
#Get Cirq Circuit from qasm file
with open("temp2.qasm", "r") as f:
c = f.read()
circ = circuit_from_qasm(c)
#Remove temporary files
os.remove("temp.qasm")
os.remove("temp2.qasm")
return circ
def function_call(self,fname_in):
a = VOQC(fname_in, False)
for i in range(len(self.func)):
call = getattr(a,self.func[i])
call()
return a.write("temp2.qasm")
| [
{
"point_num": 1,
"id": "no_function_exceeds_5_params",
"question": "Does every function in this file take 5 or fewer parameters (excluding self/cls)?",
"answer": true
},
{
"point_num": 2,
"id": "has_multiple_inheritance",
"question": "Does any class in this file use multiple inherit... | 3 | pyvoqc/cirq/voqc_optimization.py | akshajgaur/pyvoqc |
from django.db import models
from django.contrib.auth.models import User
# Token模型 - 用于浏览器扩展
class UserToken(models.Model):
user = models.OneToOneField(User,on_delete=models.CASCADE)
token = models.CharField(verbose_name="token值",max_length=250,unique=True)
def __str__(self):
return self.user
class Meta:
verbose_name = '用户Token'
verbose_name_plural = verbose_name
# AppToken模型 - 用于桌面、移动等各类 APP 应用
class AppUserToken(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
token = models.CharField(verbose_name="token值", max_length=250, unique=True)
def __str__(self):
return self.user
class Meta:
verbose_name = 'App用户Token'
verbose_name_plural = verbose_name | [
{
"point_num": 1,
"id": "more_functions_than_classes",
"question": "Does this file define more functions than classes?",
"answer": false
},
{
"point_num": 2,
"id": "every_class_has_docstring",
"question": "Does every class in this file have a docstring?",
"answer": false
},
{... | 3 | app_api/models.py | AngusChiang/MrDoc |
"""
This file defines the database models
"""
from .common import db, Field, auth
from py4web import URL
from pydal.validators import IS_NOT_EMPTY, IS_FILE, IS_EMPTY_OR
import datetime
from . import settings
def get_time():
return datetime.datetime.utcnow()
def get_download_url(picture):
return f"images/{picture}"
def get_user():
return auth.current_user.get("id") if auth.current_user else None
db.define_table(
"post",
Field("title", "string", requires=IS_NOT_EMPTY()),
Field("content", "text", requires=IS_NOT_EMPTY()),
Field("date_posted", "datetime", default=get_time, readable=False, writable=False),
Field(
"author",
"reference auth_user",
default=get_user,
readable=False,
writable=False,
),
)
db.define_table(
"profile",
Field("user", "reference auth_user", readable=False, writable=False),
Field(
"image",
"upload",
requires = IS_EMPTY_OR(IS_FILE()),
default="",
uploadfolder=settings.UPLOAD_PATH,
download_url=get_download_url, label="Profile Picture",
),
)
# We do not want these fields to appear in forms by default.
db.post.id.readable = False
db.post.id.writable = False
db.profile.id.readable = False
db.profile.id.writable = False
db.commit()
| [
{
"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 | models.py | Kkeller83/py4web_spa_blog |
import streamlit as st
import tensorflow as tf
from tensorflow.keras.models import model_from_json
from tensorflow.keras.losses import BinaryCrossentropy
import numpy as np
from tensorflow.keras.preprocessing import text
from tensorflow.keras.preprocessing.sequence import pad_sequences
from tensorflow.keras.preprocessing.text import Tokenizer
from tensorflow.keras.optimizers import Adam
from keras.models import load_model
from keras import backend as K
import pickle
class Predict_Bias:
def __init__(self):
self.new_text = None
@st.cache(allow_output_mutation=True)
def get_model(self):
saved_model = load_model("fake_n_model.h5")
return saved_model
def preprocess(self, text):
new_text = text
num_d_words = 50000
maxlen = 300
with open('tokenizer.pickle', 'rb') as handle:
tokenizer = pickle.load(handle)
new_text = tokenizer.texts_to_sequences(new_text)
self.new_text = pad_sequences(new_text, maxlen=maxlen)
#preprocessed = pad_sequences(new_text, maxlen=maxlen)
return self.new_text
def get_pred(self, text):
model = self.get_model()
pred = model.predict(self.preprocess(text))
if pred >= 0.5:
return str(f'This text is biased news with {pred[0][0]} certainty.')
else:
return str(f'This text is balanced news with {100 - pred[0][0]} certainty')
if __name__ == '__main__':
st.title("Biased News Article Predictor")
st.text("By Alan Reid | https://github.com/Alanapiereid")
st.text("Trained on Keras LSTM")
st.header("Is your news biased?")
text = st.text_input('Paste a news article into the field below to get a prediction')
text_array = [text]
trigger = st.button('Get Prediction')
model = Predict_Bias()
if trigger:
result = model.get_pred(text_array)
st.text(result)
| [
{
"point_num": 1,
"id": "all_function_names_snake_case",
"question": "Are all function names in this file written in snake_case?",
"answer": true
},
{
"point_num": 2,
"id": "has_multiple_inheritance",
"question": "Does any class in this file use multiple inheritance?",
"answer": ... | 3 | Streamlit_app.py | Alanapiereid/Streamlit_KERAS_LSTM_Fake_News |
# coding=UTF-8
#全部切成四字及以下
import jieba
def clean_and_append(result_list,word):
# word = word.replace("\n","")
if word == " " or word == "":
return result_list
result_list.append(word)
return result_list
def recursive_cut(line):
line = line.replace("\n", "")
result = []
for big_word in jieba.lcut(line,HMM=False):
subword_list = get_subword_list(big_word)
if isinstance(subword_list, list):
go_subword_list(subword_list,result)
elif isinstance(subword_list, str):
clean_and_append(result,subword_list)
else:
print("error")
return result
def isEN(uchar):
if (uchar >= u'\u0041' and uchar <= u'\u005a') or (uchar >= u'\u0061' and uchar <= u'\u007a'):
return True
else:
return False
def isZH(char):
if not ('\u4e00' <= char <= '\u9fa5'):
return False
return True
def get_subword_list(big_word):
if not isZH(big_word[0]):
return big_word
if len(big_word)>4:
jieba.del_word(big_word)
return jieba.lcut(big_word, HMM=False)
else:
return big_word
def go_subword_list(input_list,result):
for big_word in input_list:
if len(big_word)>4:
subword_list = get_subword_list(big_word)
if isinstance(subword_list,list):
go_subword_list(subword_list,result)
elif isinstance(subword_list,str):
clean_and_append(result, subword_list)
else:
print("error")
else:
clean_and_append(result, big_word)
#print(recursive_cut("一二三四五六七八九十"))
#print(recursive_cut("十九八七六五四三二一"))
| [
{
"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 | recursive_cut.py | Rokid/better_jieba |
from ..check import Check
_REQUIRED_FIELDS = set(['description'])
_OPTIONAL_FIELDS = set([
'author', 'es5id', 'es6id', 'esid', 'features', 'flags', 'includes',
'info', 'negative', 'timeout'
])
_VALID_FIELDS = _REQUIRED_FIELDS | _OPTIONAL_FIELDS
class CheckFeatures(Check):
'''Ensure tests specify only `features` from a list of valid values.'''
ID = 'FEATURES'
def __init__(self, filename):
with open(filename, 'r') as f:
self.valid_features = self._parse(f.read())
@staticmethod
def _parse(content):
features = []
for line in content.split():
if not line or line.startswith('#'):
continue
features.append(line)
return features
def run(self, name, meta, source):
if not meta or 'features' not in meta:
return
features = meta['features']
if len(features) == 0:
return 'If present, the `features` tag must have at least one member'
for feature in features:
if feature not in self.valid_features:
return 'Unrecognized feature: "%s"' % feature
| [
{
"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 | tools/lint/lib/checks/features.py | Acidburn0zzz/test262 |
from abc import abstractmethod, ABCMeta
from collections import namedtuple
from cairo import SolidPattern
from zorro.di import has_dependencies, dependency
from .bar import Bar
from tilenol.theme import Theme
@has_dependencies
class Widget(metaclass=ABCMeta):
bar = dependency(Bar, 'bar')
stretched = False
def __init__(self, right=False):
self.right = right
@abstractmethod
def draw(self, canvas, left, right):
return left, right
@has_dependencies
class Sep(Widget):
theme = dependency(Theme, 'theme')
def __zorro_di_done__(self):
bar = self.theme.bar
self.padding = bar.box_padding
self.color = bar.separator_color_pat
self.line_width = bar.separator_width
def draw(self, canvas, l, r):
if self.right:
x = r - self.padding.right - 0.5
r -= self.padding.left + self.padding.right
else:
x = l + self.padding.left + 0.5
l += self.padding.left + self.padding.right
canvas.set_source(self.color)
canvas.set_line_width(self.line_width)
canvas.move_to(x, self.padding.top)
canvas.line_to(x, self.height - self.padding.bottom)
canvas.stroke()
return l, r
| [
{
"point_num": 1,
"id": "every_function_under_20_lines",
"question": "Is every function in this file shorter than 20 lines?",
"answer": true
},
{
"point_num": 2,
"id": "all_params_annotated",
"question": "Does every function parameter in this file have a type annotation (excluding se... | 3 | tilenol/widgets/base.py | paulie-g/tilenol |
# BSD 3-Clause License; see https://github.com/scikit-hep/awkward-1.0/blob/main/LICENSE
import pytest # noqa: F401
import numpy as np # noqa: F401
import awkward as ak # noqa: F401
to_list = ak._v2.operations.convert.to_list
def test_broadcast_arrays():
a = ak._v2.Array([[1.1, 2.2, 3.3], [], [4.4, 5.5]], check_valid=True)
b = ak._v2.Array([100, 200, 300], check_valid=True)
out = ak._v2.operations.structure.broadcast_arrays(a, b)
assert to_list(out[0]) == [[1.1, 2.2, 3.3], [], [4.4, 5.5]]
assert to_list(out[1]) == [[100, 100, 100], [], [300, 300]]
numexpr = pytest.importorskip("numexpr")
def test_numexpr():
# NumExpr's interface pulls variables from the surrounding scope,
# so these F841 "unused variables" actually are used.
a = ak._v2.Array([[1.1, 2.2, 3.3], [], [4.4, 5.5]], check_valid=True) # noqa: F841
b = ak._v2.Array([100, 200, 300], check_valid=True) # noqa: F841
assert to_list(ak._v2._connect.numexpr.evaluate("a + b")) == [
[101.1, 102.2, 103.3],
[],
[304.4, 305.5],
]
a = [1, 2, 3] # noqa: F841
assert to_list(ak._v2._connect.numexpr.re_evaluate()) == [101, 202, 303]
| [
{
"point_num": 1,
"id": "every_function_has_docstring",
"question": "Does every function in this file have a docstring?",
"answer": false
},
{
"point_num": 2,
"id": "has_nested_function_def",
"question": "Does this file contain any function defined inside another function?",
"ans... | 3 | tests/v2/test_0119-numexpr-and-broadcast-arrays.py | douglasdavis/awkward-1.0 |
# coding: utf8
def cache_func(cache_instance, timeout=None):
def dec(func):
def wrapper(*args, **kwargs):
key = '%s:%s|' % (func.__module__, func.__name__) + repr((args, kwargs))
result = cache_instance.get(key)
if result:
return result
else:
value = func(*args, **kwargs)
if value:
cache_instance.set(key, value, timeout)
return value
else:
return None
return wrapper
return dec | [
{
"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 | api/cache.py | no13bus/bustime |
from Helper.helper import start_text, help_text
from config import bot
from telethon import events
class start():
@bot.on(events.NewMessage(pattern="/start"))
async def event_handler_start(event):
await bot.send_message(
event.chat_id,
start_text,
file='https://telegra.ph/file/92cf02b20ff395bd5e9e0.jpg'
)
@bot.on(events.NewMessage(pattern="/help"))
async def event_handler_help(event):
await bot.send_message(
event.chat_id,
help_text
)
@bot.on(events.NewMessage(pattern="/source"))
async def event_handler_source(event):
await bot.send_message(
event.chat_id,
'[Channel](https://t.me/Animemusicarchive6)\nThis bot was hosted on Heroku'
)
| [
{
"point_num": 1,
"id": "all_function_names_snake_case",
"question": "Are all function names in this file written in snake_case?",
"answer": true
},
{
"point_num": 2,
"id": "more_functions_than_classes",
"question": "Does this file define more functions than classes?",
"answer": ... | 3 | Plugins/starter.py | Naim120/Heroku-Manga-DL-Bot |
# Copyright (c) 2017-present, Facebook, Inc.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
from queue import Queue, Full, Empty
import msgpack
import msgpack_numpy
msgpack_numpy.patch()
def dumps(obj):
return msgpack.dumps(obj, use_bin_type=True)
def loads(buf):
return msgpack.loads(buf)
def check_done_flag(done_flag):
if done_flag is not None:
with done_flag.get_lock():
return done_flag.value
return False
def queue_get(q, done_flag=None, fail_comment=None):
if done_flag is None:
return q.get()
done = False
while not done:
try:
return q.get(True, 0.01)
except Empty:
if fail_comment is not None:
print(fail_comment)
if check_done_flag(done_flag):
done = True
# Return
return None
def queue_put(q, item, done_flag=None, fail_comment=None):
if done_flag is None:
q.put(item)
return True
done = False
while not done:
try:
q.put(item, True, 0.01)
return True
except Full:
if fail_comment is not None:
print(fail_comment)
if check_done_flag(done_flag):
done = True
return False
| [
{
"point_num": 1,
"id": "no_function_exceeds_5_params",
"question": "Does every function in this file take 5 or fewer parameters (excluding self/cls)?",
"answer": true
},
{
"point_num": 2,
"id": "every_function_under_20_lines",
"question": "Is every function in this file shorter than... | 3 | elf_python/utils.py | douglasrizzo/ELF |
from scfmsp.controlflowanalysis.StatusRegister import StatusRegister
from scfmsp.controlflowanalysis.instructions.AbstractInstructionBranching import AbstractInstructionBranching
class InstructionJz(AbstractInstructionBranching):
name = 'jz'
def get_execution_time(self):
return 2
def get_branching_condition_domain(self, ac):
return ac.sra.get(StatusRegister.ZERO)
| [
{
"point_num": 1,
"id": "every_function_has_docstring",
"question": "Does every function in this file have a docstring?",
"answer": false
},
{
"point_num": 2,
"id": "has_nested_function_def",
"question": "Does this file contain any function defined inside another function?",
"ans... | 3 | scfmsp/controlflowanalysis/instructions/InstructionJz.py | sepidehpouyan/SCF-MSP430 |
# coding: utf-8
"""
Kubernetes
No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
OpenAPI spec version: v1.8.2
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from __future__ import absolute_import
import os
import sys
import unittest
import kubernetes.client
from kubernetes.client.rest import ApiException
from kubernetes.client.models.v1_ceph_fs_volume_source import V1CephFSVolumeSource
class TestV1CephFSVolumeSource(unittest.TestCase):
""" V1CephFSVolumeSource unit test stubs """
def setUp(self):
pass
def tearDown(self):
pass
def testV1CephFSVolumeSource(self):
"""
Test V1CephFSVolumeSource
"""
# FIXME: construct object with mandatory attributes with example values
#model = kubernetes.client.models.v1_ceph_fs_volume_source.V1CephFSVolumeSource()
pass
if __name__ == '__main__':
unittest.main()
| [
{
"point_num": 1,
"id": "more_functions_than_classes",
"question": "Does this file define more functions than classes?",
"answer": true
},
{
"point_num": 2,
"id": "every_function_has_docstring",
"question": "Does every function in this file have a docstring?",
"answer": false
}... | 3 | kubernetes/test/test_v1_ceph_fs_volume_source.py | scele/kubernetes-client-python |
# Copyright 2015-2015 Amazon.com, Inc. or its affiliates. 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. A copy of the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "license" file accompanying this file. This file is distributed on an "AS IS"
# BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations under the License.
import os
import string
import random
from locust import HttpLocust, TaskSet, task
class MyTaskSet(TaskSet):
@task(1000)
def index(self):
response = self.client.get("/")
# This task will 15 times for every 1000 runs of the above task
# @task(15)
# def about(self):
# self.client.get("/blog")
# This task will run once for every 1000 runs of the above task
# @task(1)
# def about(self):
# id = id_generator()
# self.client.post("/signup", {"email": "example@example.com", "name": "Test"})
class MyLocust(HttpLocust):
host = os.getenv('TARGET_URL', "http://localhost")
task_set = MyTaskSet
min_wait = 90
max_wait = 100
| [
{
"point_num": 1,
"id": "more_functions_than_classes",
"question": "Does this file define more functions than classes?",
"answer": false
},
{
"point_num": 2,
"id": "has_multiple_inheritance",
"question": "Does any class in this file use multiple inheritance?",
"answer": false
}... | 3 | locustfile.py | leandrosiow/eb-locustio-sample |
"""Custom S3 storage backends to store files in subfolders."""
from storages.backends.s3boto3 import S3Boto3Storage
class MediaRootS3BotoStorage(S3Boto3Storage):
location = 'media'
class StaticRootS3BotoStorage(S3Boto3Storage):
location = 'static'
class SitemapRootS3BotoStorage(S3Boto3Storage):
location = 'sitemaps'
def __init__(self, *args, **kwargs):
kwargs['location'] = self.location
super(SitemapRootS3BotoStorage, self).__init__(*args, **kwargs)
| [
{
"point_num": 1,
"id": "every_class_has_docstring",
"question": "Does every class in this file have a docstring?",
"answer": false
},
{
"point_num": 2,
"id": "more_functions_than_classes",
"question": "Does this file define more functions than classes?",
"answer": false
},
{... | 3 | oscar_heroku/s3utils.py | ApptecSrl/oscar-heroku |
from . import instance
class SelfConstructor:
def __new__(cls, *args, **kwargs):
if len(args) == 1 and len(kwargs) == 0:
if isinstance(args[0], cls):
inst = args[0]
else:
inst = super().__new__(cls)
inst.initialize(args[0])
else:
inst = super().__new__(cls)
inst.initialize(*args, **kwargs)
return inst
def __init__(self, *args, **kwargs): pass
def initialize(self, *args, **kwargs): raise NotImplementedError()
| [
{
"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 | jsonable/self_constructor.py | wikimedia/operations-debs-python-jsonable |
from .drawing import DrawingAdapter
try:
from IT8951 import constants
from IT8951.display import AutoEPDDisplay
has_it8951 = True
except ImportError:
has_it8951 = False
import threading
class DrawingAdapterEPD(DrawingAdapter):
def __init__(self, vcom: float):
if has_it8951:
print('Setting up the display using VCOM=' + str(vcom))
self.display = AutoEPDDisplay(vcom=vcom, spi_hz=24000000)
self.display.epd.wait_display_ready()
self.display.clear()
else:
raise Exception("IT8951 driver not present")
self.lock = threading.RLock()
super().__init__(self.display.frame_buf)
def draw(self):
with self.lock:
self.display.epd.run()
self.display.draw_full(constants.DisplayModes.GC16)
self.display.epd.wait_display_ready()
self.display.epd.sleep()
| [
{
"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 | epaperboard/src/drawing_adapter_epd.py | arroz/epaperboard |
from django.db import models
from ..helpers import wallpapers_dir
class Listino(models.Model):
nome = models.CharField(max_length=200)
def __str__(self):
return f"Listino {self.nome}"
class Meta:
verbose_name = "Listino"
verbose_name_plural = "Listini"
| [
{
"point_num": 1,
"id": "more_functions_than_classes",
"question": "Does this file define more functions than classes?",
"answer": false
},
{
"point_num": 2,
"id": "has_multiple_inheritance",
"question": "Does any class in this file use multiple inheritance?",
"answer": false
}... | 3 | minigest/magazzino/models/listino.py | ctrlmaniac/minigest |
from ducts.spi import EventHandler
from datetime import datetime
from io import BytesIO
import logging
logger = logging.getLogger(__name__)
class Handler(EventHandler):
def __init__(self):
super().__init__()
def setup(self, handler_spec, manager):
handler_spec.set_description('echo back test')
return handler_spec
async def handle(self, event):
bio = BytesIO()
for i in range(1024):
bio.write(b'0123456789'*1024)
bio.seek(0)
for buf in iter(lambda: bio.read(2000), b''):
yield buf
| [
{
"point_num": 1,
"id": "all_function_names_snake_case",
"question": "Are all function names in this file written in snake_case?",
"answer": true
},
{
"point_num": 2,
"id": "no_function_exceeds_5_params",
"question": "Does every function in this file take 5 or fewer parameters (exclu... | 3 | handler/evt_90003_ducts_test_loop_bio.py | iflb/ducts-tutorial-202107 |
from .callbacks import Callback
from timeit import default_timer
from numbers import Number
import sys
overhead = sys.getsizeof(1.23) * 4 + sys.getsizeof(()) * 4
class Cache(Callback):
"""Use cache for computation
Examples
--------
>>> cache = Cache(1e9) # doctest: +SKIP
The cache can be used locally as a context manager around ``compute`` or
``get`` calls:
>>> with cache: # doctest: +SKIP
... result = x.compute()
You can also register a cache globally, so that it works for all
computations:
>>> cache.register() # doctest: +SKIP
>>> cache.unregister() # doctest: +SKIP
"""
def __init__(self, cache, *args, **kwargs):
try:
import cachey
except ImportError as ex:
raise ImportError(
'Cache requires cachey, "{ex}" problem ' "importing".format(ex=str(ex))
) from ex
self._nbytes = cachey.nbytes
if isinstance(cache, Number):
cache = cachey.Cache(cache, *args, **kwargs)
else:
assert not args and not kwargs
self.cache = cache
self.starttimes = dict()
def _start(self, dsk):
self.durations = dict()
overlap = set(dsk) & set(self.cache.data)
for key in overlap:
dsk[key] = self.cache.data[key]
def _pretask(self, key, dsk, state):
self.starttimes[key] = default_timer()
def _posttask(self, key, value, dsk, state, id):
duration = default_timer() - self.starttimes[key]
deps = state["dependencies"][key]
if deps:
duration += max(self.durations.get(k, 0) for k in deps)
self.durations[key] = duration
nb = self._nbytes(value) + overhead + sys.getsizeof(key) * 4
self.cache.put(key, value, cost=duration / nb / 1e9, nbytes=nb)
def _finish(self, dsk, state, errored):
self.starttimes.clear()
self.durations.clear()
| [
{
"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": "no_function_exceeds_5_params",
"question": "Does every function in this file take 5 or fewer parameters (excluding self/... | 3 | dask/cache.py | dgerlanc/dask |
# coding: utf-8
"""
speechapi
Speech APIs enable you to recognize speech and convert it to text using advanced machine learning, and also to convert text to speech. # noqa: E501
OpenAPI spec version: v1
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from __future__ import absolute_import
import unittest
import cloudmersive_voicerecognition_api_client
from cloudmersive_voicerecognition_api_client.models.text_to_speech_request import TextToSpeechRequest # noqa: E501
from cloudmersive_voicerecognition_api_client.rest import ApiException
class TestTextToSpeechRequest(unittest.TestCase):
"""TextToSpeechRequest unit test stubs"""
def setUp(self):
pass
def tearDown(self):
pass
def testTextToSpeechRequest(self):
"""Test TextToSpeechRequest"""
# FIXME: construct object with mandatory attributes with example values
# model = cloudmersive_voicerecognition_api_client.models.text_to_speech_request.TextToSpeechRequest() # noqa: E501
pass
if __name__ == '__main__':
unittest.main()
| [
{
"point_num": 1,
"id": "has_multiple_inheritance",
"question": "Does any class in this file use multiple inheritance?",
"answer": false
},
{
"point_num": 2,
"id": "more_functions_than_classes",
"question": "Does this file define more functions than classes?",
"answer": true
},... | 3 | test/test_text_to_speech_request.py | Cloudmersive/Cloudmersive.APIClient.Python.VoiceRecognition |
# Made by disKret
import sys
from ru.catssoftware.gameserver.model.quest import State
from ru.catssoftware.gameserver.model.quest import QuestState
from ru.catssoftware.gameserver.model.quest.jython import QuestJython as JQuest
qn = "19_GoToThePastureland"
#NPC
VLADIMIR = 31302
TUNATUN = 31537
#ITEMS
BEAST_MEAT = 7547
class Quest (JQuest) :
def __init__(self,id,name,descr):
JQuest.__init__(self,id,name,descr)
self.questItemIds = [BEAST_MEAT]
def onEvent (self,event,st) :
htmltext = event
if event == "31302-1.htm" :
st.giveItems(BEAST_MEAT,1)
st.set("cond","1")
st.setState(State.STARTED)
st.playSound("ItemSound.quest_accept")
if event == "31537-1.htm" :
st.takeItems(BEAST_MEAT,1)
st.rewardItems(57,50000)
st.addExpAndSp(136766,12688)
st.unset("cond")
st.exitQuest(False)
st.playSound("ItemSound.quest_finish")
return htmltext
def onTalk (self,npc,player):
htmltext = "<html><body>You are either not on a quest that involves this NPC, or you don't meet this NPC's minimum quest requirements.</body></html>"
st = player.getQuestState(qn)
if not st : return htmltext
npcId = npc.getNpcId()
id = st.getState()
cond = st.getInt("cond")
if npcId == VLADIMIR :
if cond == 0 :
if id == State.COMPLETED :
htmltext = "<html><body>This quest has already been completed.</body></html>"
elif player.getLevel() >= 63 :
htmltext = "31302-0.htm"
else:
htmltext = "<html><body>Quest for characters level 63 or above.</body></html>"
st.exitQuest(1)
else :
htmltext = "31302-2.htm"
elif id == State.STARTED :
htmltext = "31537-0.htm"
return htmltext
QUEST = Quest(19,qn,"Go to the Pastureland!")
QUEST.addStartNpc(VLADIMIR)
QUEST.addTalkId(VLADIMIR)
QUEST.addTalkId(TUNATUN) | [
{
"point_num": 1,
"id": "every_function_under_20_lines",
"question": "Is every function in this file shorter than 20 lines?",
"answer": false
},
{
"point_num": 2,
"id": "all_params_annotated",
"question": "Does every function parameter in this file have a type annotation (excluding s... | 3 | game/data/scripts/quests/19_GoToThePastureland/__init__.py | TheDemonLife/Lineage2Server-Interlude |
import utils
class TXInput(object):
""" Represents a transaction input
Args:
txid (string): Transaction ID.
vout (int): Transaction output value.
sig (string): Signature.
pubkey (string): Public key.
Attributes:
_tx_id (bytes): Transaction ID.
_vout (int): Transaction output value.
_sig (string): Signature.
_public_key (string): Public key.
"""
def __init__(self, txid, vout, sig, pubkey):
self._tx_id = utils.encode(txid)
self._vout = vout
self._sig = sig
self._public_key = pubkey
def uses_key(self, pubkey_hash):
# checks whether the address initiated the transaction
pubkey_hash = utils.hash_public_key(self._public_key)
return pubkey_hash == pubkey_hash
def __repr__(self):
return 'TXInput(tx_id={0!r}, vout={1!r}, signature={2!r}, public_key={3!r})'.format(
self._tx_id, self._vout, self._sig, self._public_key)
@property
def tx_id(self):
return utils.decode(self._tx_id)
@property
def vout(self):
return self._vout
@property
def signature(self):
return self._sig
@property
def public_key(self):
return self._public_key
@signature.setter
def signature(self, sig):
self._sig = sig
@public_key.setter
def public_key(self, public_key):
self._public_key = public_key
| [
{
"point_num": 1,
"id": "no_function_exceeds_5_params",
"question": "Does every function in this file take 5 or fewer parameters (excluding self/cls)?",
"answer": true
},
{
"point_num": 2,
"id": "more_functions_than_classes",
"question": "Does this file define more functions than cla... | 3 | blockchain-py/transaction_input.py | andybi7676/blockchain-py |
import ffmpeg
import cv2
import uuid
import os
import base64
import numpy as np
def save_video_to_file(file, vid, fps):
writer = cv2.VideoWriter(file.name, cv2.VideoWriter_fourcc('M','J','P','G'), fps, (vid.shape[2], vid.shape[1]))
for img in vid:
writer.write(np.flip(img, axis=2))
writer.release()
def convert(input, output):
ffmpeg.input(input).output(output).run()
def video_to_gif(vid, fps=10):
filename = uuid.uuid4()
with open(f"/tmp/{filename}.avi", "w") as avi:
save_video_to_file(avi, vid, fps)
ffmpeg.input(f"/tmp/{filename}.avi").output(f"/tmp/{filename}.gif").run()
with open(f"/tmp/{filename}.gif", "rb") as image_file:
gif_b64 = base64.b64encode(image_file.read()).decode("utf-8")
os.remove(f"/tmp/{filename}.avi")
os.remove(f"/tmp/{filename}.gif")
return gif_b64 | [
{
"point_num": 1,
"id": "every_function_under_20_lines",
"question": "Is every function in this file shorter than 20 lines?",
"answer": true
},
{
"point_num": 2,
"id": "no_function_exceeds_5_params",
"question": "Does every function in this file take 5 or fewer parameters (excluding ... | 3 | live/gif.py | svenschultze/Colab-Live-Figures |
import numpy as np
def _sample_unit_circle(n_samples: int = 1) -> np.ndarray:
"""
>>> np.isclose(np.linalg.norm(_sample_unit_circle(1)), 1)
True
"""
theta = np.random.rand(n_samples) * 2 * np.pi
x = np.cos(theta)
y = np.sin(theta)
xy = np.array([x, y]).T
assert xy.shape == (n_samples, 2)
return xy
def _sample_four_particle_torsion_scan(n_samples: int = 1) -> np.ndarray:
"""Generate n_samples random configurations of a 4-particle system abcd where
* distances ab, bc, cd are constant,
* angles abc, bcd are constant
* dihedral angle abcd is uniformly distributed in [0, 2pi]
Returns
-------
xyz : np.ndarray, shape = (n_samples, 4, 3)
Notes
-----
* Positions of a,b,c are constant, and x-coordinate of d is constant.
To be more exacting, could add random displacements and rotations.
"""
a = (-3, -1, 0)
b = (-2, 0, 0)
c = (-1, 0, 0)
d = (0, 1, 0)
# form one 3D configuration
conf = np.array([a, b, c, d])
assert conf.shape == (4, 3)
# make n_samples copies
xyz = np.array([conf] * n_samples, dtype=float)
assert xyz.shape == (n_samples, 4, 3)
# assign y and z coordinates of particle d to unit-circle samples
xyz[:, 3, 1:] = _sample_unit_circle(n_samples)
return xyz
def _timemachine_signed_torsion_angle(ci, cj, ck, cl):
"""Reference implementation from Yutong Zhao's timemachine
Copied directly from
https://github.com/proteneer/timemachine/blob/1a0ab45e605dc1e28c44ea90f38cb0dedce5c4db/timemachine/potentials/bonded.py#L152-L199
(but with 3 lines of dead code removed, and delta_r inlined)
"""
rij = cj - ci
rkj = cj - ck
rkl = cl - ck
n1 = np.cross(rij, rkj)
n2 = np.cross(rkj, rkl)
y = np.sum(
np.multiply(
np.cross(n1, n2), rkj / np.linalg.norm(rkj, axis=-1, keepdims=True)
),
axis=-1,
)
x = np.sum(np.multiply(n1, n2), -1)
return np.arctan2(y, x)
| [
{
"point_num": 1,
"id": "every_function_under_20_lines",
"question": "Is every function in this file shorter than 20 lines?",
"answer": false
},
{
"point_num": 2,
"id": "all_params_annotated",
"question": "Does every function parameter in this file have a type annotation (excluding s... | 3 | espaloma/utils/geometry.py | jstaker7/espaloma |
import numpy as np
import torch
from torch import nn as nn
from rlkit.policies.base import Policy
from rlkit.torch.core import eval_np
from rlkit.torch.distributions.tanh_normal import TanhNormal
class TanhPolicy(Policy, nn.Module):
def __init__(
self,
module,
return_raw_action=False,
):
super().__init__()
self.module = module
self.return_raw_action = return_raw_action
def get_action(self, obs_np):
if self.return_raw_action:
actions, raw_actions = self.get_actions(obs_np[None])
return actions[0, :], {'raw_action':raw_actions[0,:]}
else:
actions = self.get_actions(obs_np[None])
return actions[0, :], {}
def get_actions(self, obs_np):
if self.return_raw_action:
with torch.no_grad():
actions, info = self.forward(torch.tensor(obs_np).float(), return_info=True)
raw_actions = info['preactivation']
return np.array(actions), np.array(raw_actions)
else:
return eval_np(self, obs_np)
def forward(
self,
obs,
return_info=False,
):
"""
:param obs: Observation
:param return_info: If True, return info
"""
pre_tanh_value = self.module(obs)
action = torch.tanh(pre_tanh_value)
info = dict(
preactivation=pre_tanh_value,
)
if return_info:
return action, info
else:
return action
| [
{
"point_num": 1,
"id": "all_function_names_snake_case",
"question": "Are all function names in this file written in snake_case?",
"answer": true
},
{
"point_num": 2,
"id": "more_functions_than_classes",
"question": "Does this file define more functions than classes?",
"answer": ... | 3 | rlkit/torch/policies/tanh_policy.py | maxiaoba/rlk |
"""Post table
Revision ID: 79db95db1114
Revises: 148200b7a331
Create Date: 2019-11-21 11:03:05.596270
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '79db95db1114'
down_revision = '148200b7a331'
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.create_table('post',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('body', sa.String(length=200), nullable=True),
sa.Column('timestamp', sa.DateTime(), nullable=True),
sa.Column('user_id', sa.Integer(), nullable=True),
sa.ForeignKeyConstraint(['user_id'], ['user.id'], ),
sa.PrimaryKeyConstraint('id')
)
op.create_index(op.f('ix_post_timestamp'), 'post', ['timestamp'], unique=False)
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_index(op.f('ix_post_timestamp'), table_name='post')
op.drop_table('post')
# ### end Alembic commands ###
| [
{
"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 | migrations/versions/79db95db1114_post_table.py | Abdulrahmannaser/Micro-blog |
import torch
import torch.nn as nn
import torch.nn.functional as F
class cross_entropy_prob(nn.Module):
def __init__(self):
super(cross_entropy_prob, self).__init__()
def forward(self, pred, soft_targets):
pred = F.log_softmax(pred)
loss = torch.mean(torch.sum(- soft_targets * pred, 1))
return loss
| [
{
"point_num": 1,
"id": "every_function_has_docstring",
"question": "Does every function in this file have a docstring?",
"answer": false
},
{
"point_num": 2,
"id": "has_nested_function_def",
"question": "Does this file contain any function defined inside another function?",
"ans... | 3 | loss/cross_entropy_prob.py | zwx8981/DBCNN-Pytorch |
import os
import unittest
from satsearch.parser import SatUtilsParser
testpath = os.path.dirname(__file__)
class Test(unittest.TestCase):
""" Test main module """
args = 'search --datetime 2017-01-01 -p eo:cloud_cover=0/20 eo:platform=landsat-8'
@classmethod
def get_test_parser(cls):
""" Get testing parser with search and load subcommands """
parser = SatUtilsParser.newbie(description='sat-search testing')
return parser
def test_empty_parse_args(self):
""" Parse empty arguments """
parser = self.get_test_parser() #import pdb; pdb.set_trace()
with self.assertRaises(SystemExit):
args = parser.parse_args([])
def test_empty_parse_search_args(self):
""" Parse empty arguments """
parser = self.get_test_parser()
args = parser.parse_args(['search'])
self.assertEqual(len(args), 3)
self.assertFalse(args['printcal'])
def test_parse_args(self):
""" Parse arguments """
parser = self.get_test_parser()
args = self.args.split(' ')
args = parser.parse_args(args)
self.assertEqual(len(args), 5)
self.assertEqual(args['datetime'], '2017-01-01')
#assert(args['eo:cloud_cover'] == '0/20')
#self.assertEqual(args['cloud_from'], 0)
#self.assertEqual(args['cloud_to'], 20)
#self.assertEqual(args['satellite_name'], 'Landsat-8')
#self.assertEqual(args['dayOrNight'], 'DAY')
def _test_parse_args_badcloud(self):
parser = self.get_test_parser()
with self.assertRaises(ValueError):
args = parser.parse_args('search --datetime 2017-01-01 --cloud 0.5 eo:platform Landsat-8'.split(' '))
| [
{
"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 | test/test_parser.py | lishrimp/sat-search |
from pyunity import Behaviour, GameObject, SceneManager, Material, Color, Mesh, Vector3, MeshRenderer
class Switch(Behaviour):
def Start(self):
self.a = 3
def Update(self, dt):
self.a -= dt
if self.a < 0:
SceneManager.LoadSceneByIndex(1)
def main():
scene = SceneManager.AddScene("Scene")
scene2 = SceneManager.AddScene("Scene 2")
scene.mainCamera.transform.localPosition = Vector3(0, 0, -10)
scene2.mainCamera.transform.localPosition = Vector3(0, 0, -10)
cube = GameObject("Cube")
renderer = cube.AddComponent(MeshRenderer)
renderer.mesh = Mesh.cube(2)
renderer.mat = Material(Color(255, 0, 0))
cube.AddComponent(Switch)
scene.Add(cube)
cube2 = GameObject("Cube 2")
renderer = cube2.AddComponent(MeshRenderer)
renderer.mesh = Mesh.cube(2)
renderer.mat = Material(Color(0, 0, 255))
scene2.Add(cube2)
SceneManager.LoadScene(scene)
if __name__ == "__main__":
main()
| [
{
"point_num": 1,
"id": "every_function_under_20_lines",
"question": "Is every function in this file shorter than 20 lines?",
"answer": false
},
{
"point_num": 2,
"id": "more_functions_than_classes",
"question": "Does this file define more functions than classes?",
"answer": true... | 3 | pyunity/examples/example7/__init__.py | Knight1632/pyunity |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.