source string | points list | n_points int64 | path string | repo string |
|---|---|---|---|---|
# Copyright 2021 Huawei Technologies Co., Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
import mindspore as ms
from mindspore import context
from mindspore.ops.operations.comm_ops import AlltoAll, NeighborExchange
from mindspore.communication.management import GlobalComm, init
context.set_context(device_target="Ascend")
GlobalComm.CHECK_ENVS = False
init("hccl")
GlobalComm.CHECK_ENVS = True
class FnDict:
def __init__(self):
self.fnDict = {}
def __call__(self, fn):
self.fnDict[fn.__name__] = fn
def __getitem__(self, name):
return self.fnDict[name]
def test_neighbor_exchange(tag):
fns = FnDict()
neighbor = NeighborExchange(send_rank_ids=[0], recv_rank_ids=[1], recv_shapes=([2, 2],), send_shapes=([2, 2],),
recv_type=ms.float32)
@fns
def before(x):
return neighbor(x)
return fns[tag]
def test_all_to_all(tag):
context.set_auto_parallel_context(device_num=2, global_rank=0)
fns = FnDict()
altoall = AlltoAll(split_count=2, split_dim=2, concat_dim=3)
@fns
def before(x):
return altoall(x)
return fns[tag]
| [
{
"point_num": 1,
"id": "all_params_annotated",
"question": "Does every function parameter in this file have a type annotation (excluding self/cls)?",
"answer": false
},
{
"point_num": 2,
"id": "every_function_has_docstring",
"question": "Does every function in this file have a docst... | 3 | tests/ut/cpp/python_input/gtest_input/pre_activate/all_to_all_unify_mindir_test.py | PowerOlive/mindspore |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
#
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
from aliyunsdkcore.request import RpcRequest
class OnsMqttQueryClientByTopicRequest(RpcRequest):
def __init__(self):
RpcRequest.__init__(self, 'Ons', '2017-09-18', 'OnsMqttQueryClientByTopic')
def get_PreventCache(self):
return self.get_query_params().get('PreventCache')
def set_PreventCache(self,PreventCache):
self.add_query_param('PreventCache',PreventCache)
def get_OnsRegionId(self):
return self.get_query_params().get('OnsRegionId')
def set_OnsRegionId(self,OnsRegionId):
self.add_query_param('OnsRegionId',OnsRegionId)
def get_OnsPlatform(self):
return self.get_query_params().get('OnsPlatform')
def set_OnsPlatform(self,OnsPlatform):
self.add_query_param('OnsPlatform',OnsPlatform)
def get_ParentTopic(self):
return self.get_query_params().get('ParentTopic')
def set_ParentTopic(self,ParentTopic):
self.add_query_param('ParentTopic',ParentTopic)
def get_SubTopic(self):
return self.get_query_params().get('SubTopic')
def set_SubTopic(self,SubTopic):
self.add_query_param('SubTopic',SubTopic) | [
{
"point_num": 1,
"id": "more_functions_than_classes",
"question": "Does this file define more functions than classes?",
"answer": true
},
{
"point_num": 2,
"id": "all_params_annotated",
"question": "Does every function parameter in this file have a type annotation (excluding self/cl... | 3 | aliyun-python-sdk-ons/aliyunsdkons/request/v20170918/OnsMqttQueryClientByTopicRequest.py | DataDog/aliyun-openapi-python-sdk |
from abc import ABCMeta, abstractmethod
class Scene(object):
__metaclass__ = ABCMeta
@abstractmethod
def enter(self):
"""
Enter method to every scene
:return:
"""
pass
class Engine(object):
__metaclass__ = ABCMeta
def __init__(self, scene_map):
self.scene_map = scene_map
@abstractmethod
def play(self):
pass
class Map(object):
__metaclass__ = ABCMeta
def __init__(self, start_scene):
self.start_scene = start_scene
@abstractmethod
def next_scene(self, scene_name):
pass
@abstractmethod
def opening_scene(self):
pass
| [
{
"point_num": 1,
"id": "no_function_exceeds_5_params",
"question": "Does every function in this file take 5 or fewer parameters (excluding self/cls)?",
"answer": true
},
{
"point_num": 2,
"id": "every_class_has_docstring",
"question": "Does every class in this file have a docstring?... | 3 | design_patterns/oop/alien_game/__init__.py | JASTYN/pythonmaster |
class ElementIntersectsElementFilter(ElementIntersectsFilter, IDisposable):
"""
A filter to find elements that intersect the solid geometry of a given element.
ElementIntersectsElementFilter(element: Element,inverted: bool)
ElementIntersectsElementFilter(element: Element)
"""
def Dispose(self):
""" Dispose(self: ElementFilter,A_0: bool) """
pass
def GetElement(self):
"""
GetElement(self: ElementIntersectsElementFilter) -> Element
Gets the target element.
Returns: The element.
"""
pass
def ReleaseUnmanagedResources(self, *args):
""" ReleaseUnmanagedResources(self: ElementFilter,disposing: bool) """
pass
def __enter__(self, *args):
""" __enter__(self: IDisposable) -> object """
pass
def __exit__(self, *args):
""" __exit__(self: IDisposable,exc_type: object,exc_value: object,exc_back: object) """
pass
def __init__(self, *args):
""" x.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signature """
pass
@staticmethod
def __new__(self, element, inverted=None):
"""
__new__(cls: type,element: Element,inverted: bool)
__new__(cls: type,element: Element)
"""
pass
| [
{
"point_num": 1,
"id": "has_multiple_inheritance",
"question": "Does any class in this file use multiple inheritance?",
"answer": true
},
{
"point_num": 2,
"id": "all_function_names_snake_case",
"question": "Are all function names in this file written in snake_case?",
"answer": ... | 3 | release/stubs.min/Autodesk/Revit/DB/__init___parts/ElementIntersectsElementFilter.py | YKato521/ironpython-stubs |
def title(t):
print('\033[36m'+str(t)+'\033[90m')
def info(i):
print('\033[90m'+str(i))
def error(e):
print('\033[91m'+str(e)+'\033[90m')
| [
{
"point_num": 1,
"id": "no_function_exceeds_5_params",
"question": "Does every function in this file take 5 or fewer parameters (excluding self/cls)?",
"answer": true
},
{
"point_num": 2,
"id": "all_function_names_snake_case",
"question": "Are all function names in this file written... | 3 | console.py | Frank-Mayer/yule |
from toontown.dna import DNALandmarkBuilding
from toontown.dna import DNAError
from toontown.dna import DNAUtil
class DNAAnimBuilding(DNALandmarkBuilding.DNALandmarkBuilding):
__slots__ = (
'animName')
COMPONENT_CODE = 16
def __init__(self, name):
DNALandmarkBuilding.DNALandmarkBuilding.__init__(self, name)
self.animName = ''
def __del__(self):
DNALandmarkBuilding.DNALandmarkBuilding.__del__(self)
del self.animName
def setAnimName(self, name):
self.animName = str(name)
def getAnimName(self):
return self.animName
def makeFromDGI(self, dgi, store):
DNALandmarkBuilding.DNALandmarkBuilding.makeFromDGI(self, dgi, store)
self.animName = dgi.getString()
def traverse(self, np, store):
result = store.findNode(self.code)
if result.isEmpty():
raise DNAError.DNAError('DNAAnimBuilding code ' + self.code + ' not found in dnastore')
_np = result.copyTo(np)
_np.setName(self.name)
_np.setPosHprScale(self.pos, self.hpr, self.scale)
_np.setTag("DNAAnim", self.animName)
self.setupSuitBuildingOrigin(np, _np)
self.traverseChildren(np, store)
_np.flattenStrong() | [
{
"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 | toontown/dna/DNAAnimBuilding.py | LittleNed/toontown-stride |
"""
Wrapper for classes like `Paginator`.
"""
import inspect
from mypy_boto3_builder.import_helpers.import_record import ImportRecord
from mypy_boto3_builder.import_helpers.import_string import ImportString
from mypy_boto3_builder.type_annotations.fake_annotation import FakeAnnotation
class TypeClass(FakeAnnotation):
"""
Wrapper for classes like `Paginator`.
Arguments:
value -- Any Class.
alias -- Local name.
"""
def __init__(self, value: type, alias: str = "") -> None:
self.value: type = value
self.alias: str = alias
def render(self, parent_name: str = "") -> str:
"""
Render type annotation to a valid Python code for local usage.
Returns:
A string with a valid type annotation.
"""
if self.alias:
return self.alias
return self.get_import_name()
def get_import_name(self) -> str:
"""
Get name for import string.
"""
return self.value.__name__
def get_import_record(self) -> ImportRecord:
"""
Create an impoort record to insert where TypeClass is used.
"""
module = inspect.getmodule(self.value)
if module is None:
raise ValueError(f"Unknown module for {self.value}")
module_name = module.__name__
return ImportRecord(
source=ImportString.from_str(module_name),
name=self.get_import_name(),
alias=self.alias,
)
def copy(self) -> "TypeClass":
"""
Create a copy of type annotation wrapper.
"""
return TypeClass(self.value, self.alias)
| [
{
"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 | mypy_boto3_builder/type_annotations/type_class.py | benesch/mypy_boto3_builder |
from benchmarkstt.helpers import make_printable
from benchmarkstt.deferred import DeferredCallback
import pytest
def cb(txt):
def _():
_.cb_count += 1
return '[%s]' % (txt,)
_.cb_count = 0
return _
class ToDefer:
def __init__(self, value):
self.value = value
self.cb_count = 0
def __repr__(self):
self.cb_count += 1
return '<ToDefer:%s>' % (repr(self.value),)
def test_deferred_str():
callback = cb('test')
deferred = DeferredCallback(callback)
assert callback.cb_count == 0
assert str(deferred) == '[test]'
assert callback.cb_count == 1
assert repr(deferred) == '<DeferredCallback:\'[test]\'>'
assert callback.cb_count == 2
@pytest.mark.parametrize('orig,printable', [
['', ''],
[' ', '·'],
['I\'m afraid I\thave no choice\nbut to sell you all for\tscientific experiments.',
'I\'m·afraid·I␉have·no·choice␊but·to·sell·you·all·for␉scientific·experiments.']
])
def test_make_printable(orig, printable):
assert make_printable(orig) == printable
| [
{
"point_num": 1,
"id": "more_functions_than_classes",
"question": "Does this file define more functions than classes?",
"answer": true
},
{
"point_num": 2,
"id": "every_function_under_20_lines",
"question": "Is every function in this file shorter than 20 lines?",
"answer": true
... | 3 | tests/benchmarkstt/test_benchmarkstt.py | ebu/benchmarkstt |
import numpy as np
from ..base.mixins import RandomStateMixin
from ..policies.base import BasePolicy
from ..utils import argmax
__all__ = (
'EpsilonGreedy',
# 'BoltzmannPolicy', #TODO: implement
)
class EpsilonGreedy(BasePolicy, RandomStateMixin):
"""
Value-based policy to select actions using epsilon-greedy strategy.
Parameters
----------
q_function : callable
A state-action value function object.
epsilon : float between 0 and 1
The probability of selecting an action uniformly at random.
random_seed : int, optional
Sets the random state to get reproducible results.
"""
def __init__(self, q_function, epsilon=0.1, random_seed=None):
self.q_function = q_function
self.epsilon = epsilon
self.random_seed = random_seed # sets self.random in RandomStateMixin
def __call__(self, s):
if self.random.rand() < self.epsilon:
return self.q_function.env.action_space.sample()
a = self.greedy(s)
return a
def set_epsilon(self, epsilon):
"""
Change the value for ``epsilon``.
Parameters
----------
epsilon : float between 0 and 1
The probability of selecting an action uniformly at random.
Returns
-------
self
The updated instance.
"""
self.epsilon = epsilon
return self
def greedy(self, s):
Q = self.q_function(s) # shape: [num_actions]
a = argmax(Q)
return a
def dist_params(self, s):
Q = self.q_function(s) # shape: [num_actions]
a = argmax(Q)
n = self.q_function.num_actions
p = np.ones(n) * self.epsilon / n
p[a] += 1 - self.epsilon
assert p.sum() == 1
return p
| [
{
"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 | keras_gym/policies/value_based.py | KristianHolsheimer/keras-gym |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def bstToGst(self, root: TreeNode) -> TreeNode:
self.sum = 0
def dfs(node):
if node:
dfs(node.right)
node.val += self.sum
self.sum = node.val
dfs(node.left)
dfs(root)
return root | [
{
"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/tree/1038.binary-search-tree-to-greater-sum-tree/binary-search-tree-to-greater-sum-tree.py | lyphui/Just-Code |
import os
import shutil
import numpy as np
import tensorflow as tf
def path_exists(path, overwrite=False):
if not os.path.isdir(path):
os.mkdir(path)
elif overwrite == True :
shutil.rmtree(path)
return path
def remove_dir(path):
os.rmdir(path)
return True
def relu_init(shape, dtype=tf.float32, partition_info=None):
init_range = np.sprt(2.0 / shape[1])
return tf.random_normal(shape, dtype=dtype) * init_range
def ones(shape, dtype=tf.float32):
return tf.ones(shape, dtype=dtype)
def zeros(shape, dtype=tf.float32):
return tf.zeros(shape, dtype=dtype)
def tanh_init(shape, dtype=tf.float32, partition_info=None):
init_range = np.sqrt(6.0 / (shape[0] + shape[1]))
return tf.random_uniform(shape, minval=-init_range, maxval=init_range, dtype=dtype)
def leaky_relu(X, alpha=0.01):
return tf.maximum(X, alpha * X)
def max(input):
return tf.argmax(input)
| [
{
"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 | src/utils.py | MahdiSajedei/Searching-for-activation-functions |
"""
PyDraw-after: simple canvas paint program and object mover/animator
use widget.after scheduled events to implement object move loops, such
that more than one can be in motion at once without having to use threads;
this does moves in parallel, but seems to be slower than time.sleep version;
see also canvasDraw in Tour: builds and passes the incX/incY list at once:
here, would be allmoves = ([(incrX, 0)] * reptX) + ([(0, incrY)] * reptY)
"""
from movingpics import *
class MovingPicsAfter(MovingPics):
def doMoves(self, delay, objectId, incrX, reptX, incrY, reptY):
if reptX:
self.canvas.move(objectId, incrX, 0)
reptX -= 1
else:
self.canvas.move(objectId, 0, incrY)
reptY -= 1
if not (reptX or reptY):
self.moving.remove(objectId)
else:
self.canvas.after(delay,
self.doMoves, delay, objectId, incrX, reptX, incrY, reptY)
def onMove(self, event):
traceEvent('onMove', event, 0)
object = self.object # move cur obj to click spot
if object:
msecs = int(pickDelays[0] * 1000)
parms = 'Delay=%d msec, Units=%d' % (msecs, pickUnits[0])
self.setTextInfo(parms)
self.moving.append(object)
incrX, reptX, incrY, reptY = self.plotMoves(event)
self.doMoves(msecs, object, incrX, reptX, incrY, reptY)
self.where = event
if __name__ == '__main__':
from sys import argv # when this file is executed
if len(argv) == 2:
import movingpics # not this module's global
movingpics.PicDir = argv[1] # and from* doesn't link names
root = Tk()
MovingPicsAfter(root)
root.mainloop()
| [
{
"point_num": 1,
"id": "has_multiple_inheritance",
"question": "Does any class in this file use multiple inheritance?",
"answer": false
},
{
"point_num": 2,
"id": "no_function_exceeds_5_params",
"question": "Does every function in this file take 5 or fewer parameters (excluding self... | 3 | PP4E-Examples-1.4/Examples/PP4E/Gui/MovingPics/movingpics_after.py | AngelLiang/PP4E |
import re
import time
from pyquery import PyQuery as pq
from policy_crawl.common.fetch import get,post
from policy_crawl.common.save import save
from policy_crawl.common.logger import alllog,errorlog
def parse_detail(html,url):
alllog.logger.info("天津市教育厅: %s"%url)
doc=pq(html)
data={}
data["title"]=doc(".list_content td span").text()
data["content"]=doc(".tdfont").text().replace("\n","")
data["content_url"]=[item.attr("href") for item in doc(".tdfont a").items()]
try:
# data["publish_time"]=re.findall("(\d{4}年\d{1,2}月\d{1,2}日)",html)[0]
# data["publish_time"]=re.findall("(\d{4}/\d{1,2}/\d{1,2})",html)[0]
data["publish_time"]=re.findall("(\d{4}-\d{1,2}-\d{1,2})",html)[0]
except:
data["publish_time"]=""
errorlog.logger.error("url:%s 未找到publish_time"%url)
data["classification"]="天津市教育厅"
data["url"]=url
print(data)
save(data)
def parse_index(html):
doc=pq(html)
items=doc(".bb a").items()
for item in items:
url=item.attr("href")
if "http" not in url:
url="http://jy.tj.gov.cn/" + url
try:
html=get(url)
except:
errorlog.logger.error("url错误:%s"%url)
parse_detail(html,url)
time.sleep(1)
def main():
for i in range(1,60):
print(i)
url="http://jy.tj.gov.cn/info_list.jsp?classid=201707190828598801&curPage=" + str(i)
html=get(url)
parse_index(html)
if __name__ == '__main__':
main() | [
{
"point_num": 1,
"id": "no_function_exceeds_5_params",
"question": "Does every function in this file take 5 or fewer parameters (excluding self/cls)?",
"answer": true
},
{
"point_num": 2,
"id": "every_function_has_docstring",
"question": "Does every function in this file have a docs... | 3 | spiders/moe/all/tianjin.py | JJYYYY/policy_crawl |
class carro:
pass
NORTE = 'Norte'
LESTE = 'Leste'
SUL = 'Sul'
OESTE = 'Oeste'
class direcao:
rotacao_a_direita_dct = {NORTE: LESTE, LESTE: SUL, SUL: OESTE, OESTE: NORTE}
rotacao_a_esquerda_dct = {NORTE: OESTE, OESTE: SUL, SUL: LESTE, LESTE: NORTE}
def __init__(self):
self.valor = NORTE
def girar_a_direita(self):
self.valor = self.rotacao_a_direita_dct[self.valor]
def girar_a_esquerda(self):
self.valor = self.rotacao_a_esquerda_dct[self.valor]
class motor:
def __init__(self):
self.velocidade = 0
def acelertar(self):
self.velocidade += 1
def frear(self):
self.velocidade -= 2
self.velocidade = max(0, self.velocidade)
| [
{
"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 | oo/carro.py | cadica/pythonbirds |
# -*- coding: utf-8 -*-
import re
from osgeo import ogr
class ShpToGDALFeatures(object):
def __init__(self, shpFilePath=None):
if shpFilePath is None:
raise Exception('No shapefile path provided')
if re.search(r'(\.shp)$', shpFilePath) is None:
raise TypeError(
'Only shapefiles are supported. Provided path %s' % shpFilePath
)
self.shpFilePath = shpFilePath
self.drvName = 'ESRI Shapefile'
self.drv = ogr.GetDriverByName(self.drvName)
# Returns a list of GDAL Features
def __read__(self):
dataSource = self._getDatasource()
# 0 refers to read-only
layer = dataSource.GetLayer()
features = [feature for feature in layer]
if len(features) == 0:
return features
# raise Exception('Empty shapefile')
geometryType = features[0].GetGeometryRef().GetGeometryName()
if geometryType != 'POLYGON':
raise TypeError('Unsupported input geometry type: %s' % geometryType)
return features
def getFeatures(self):
dataSource = self._getDatasource()
layer = dataSource.GetLayer()
for feature in layer:
yield feature
def _getDatasource(self):
dataSource = self.drv.Open(self.shpFilePath, 0)
if dataSource is None:
raise IOError('Could not open %s' % self.shpFilePath)
return dataSource
| [
{
"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 | forge/lib/shapefile_utils.py | Pandinosaurus/3d-forge |
#!/usr/bin/env python
import sys
import agate
from csvkit.cli import CSVKitUtility
class CSVPy(CSVKitUtility):
description = 'Load a CSV file into a CSV reader and then drop into a Python shell.'
def add_arguments(self):
self.argparser.add_argument('--dict', dest='as_dict', action='store_true',
help='Load the CSV file into a DictReader.')
self.argparser.add_argument('--agate', dest='as_agate', action='store_true',
help='Load the CSV file into an agate table.')
def main(self):
if self.input_file == sys.stdin:
self.argparser.error('csvpy cannot accept input as piped data via STDIN.')
# Attempt reading filename, will cause lazy loader to access file and raise error if it does not exist
filename = self.input_file.name
if self.args.as_dict:
klass = agate.csv.DictReader
class_name = 'agate.csv.DictReader'
variable_name = 'reader'
elif self.args.as_agate:
klass = agate.Table.from_csv
class_name = 'agate.Table'
variable_name = 'table'
else:
klass = agate.csv.reader
class_name = 'agate.csv.reader'
variable_name = 'reader'
variable = klass(self.input_file, **self.reader_kwargs)
welcome_message = 'Welcome! "%s" has been loaded in an %s object named "%s".' % (filename, class_name, variable_name)
try:
from IPython.frontend.terminal.embed import InteractiveShellEmbed
exec('%s = variable' % variable_name)
ipy = InteractiveShellEmbed(banner1=welcome_message)
ipy()
except ImportError:
import code
code.interact(welcome_message, local={variable_name: variable})
def launch_new_instance():
utility = CSVPy()
utility.run()
if __name__ == '__main__':
launch_new_instance()
| [
{
"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 | csvkit/utilities/csvpy.py | felixbuenemann/csvkit |
from unittest import TestCase
from chatterbot.adapters.logic import LogicAdapter
class LogicAdapterTestCase(TestCase):
"""
This test case is for the LogicAdapter base class.
Although this class is not intended for direct use,
this test case ensures that exceptions requiring
basic functionality are triggered when needed.
"""
def setUp(self):
super(LogicAdapterTestCase, self).setUp()
self.adapter = LogicAdapter()
def test_can_process(self):
"""
This method should return true by default.
"""
self.assertTrue(self.adapter.can_process(""))
def test_process(self):
with self.assertRaises(LogicAdapter.AdapterMethodNotImplementedError):
self.adapter.process("")
def test_set_statement_comparison_function_string(self):
adapter = LogicAdapter(
statement_comparison_function='chatterbot.conversation.comparisons.levenshtein_distance'
)
self.assertTrue(callable(adapter.compare_statements))
def test_set_statement_comparison_function_callable(self):
from chatterbot.conversation.comparisons import levenshtein_distance
adapter = LogicAdapter(
statement_comparison_function=levenshtein_distance
)
self.assertTrue(callable(adapter.compare_statements))
def test_set_response_selection_method_string(self):
adapter = LogicAdapter(
response_selection_method='chatterbot.conversation.response_selection.get_first_response'
)
self.assertTrue(callable(adapter.select_response))
def test_set_response_selection_method_callable(self):
from chatterbot.conversation.response_selection import get_first_response
adapter = LogicAdapter(
response_selection_method=get_first_response
)
self.assertTrue(callable(adapter.select_response)) | [
{
"point_num": 1,
"id": "all_function_names_snake_case",
"question": "Are all function names in this file written in snake_case?",
"answer": false
},
{
"point_num": 2,
"id": "every_function_under_20_lines",
"question": "Is every function in this file shorter than 20 lines?",
"ans... | 3 | tests/logic_adapter_tests/test_logic_adapter.py | arnauddelaunay/ChatterBot |
from ascetic.contrib.versioning.exceptions import AlreadyRegistered, NotRegistered
from ascetic.contrib.versioning.interfaces import IRegistry
class Registry(IRegistry):
def __init__(self):
self._fields_mapping = dict()
self._object_accessor_mapping = dict()
def register(self, model, fields, object_accessor):
if model in self._fields_mapping:
raise AlreadyRegistered("Already registered {0}".format(model.__name__))
self._fields_mapping[model] = fields
self._object_accessor_mapping[model] = fields
def unregister(self, model):
"""
:type model: object
"""
del self._fields_mapping[model]
del self._object_accessor_mapping[model]
def get_fields(self, model):
try:
return self._fields_mapping[model]
except KeyError:
raise NotRegistered('"{0}" is not registerd'.format(model))
def get_object_accessor(self, model):
try:
return self._object_accessor_mapping[model]
except KeyError:
raise NotRegistered('"{0}" is not registerd'.format(model))
| [
{
"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 | ascetic/contrib/versioning/registry.py | emacsway/ascetic |
from flying_ioc import IocManager
class TSingleton1:
def __init__(self):
pass
def test_singleton_container():
ioc = IocManager(stats=True)
ioc.set_class(name='singleton1', cls=TSingleton1, singleton=True)
assert ioc.singleton1 is ioc.singleton1
ioc.print_stats()
| [
{
"point_num": 1,
"id": "every_function_under_20_lines",
"question": "Is every function in this file shorter than 20 lines?",
"answer": true
},
{
"point_num": 2,
"id": "more_functions_than_classes",
"question": "Does this file define more functions than classes?",
"answer": true
... | 3 | tests/test_singleton_container.py | ClanPlay/Python_IoC |
import flask
from flask import Flask,jsonify,request
import json
from data_input import data_in
import numpy as np
import pickle
def load_models():
file_name = './models/model_file.p'
with open(file_name,'rb') as pickled:
data = pickle.load(pickled)
model = data['model']
return model
app = Flask(__name__)
@app.route('/predict',methods=['GET'])
def predict():
request_json = request.get_json()
x = request_json['input']
x_in = np.array(x).reshape(1,-1)
model = load_models()
prediction = model.predict(x_in)[0]
response = json.dumps({'response': prediction})
return response,200
if __name__ == '__main__':
application.run(debug=True) | [
{
"point_num": 1,
"id": "every_function_has_docstring",
"question": "Does every function in this file have a docstring?",
"answer": false
},
{
"point_num": 2,
"id": "has_nested_function_def",
"question": "Does this file contain any function defined inside another function?",
"ans... | 3 | Data Science salary prediction/FlaskAPI/app.py | negiaditya/PROJECTS-Data_Science |
import pytest
from test_fixtures.scenarios.basic import * # noqa
from organizations.tests.conftest import organization_random # noqa - used by local tests
from logs.tests.conftest import flexible_slicer_test_data, report_type_nd # noqa
@pytest.fixture
def root_platform(platforms):
return platforms['root']
@pytest.fixture
def tr_report(report_types):
return report_types['tr']
| [
{
"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 | apps/api/tests/conftest.py | techlib/czechelib-stats |
import unittest
from ebird.api.validation import is_subnational1
class IsSubnational1Tests(unittest.TestCase):
"""Tests for the is_subnational1 validation function."""
def test_is_subnational1(self):
self.assertTrue(is_subnational1("US-NV"))
def test_invalid_code_is_not_subnational1(self):
self.assertFalse(is_subnational1("U"))
self.assertFalse(is_subnational1("US-"))
def test_country_is_not_subnational1(self):
self.assertFalse(is_subnational1("US"))
def test_subnational2_is_not_subnational1(self):
self.assertFalse(is_subnational1("US-NV-VMT"))
def test_location_is_not_subnational1(self):
self.assertFalse(is_subnational1("L123456"))
| [
{
"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/validation/test_is_subnational1.py | StuartMacKay/ebird-api |
from logging import getLogger
import slack
logger = getLogger(__name__)
class ChannelListNotLoadedError(RuntimeError):
pass
class ChannelNotFoundError(RuntimeError):
pass
class FileNotUploadedError(RuntimeError):
pass
class SlackAPI(object):
def __init__(self, token, channel: str, to_user: str) -> None:
self._client = slack.WebClient(token=token)
self._channel_id = self._get_channel_id(channel)
self._to_user = to_user if to_user == '' or to_user.startswith('@') else '@' + to_user
def _get_channels(self, channels=[], cursor=None):
params = {}
if cursor:
params['cursor'] = cursor
response = self._client.api_call('channels.list', http_verb="GET", params=params)
if not response['ok']:
raise ChannelListNotLoadedError(f'Error while loading channels. The error reason is "{response["error"]}".')
channels += response.get('channels', [])
if not channels:
raise ChannelListNotLoadedError('Channel list is empty.')
if response['response_metadata']['next_cursor']:
return self._get_channels(channels, response['response_metadata']['next_cursor'])
else:
return channels
def _get_channel_id(self, channel_name):
for channel in self._get_channels():
if channel['name'] == channel_name:
return channel['id']
raise ChannelNotFoundError(f'Channel {channel_name} is not found in public channels.')
def send_snippet(self, comment, title, content):
request_body = dict(
channels=self._channel_id,
initial_comment=f'<{self._to_user}> {comment}' if self._to_user else comment,
content=content,
title=title)
response = self._client.api_call('files.upload', data=request_body)
if not response['ok']:
raise FileNotUploadedError(f'Error while uploading file. The error reason is "{response["error"]}".')
| [
{
"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_has_docstring",
"question": "Does every function in this file have a docstring?",
"answer": false
},
... | 3 | gokart/slack/slack_api.py | skmatz/gokart |
class Calls(object):
def __init__(self):
self.calls = []
def addCall(self, call):
self.calls.append(call)
def endCall(self, call):
for c in self.calls:
if call.ID == c.ID:
self.calls.remove(call)
def searchCall(self, call_id):
for c in self.calls:
if call_id == c.ID:
return c
return None
def printaCalls(self):
for i in self.calls:
print(i.status) | [
{
"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 | basic/calls.py | Mateuskim/call-center |
from datetime import datetime
from django.core import mail
from django.core.mail import EmailMessage
from src.rooms.models import Donation, Room
def send_email(data):
message = EmailMessage(data['subject'], data['message'], to=data['to'])
return message.send()
def send_mass_email(email_message_list):
connection = mail.get_connection()
messages = email_message_list
return connection.send_messages(messages)
# will be shared task
def close_rooms():
today = datetime.now().date()
outdated_rooms = Room.objects.filter(expires__lt=today)
for room in outdated_rooms:
notify_creator(room)
notify_interested(room)
room.is_active = False
room.save()
# will be shared tasks
def room_collected(id):
room = Room.objects.get(id=id)
notify_creator(room)
notify_interested(room)
room.is_active = False
room.save()
def notify_creator(room):
resume = Donation.objects.filter(room_id=room.id).resume()
message = {
'subject': 'Tytuł',
'message': resume,
'to': ['bartosz@wp.com',]
}
return send_email(message)
def notify_interested(room):
subject = f'Została zakończona zbiórka {room.gift}'
with open('./interested_email.txt') as body:
body = body.replace('<osiąginięto>', room.collected)
interested = room.get_interested()
messages = []
for user in interested:
messages.append(EmailMessage(
'Zbiórka została zakończona',
body,
to=[user.email],
))
send_mass_email(messages)
| [
{
"point_num": 1,
"id": "no_function_exceeds_5_params",
"question": "Does every function in this file take 5 or fewer parameters (excluding self/cls)?",
"answer": true
},
{
"point_num": 2,
"id": "all_function_names_snake_case",
"question": "Are all function names in this file written... | 3 | src/notifications/tasks.py | Bounty1993/my-blog |
# Copyright 2019. ThingsBoard
#
# 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.
class EventStorageReaderPointer:
def __init__(self, file, line):
self.file = file
self.line = line
def __eq__(self, other):
return self.file == other.file and self.line == other.line
def __hash__(self):
return hash((self.file, self.line))
def get_file(self):
return self.file
def get_line(self):
return self.line
def set_file(self, file):
self.file = file
def set_line(self, line):
self.line = line
| [
{
"point_num": 1,
"id": "all_params_annotated",
"question": "Does every function parameter in this file have a type annotation (excluding self/cls)?",
"answer": false
},
{
"point_num": 2,
"id": "every_function_has_docstring",
"question": "Does every function in this file have a docst... | 3 | thingsboard_gateway/storage/event_storage_reader_pointer.py | xinge-ok/thingsboard-gateway |
from django.apps import AppConfig
from django.db import connections as djcs
from django.core.exceptions import ImproperlyConfigured
class ExplorerAppConfig(AppConfig):
name = 'explorer'
def ready(self):
from explorer.schema import build_async_schemas
_validate_connections()
build_async_schemas()
def _get_default():
from explorer.app_settings import EXPLORER_DEFAULT_CONNECTION
return EXPLORER_DEFAULT_CONNECTION
def _get_explorer_connections():
from explorer.app_settings import EXPLORER_CONNECTIONS
return EXPLORER_CONNECTIONS
def _validate_connections():
# Validate connections
if _get_default() not in _get_explorer_connections().values():
raise ImproperlyConfigured(
'EXPLORER_DEFAULT_CONNECTION is %s, but that alias is not present in the values of EXPLORER_CONNECTIONS'
% _get_default())
for name, conn_name in _get_explorer_connections().items():
if conn_name not in djcs:
raise ImproperlyConfigured(
'EXPLORER_CONNECTIONS contains (%s, %s), but %s is not a valid Django DB connection.'
% (name, conn_name, conn_name))
| [
{
"point_num": 1,
"id": "every_function_has_docstring",
"question": "Does every function in this file have a docstring?",
"answer": false
},
{
"point_num": 2,
"id": "more_functions_than_classes",
"question": "Does this file define more functions than classes?",
"answer": true
}... | 3 | explorer/apps.py | vrjbvishnu/django-sql-explorer |
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
from base import BaseObject
class SiblingsDictGenerator(BaseObject):
def __init__(self, some_df):
BaseObject.__init__(self, __name__)
self.df = some_df
@staticmethod
def normalize(some_dict):
the_normalized_dict = {}
for key in some_dict:
the_normalized_dict[key] = list(some_dict[key])
return the_normalized_dict
def process(self):
the_siblings_dict = {}
for i, row in self.df.iterrows():
source = row["name"].lower().strip()
target = [x.lower().strip() for x in row["members"].split(",")]
if source not in the_siblings_dict:
the_siblings_dict[source] = set()
the_siblings_dict[source] = the_siblings_dict[source].union(
target)
return self.normalize(the_siblings_dict)
| [
{
"point_num": 1,
"id": "all_function_names_snake_case",
"question": "Are all function names in this file written in snake_case?",
"answer": true
},
{
"point_num": 2,
"id": "has_multiple_inheritance",
"question": "Does any class in this file use multiple inheritance?",
"answer": ... | 3 | python/taskmda/mda/dmo/siblings_dict_generator.py | jiportilla/ontology |
from flask import Blueprint, render_template, session, redirect, url_for, request, flash
import sys
sys.path.append("../..")
import user_database as db
import views.posts.post_database as pdb
from auth import auth
from user import User
import app_settings
posts = Blueprint("posts", __name__, static_folder='static', template_folder='templates')
@posts.route('/create')
def create_post():
auth_status = auth()
post = request.args.get('p')
post_title = request.args.get('t')
for i in auth_status:
print(auth_status)
if post and auth_status[0]:
if not post_title:
post_title = 'Post'
pdb.add_post(post, post_title, auth_status[1].id)
flash('post created')
elif not post:
flash('You must write something for your post')
elif not auth_status[0]:
flash('You must be signed in to create a post, make sure you have cookies enabled')
return redirect(url_for('myprofile'))
@posts.route('/remove')
def delete_post():
auth_status = auth()
post_id = request.args.get('p')
if post_id:
pdb.remove_post(auth_status[1].id, post_id)
flash('post removed')
elif not post_id:
flash('Could not delete post')
elif not auth_status[0]:
flash('You must be signed in to delete a post, make sure you have cookies enabled')
return redirect(url_for('myprofile')) | [
{
"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 | views/posts/posts.py | samg11/slakr |
# -*- coding: utf-8 -*-
#
# michael a.g. aïvázis <michael.aivazis@para-sim.com>
# (c) 1998-2022 all rights reserved
# externals
import merlin
# declaration
class About(merlin.shells.command, family='merlin.cli.about'):
"""
Display information about this application
"""
@merlin.export(tip="print the copyright note")
def copyright(self, plexus, **kwds):
"""
Print the copyright note of the merlin package
"""
# show the copyright note
plexus.info.log(merlin.meta.copyright)
# all done
return
@merlin.export(tip="print out the acknowledgments")
def credits(self, plexus, **kwds):
"""
Print out the license and terms of use of the merlin package
"""
# make some space
plexus.info.log(merlin.meta.header)
# all done
return
@merlin.export(tip="print out the license and terms of use")
def license(self, plexus, **kwds):
"""
Print out the license and terms of use of the merlin package
"""
# make some space
plexus.info.log(merlin.meta.license)
# all done
return
@merlin.export(tip="print the version number")
def version(self, plexus, **kwds):
"""
Print the version of the merlin package
"""
# make some space
plexus.info.log(merlin.meta.header)
# all done
return
# end of file
| [
{
"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 | packages/merlin/cli/About.py | PyreFramework/pyre |
#!/usr/bin/python3
"""Student module.
Contains a Student class and some methods.
"""
class Student():
"""Defines a Student."""
def __init__(self, first_name, last_name, age):
"""Sets the necessary attributes for the Student object.
Args:
first_name (str): first name of the student.
last_name (str): last name of the student.
age (int): age of the student.
"""
self.first_name = first_name
self.last_name = last_name
self.age = age
def to_json(self, attrs=None):
"""Retrieves a dictionary representation of a Student instance."""
if attrs is not None:
return {k: v for k, v in self.__dict__.items() if k in attrs}
return self.__dict__
| [
{
"point_num": 1,
"id": "every_function_has_docstring",
"question": "Does every function in this file have a docstring?",
"answer": true
},
{
"point_num": 2,
"id": "all_params_annotated",
"question": "Does every function parameter in this file have a type annotation (excluding self/c... | 3 | 0x0B-python-input_output/10-student.py | malu17/alx-higher_level_programming |
import sys
import cro_mapper
import os
import unicodedata
import numpy as np
from scipy import misc
def _get_all_file_paths(path):
file_paths = []
for root, dirs, files in os.walk(path):
for file_ in files:
full_path = os.path.join(root, file_)
if os.path.isfile(full_path) and full_path.endswith(".png"):
file_paths.append(unicodedata.normalize('NFC', full_path))
return file_paths
def load_dataset(path):
print("Loading dataset at path:", path)
files = _get_all_file_paths(path)
X = []
y = []
for file in files:
image = misc.imread(file, mode='F')
X.append(image)
folder_path = os.path.dirname(file)
letter = os.path.basename(folder_path)
letter_int = cro_mapper.map_letter_to_int(letter)
y.append(letter_int)
return np.asarray(X), np.asarray(y)
| [
{
"point_num": 1,
"id": "every_function_under_20_lines",
"question": "Is every function in this file shorter than 20 lines?",
"answer": true
},
{
"point_num": 2,
"id": "every_function_has_docstring",
"question": "Does every function in this file have a docstring?",
"answer": fals... | 3 | source/clcd.py | fgulan/masters-seminar |
from rest_framework.generics import ListAPIView, RetrieveAPIView
from api.serializers import ChallengeSerializer
from challenges.models import Challenge
class ChallengeListAPIView(ListAPIView):
""" Lists all challenges. """
serializer_class = ChallengeSerializer
def get_queryset(self):
return Challenge.objects.all().filter(author=self.request.user)
class ChallengeRetrieveAPIView(RetrieveAPIView):
""" Retrieve specific challenge by id. """
serializer_class = ChallengeSerializer
def get_queryset(self):
return Challenge.objects.all().filter(author=self.request.user)
| [
{
"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 | gesund_projekt/api/views/challenges.py | asis2016/gesund-projekt |
from kay.utils import url_for
from kay_sitemap import Sitemap
from przepisy import VISIBILITY
from przepisy.models import Category, Recipe
class StaticSitemap(Sitemap):
changefreq = 'weekly'
def items(self):
items = [url_for('index/index', _external=True)]
for cat in Category.all().fetch(20):
items.append(cat.get_url(True))
return items
class RecipesSitemap(Sitemap):
changefreq = 'weekly'
def items(self):
return Recipe.all().filter('rec_vis =', VISIBILITY[2]).filter('disabled =', False).order('-created').fetch(200)
def lastmod(self, item):
return item.updated
| [
{
"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 | index/sitemaps.py | gluwer/przepisymm |
# This file is part of the Extra-P software (http://www.scalasca.org/software/extra-p)
#
# Copyright (c) 2020, Technical University of Darmstadt, Germany
#
# This software may be modified and distributed under the terms of a BSD-style license.
# See the LICENSE file in the base directory for details.
class RecoverableError(RuntimeError):
def __init__(self, *args: object) -> None:
super().__init__(*args)
class FileFormatError(RecoverableError):
NAME = 'File Format Error'
def __init__(self, *args: object) -> None:
super().__init__(*args)
class InvalidExperimentError(RecoverableError):
NAME = 'Invalid Experiment Error'
def __init__(self, *args: object) -> None:
super().__init__(*args)
class CancelProcessError(RecoverableError):
NAME = 'Canceled Process'
def __init__(self, *args: object) -> None:
super().__init__(*args)
| [
{
"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 | extrap/util/exceptions.py | arima0714/extrap |
class Calculator:
__result = 0
def __init__(self):
pass
def add(self, i: int):
self.__result = self.__result + i
def subtract(self, i: int):
self.__result = self.__result - i
def getResult(self):
return self.__result
| [
{
"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 | snippets/URL parameters/calculator.py | keremkoseoglu/Python-Library |
import ipaddress
from aiohttp import web
def register_routes(app: web.Application):
app.add_routes(
[
web.get("/echo", echo),
web.get("/endpoints", list_endpoints),
web.post("/endpoints", add_endpoints),
web.delete("/endpoints", delete_endpoints),
]
)
# GET /echo
async def echo(req):
remote_ip = req.remote
if ipaddress.ip_address(remote_ip).is_loopback:
remote_ip = req.app["config"]["ip"]
return web.json_response({**req.app["config"], "remote_ip": remote_ip})
# GET /endpoints
async def list_endpoints(req):
epm = req.app["endpoint_manager"]
return web.json_response(epm.query())
# POST /endpoints
async def add_endpoints(req):
epm = req.app["endpoint_manager"]
epm.add(await req.json())
return web.json_response({"msg": "ok"})
# DELETE /endpoints
async def delete_endpoints(req):
epm = req.app["endpoint_manager"]
payload = await req.json()
epm.remove(payload["addr"])
return web.json_response({"msg": "ok"})
| [
{
"point_num": 1,
"id": "no_function_exceeds_5_params",
"question": "Does every function in this file take 5 or fewer parameters (excluding self/cls)?",
"answer": true
},
{
"point_num": 2,
"id": "has_nested_function_def",
"question": "Does this file contain any function defined insid... | 3 | perwez/perwez/server/routes.py | sosp2021/Reth |
from django.core.urlresolvers import reverse
from django.conf import settings
from django.db import models
class List(models.Model):
owner = models.ForeignKey(settings.AUTH_USER_MODEL, blank=True, null=True)
shared_with = models.ManyToManyField(
settings.AUTH_USER_MODEL, related_name='shared_lists'
)
@property
def name(self):
return self.item_set.first().text
def get_absolute_url(self):
return reverse('view_list', args=[self.id])
@staticmethod
def create_new(first_item_text, owner=None):
list_ = List.objects.create(owner=owner)
Item.objects.create(text=first_item_text, list=list_)
return list_
class Item(models.Model):
text = models.TextField(default='')
list = models.ForeignKey(List, default=None)
class Meta:
ordering = ('id',)
unique_together = ('list', 'text')
def __str__(self):
return self.text
| [
{
"point_num": 1,
"id": "all_function_names_snake_case",
"question": "Are all function names in this file written in snake_case?",
"answer": true
},
{
"point_num": 2,
"id": "more_functions_than_classes",
"question": "Does this file define more functions than classes?",
"answer": ... | 3 | lists/models.py | danrneal/superlists |
import jieba
import jieba.posseg as pseg
def user_dict():
from sagas.conf import resource_path
dictf = resource_path('dict_zh.txt')
jieba.load_userdict(dictf)
seg_list = jieba.cut("列出所有的采购订单") # 默认是精确模式
print(", ".join(seg_list))
def user_words():
jieba.add_word('寄账单地址', tag='typ')
jieba.add_word('新建', tag='srv')
seg_list = jieba.cut("列出所有的寄账单地址") # 默认是精确模式
print(", ".join(seg_list))
words = pseg.cut("新建所有的寄账单地址")
for word, flag in words:
print('%s %s' % (word, flag))
if __name__ == '__main__':
user_dict()
| [
{
"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 | sagas/tests/langs/jieba_procs.py | samlet/stack |
"""Standardized service-level logger utils."""
import logging
from termcolor import colored
def configure_logger():
"""Configure the built-in root Python logger."""
logger = logging.getLogger()
handler = logging.StreamHandler()
formatter = logging.Formatter('%(asctime)s %(levelname)-8s %(message)s')
handler.setFormatter(formatter)
logger.addHandler(handler)
logger.setLevel(logging.INFO)
def format_error(type, message):
"""Format an error message with color."""
return colored(type + ': ', 'red', attrs=['bold']) + message
| [
{
"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 | services/common/python/logger.py | uavaustin/orchestra |
# -*- coding: utf-8 -*-
from .context import tatsumaki
from motor import MotorClient
from tatsumaki.base import Document
from tatsumaki.connection import connect, Connection
# Importing testing libraries for async tests
from tornado.testing import gen_test
from tornado.testing import AsyncTestCase
class DocumentTest(AsyncTestCase):
"""Test the Behaviour of document class"""
def setUp(self):
super(DocumentTest, self).setUp()
connect('mongodb://localhost:27017/test')
client = MotorClient("mongodb://localhost:27017/test")
class Hello(Document):
name = tatsumaki.StringType()
self.Modal = Hello
self.db = client['test']['Hello']
@gen_test
def test_save(self):
new_mod = self.Modal(id=2)
new_mod.name = "grey"
saved = yield new_mod.save()
ided = yield self.db.find_one({"_id": 2})
self.assertIsNotNone(ided)
self.assertEqual(saved, ided["_id"])
@gen_test
def test_remove(self):
new_mod = self.Modal(id=2)
yield new_mod.save()
yield new_mod.delete()
ided = yield self.db.find_one({"_id": 2})
self.assertIsNone(ided)
@gen_test
def test_find(self):
results = yield self.Modal.find({}, length=100)
self.assertIsNotNone(results)
result = results[0]
self.assertIsInstance(result, self.Modal)
def tearDown(self):
super(DocumentTest, self).tearDown()
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/test_base.py | plasmashadow/tatsumaki |
import getpass, platform, sys, threading
from .. util import log
from . control import ExtractedControl
# See https://stackoverflow.com/questions/42603000
DARWIN_ROOT_WARNING = """
In MacOS, pynput must to be running as root in order to get keystrokes.
Try running your program like this:
sudo %s <your commands here>
"""
INSTALL_ERROR = """
Please install the pynput library with
$ pip install pynput
"""
try:
import pynput
except ImportError:
pynput = Listener = None
else:
class Listener(pynput.keyboard.Listener):
def join(self, timeout=None):
# join() on pynput.keyboard.Listener waits on a queue...
self._queue.put(None)
return super().join(timeout)
def keyname(key):
return getattr(key, 'name', None) or getattr(key, 'char')
class Keyboard(ExtractedControl):
EXTRACTOR = {
'keys_by_type': {
'press': ['type', 'key'],
'release': ['type', 'key'],
},
'normalizers': {
'key': keyname,
},
}
def _press(self, key):
self.receive({'type': 'press', 'key': key})
def _release(self, key):
self.receive({'type': 'release', 'key': key})
def _make_thread(self):
if not pynput:
raise ValueError(INSTALL_ERROR)
if platform.platform().startswith('Darwin'):
if getpass.getuser() != 'root':
log.warning(DARWIN_ROOT_WARNING, sys.argv[0])
log.info('Starting to listen for keyboard input')
return Listener(self._press, self._release)
| [
{
"point_num": 1,
"id": "all_params_annotated",
"question": "Does every function parameter in this file have a type annotation (excluding self/cls)?",
"answer": false
},
{
"point_num": 2,
"id": "all_function_names_snake_case",
"question": "Are all function names in this file written ... | 3 | bibliopixel/control/keyboard.py | rec/leds |
def count_matches(s1, s2):
''' (str, str) -> int
Return the number of positions in s1 that contain the
same character at the corresponding position of s2.
Precondition: len(s1) == len(s2)
>>> count_matches('ate', 'ape')
2
>>> count_matches('head', 'hard')
2
'''
num_matches = 0
for i in range(len(s1)):
if s1[i] == s2[i]:
num_matches = num_matches + 1
return num_matches
def sum_items(list1, list2):
''' (list of number, list of number) -> list of number
Return a new list in which each item is the sum of the items at the
corresponding position of list1 and list2.
Precondition: len(list1) == len(list2)
>> sum_items([1, 2, 3], [2, 4, 2])
[3, 6, 5]
'''
sum_list = []
for i in range(len(list1)):
sum_list.append(list1[i] + list2[i])
return sum_list
| [
{
"point_num": 1,
"id": "has_nested_function_def",
"question": "Does this file contain any function defined inside another function?",
"answer": false
},
{
"point_num": 2,
"id": "all_params_annotated",
"question": "Does every function parameter in this file have a type annotation (ex... | 3 | University-of-Toronto-The Fundamentals/week6/parallel_list_str.py | Sam-Gao-Xin/Courses- |
import pytest
import os
from polyglotdb.io import inspect_maus
from polyglotdb import CorpusContext
from polyglotdb.exceptions import ParseError
def test_load_aus(maus_test_dir, graph_db):
with CorpusContext('test_mfa', **graph_db) as c:
c.reset()
testFilePath = os.path.join(maus_test_dir, "maus_test.TextGrid")
parser = inspect_maus(testFilePath)
print(parser.speaker_parser)
c.load(parser, testFilePath)
assert (c.hierarchy.has_type_property('word', 'transcription'))
q = c.query_graph(c.word).filter(c.word.label == 'JURASSIC')
print(q)
print(q.all())
q = q.filter(c.word.speaker.name == 'maus_test')
print(q.all())
q = q.order_by(c.word.begin)
print(q.all())
q = q.columns(c.word.label)
print(q.all())
results = q.all()
assert (len(results) == 1)
c.encode_pauses('<SIL>')
c.encode_utterances(min_pause_length=0)
q = c.query_graph(c.word).filter(c.word.label == 'PLANET')
q = q.filter(c.word.speaker.name == 'maus_test')
q = q.order_by(c.word.begin)
q = q.columns(c.word.label, c.word.following.label.column_name('following'))
results = q.all()
assert (len(results) == 1)
assert (results[0]['following'] == 'JURASSIC')
q = c.query_speakers().filter(c.speaker.name == 'maus_test')
q = q.columns(c.speaker.discourses.name.column_name('discourses'))
s = q.get()
assert (len(s['discourses']) == 1)
assert (s['discourses'] == ['maus_test'])
def test_mismatch_parser(timit_test_dir, graph_db):
with CorpusContext('test_mismatch', **graph_db) as c:
c.reset()
parser = inspect_maus(timit_test_dir)
with pytest.raises(ParseError):
c.load(parser, timit_test_dir)
| [
{
"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_params_annotated",
"question": "Does every function parameter in this file have a type annotation (excluding self/... | 3 | tests/test_io_maus.py | michaelhaaf/PolyglotDB |
import sqlite3
from my_config import DB_CONNECTION_STR
class SqliteUtil():
def __init__(self):
self.db_connection_str = DB_CONNECTION_STR
self.con = sqlite3.connect(self.db_connection_str, check_same_thread=False)
self.con.row_factory = sqlite3.Row
self.cursorObj = self.con.cursor()
def execute_sql(self, sql):
self.cursorObj.execute(sql)
self.con.commit()
def drop_table(self, table_name):
sql_drop = ("DROP TABLE IF EXISTS {}".format(table_name))
self.cursorObj.execute(sql_drop)
self.con.commit()
def get_all(self, table):
self.cursorObj.execute('SELECT * FROM {}'.format(table))
rows = self.cursorObj.fetchall()
rows_dict = [dict(row) for row in rows]
return rows_dict
def get_all_tables_name(self):
self.cursorObj.execute('SELECT name from sqlite_master where type= "table"')
all_tables = self.cursorObj.fetchall()
return all_tables
def count_all(self, table):
rowcount = self.cursorObj.execute('SELECT * FROM {}'.format(table)).rowcount
return rowcount
| [
{
"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 | sql_util.py | hoaipham97/togo |
# This is the object-based adapter pattern
# It allows us to take an outside class 'StrangeCreature' with a different interface,
# and squeeze that SOB into another hierachy.
# The good thing about the object version of this pattern is that if StrangeCreature had
# a lot of subtypes, we would not need to write an adapter for each subtype.
#(I don't think this is relevant considering Pythons Dynamic Typing, but it's good to know for something like C++ I'm guessing)
import abc
class StrangeCreature(object):
def make_horrible_noise(self):
print("Rawr")
class Animal(object, metaclass=abc.ABCMeta):
@abc.abstractmethod
def make_noise(self):
raise NotImplementedError
class Horse(Animal):
def make_noise(self):
print("Vrinsk")
class Platypus(Animal):
_strange_creature = None
def __init__(self):
self._strange_creature = StrangeCreature()
def make_noise(self):
return self._strange_creature.make_horrible_noise()
p = Platypus()
p.make_noise()
h = Horse()
h.make_noise() | [
{
"point_num": 1,
"id": "every_class_has_docstring",
"question": "Does every class in this file have a docstring?",
"answer": false
},
{
"point_num": 2,
"id": "all_function_names_snake_case",
"question": "Are all function names in this file written in snake_case?",
"answer": true... | 3 | Structural/object_adapter.py | TheVikingGent/DesignPatterns4Python |
# system imports
import os, json
basedir = os.path.abspath(os.path.dirname(__file__))
class Config:
"""
Class used to hold configurations that are used in both website and admin applications
"""
MONGO_HOST = "localhost"
MONGO_DBNAME = "panoptes"
THREADS_PER_PAGE = 8
mailcfg = json.load(open('mailcfg.json'))
MAIL_SERVER = mailcfg['MAIL_SERVER']
MAIL_PORT = mailcfg['MAIL_PORT']
MAIL_USE_TLS = mailcfg['MAIL_USE_TLS']
MAIL_USERNAME = mailcfg['MAIL_USERNAME']
MAIL_PASSWORD = mailcfg['MAIL_PASSWORD']
MAIL_ADDRESS = mailcfg['MAIL_ADDRESS']
PERMISSIONS = {'admin':3, 'manager':2, 'user':1}
SERVICE_TYPES = ["mongo","redis"]
SERVICES = [('/services/db/'+x,'services',x.title()) for x in SERVICE_TYPES]
SERVICES += [('/services/setari/lista','services','Settings')]
MENU = [('services.home','hardware','Hardware',''),('services.home','services','Software services',SERVICES),('services.home','hardware','App','')]
@staticmethod
def init_app(app):
pass
class DevConfig(Config):
"""
Class used to hold admin-specific configurations
"""
SECRET_KEY = 'hardtoguesstring'
DEBUG = True
ADMINS = json.load(open('admins.json'))
CSRF_ENABLED = False
CSRF_SESSION_KEY = "somethingimpossibletoguess"
class AdminConfig(Config):
"""
Class used to hold admin-specific configurations
"""
SECRET_KEY = 'hardtoguesstring'
DEBUG = False
ADMINS = json.load(open('admins.json'))
CSRF_ENABLED = True
CSRF_SESSION_KEY = "somethingimpossibletoguess"
config = {
'dev': DevConfig,
'admin':AdminConfig
}
| [
{
"point_num": 1,
"id": "every_class_has_docstring",
"question": "Does every class in this file have a docstring?",
"answer": true
},
{
"point_num": 2,
"id": "has_multiple_inheritance",
"question": "Does any class in this file use multiple inheritance?",
"answer": false
},
{
... | 3 | panoptes/webapp/config.py | lesingerouge/Panoptes |
"""A ApiController Module."""
from masonite.request import Request
from masonite.view import View
from masonite.controllers import Controller
class ApiController(Controller):
"""ApiController Controller Class."""
def __init__(self, request: Request):
"""ApiController Initializer
Arguments:
request {masonite.request.Request} -- The Masonite Request class.
"""
self.request = request
def show(self, view: View):
pass
| [
{
"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 | app/http/controllers/ApiController.py | krishotte/env_data2 |
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def rotateRight(self, head: ListNode, k: int) -> ListNode:
if not (head and head.next and k) :
return head
fast = head
cnt = 1
while fast.next:
fast = fast.next
cnt += 1
fast.next = head
slow = head
for i in range(cnt - k%cnt - 1):
slow = slow.next
second = slow.next
slow.next = None
return second
| [
{
"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 | 61. Rotate List.py | XinchaoGou/MyLeetCode |
import matplotlib.pyplot as plt
def plot_data(first_path, best_path, distances_plot_data, temperatures_plot_data):
first_path_xs = []
first_path_ys = []
for city in first_path:
first_path_xs.append(city[0])
first_path_ys.append(city[1])
first_path_xs.append(first_path_xs[0])
first_path_ys.append(first_path_ys[0])
best_path_xs = []
best_path_ys = []
for city in best_path:
best_path_xs.append(city[0])
best_path_ys.append(city[1])
best_path_xs.append(best_path_xs[0])
best_path_ys.append(best_path_ys[0])
temperatures_xs = temperatures_plot_data[0]
temperatures_ys = temperatures_plot_data[1]
distances_xs = distances_plot_data[0]
distances_ys = distances_plot_data[1]
f, axarr = plt.subplots(2, 2)
axarr[0, 0].plot(first_path_xs, first_path_ys, marker="o", markerfacecolor="red")
axarr[0, 0].set_title("Before annealing")
axarr[0, 1].plot(best_path_xs, best_path_ys, marker="o", markerfacecolor="red")
axarr[0, 1].set_title("After annealing")
axarr[1, 0].plot(temperatures_xs, temperatures_ys)
axarr[1, 0].set_title("Temperature")
axarr[1, 1].plot(distances_xs, distances_ys)
axarr[1, 1].set_title("Distance")
plt.show()
def plot_iterations_and_distances(iterations, distances):
plt.plot(iterations, distances)
plt.show()
| [
{
"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 | lab4_simulated_annealing/task_1/plotter.py | j-adamczyk/Numerical-Algorithms |
from marshmallow import fields
from .field_set import FieldSet, FieldSetSchema
class Destination(FieldSet):
def __init__(self,
address: str = None,
bytes: int = None,
domain: str = None,
ip: str = None,
mac: str = None,
packets: int = None,
port: int = None,
*args, **kwargs):
super().__init__(*args, **kwargs)
self.address = address
self.bytes = bytes
self.domain = domain
self.ip = ip
self.mac = mac
self.packets = packets
self.port = port
class DestinationSchema(FieldSetSchema):
address = fields.String()
bytes = fields.Integer()
domain = fields.String()
ip = fields.String()
mac = fields.String()
packets = fields.Integer()
port = fields.Integer()
| [
{
"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 | kubi_ecs_logger/models/fields/destination.py | kumina/kubi_ecs_logger |
""" ELBO """
import oneflow.experimental as flow
class ELBO(flow.nn.Module):
def __init__(self, generator, variational):
super(ELBO, self).__init__()
self.generator = generator
self.variational = variational
def log_joint(self, nodes):
log_joint_ = None
for n_name in nodes.keys():
try:
log_joint_ += nodes[n_name].log_prob()
except:
log_joint_ = nodes[n_name].log_prob()
return log_joint_
def forward(self, observed, reduce_mean=True):
nodes_q = self.variational(observed).nodes
_v_inputs = {k:v.tensor for k,v in nodes_q.items()}
_observed = {**_v_inputs, **observed}
nodes_p = self.generator(_observed).nodes
logpxz = self.log_joint(nodes_p)
logqz = self.log_joint(nodes_q)
if len(logqz.shape) > 0 and reduce_mean:
elbo = flow.mean(logpxz - logqz)
else:
elbo = logpxz - logqz
return -elbo
| [
{
"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 | zhusuan_of/variational/elbo.py | Oneflow-Inc/Zhusuan-Oneflow |
#!/usr/bin/env python3
import sys
# Functions
def sumup():
''' Iterative '''
numbers = []
for argument in sys.argv[1:]:
try:
numbers.append(int(argument))
except ValueError:
pass
print(f'The sum of {numbers} is {sum(numbers)}')
def sumup_fp():
''' Functional Programming '''
numbers = list(map(int, filter(str.isdigit, sys.argv[1:])))
print(f'The sum of {numbers} is {sum(numbers)}')
def sumup_lc():
''' List Comprehension '''
numbers = [int(arg) for arg in sys.argv[1:] if arg.isdigit()]
print(f'The sum of {numbers} is {sum(numbers)}')
# Main Execution
if __name__ == '__main__':
sumup()
| [
{
"point_num": 1,
"id": "every_function_under_20_lines",
"question": "Is every function in this file shorter than 20 lines?",
"answer": true
},
{
"point_num": 2,
"id": "every_function_has_docstring",
"question": "Does every function in this file have a docstring?",
"answer": true... | 3 | lecture09/sumup.py | nd-cse-20289-sp22/cse-20289-sp22-examples |
"""
GENERATED FILE - DO NOT EDIT (created via @build_stack_rules_proto//cmd/depsgen)
"""
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
def _maybe(repo_rule, name, **kwargs):
if name not in native.existing_rules():
repo_rule(name = name, **kwargs)
def prebuilt_protoc_deps():
prebuilt_protoc_linux() # via <TOP>
prebuilt_protoc_osx() # via <TOP>
prebuilt_protoc_windows() # via <TOP>
def prebuilt_protoc_linux():
_maybe(
http_archive,
name = "prebuilt_protoc_linux",
sha256 = "6003de742ea3fcf703cfec1cd4a3380fd143081a2eb0e559065563496af27807",
urls = [
"https://github.com/google/protobuf/releases/download/v3.6.1/protoc-3.6.1-linux-x86_64.zip",
],
build_file_content = """
filegroup(
name = "protoc",
srcs = ["bin/protoc"],
visibility = ["//visibility:public"],
)
""",
)
def prebuilt_protoc_osx():
_maybe(
http_archive,
name = "prebuilt_protoc_osx",
sha256 = "0decc6ce5beed07f8c20361ddeb5ac7666f09cf34572cca530e16814093f9c0c",
urls = [
"https://github.com/google/protobuf/releases/download/v3.6.1/protoc-3.6.1-osx-x86_64.zip",
],
build_file_content = """
filegroup(
name = "protoc",
srcs = ["bin/protoc"],
visibility = ["//visibility:public"],
)
""",
)
def prebuilt_protoc_windows():
_maybe(
http_archive,
name = "prebuilt_protoc_windows",
sha256 = "0decc6ce5beed07f8c20361ddeb5ac7666f09cf34572cca530e16814093f9c0c",
urls = [
"https://github.com/google/protobuf/releases/download/v3.6.1/protoc-3.6.1-win32.zip",
],
build_file_content = """
filegroup(
name = "protoc",
srcs = ["bin/protoc.exe"],
visibility = ["//visibility:public"],
)
""",
)
| [
{
"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 | deps/prebuilt_protoc_deps.bzl | heartless-clown/rules_proto |
from __future__ import print_function
from __future__ import division
from . import _C
import numpy as np
###################################################################################################################################################
def get_random_time_mesh(ti, tf, min_dt):
if tf<=ti:
return []
t0 = ti+np.random.uniform(0, min_dt)
new_times = []
while t0<tf:
new_times.append(t0)
t0 += min_dt
return new_times
def get_augmented_time_mesh(times, ti, tf, min_dt, extra_times,
dropout_p=0.0,
):
assert dropout_p>=0 and dropout_p<=1
assert tf>=ti
if tf==ti:
return [ti]
if tf-ti<min_dt:
return np.random.uniform(ti, tf, size=1)
new_times = [ti-min_dt]+[t for t in np.sort(times) if t>=ti and t<=tf]+[tf+min_dt]
possible_times = []
for i in range(0, len(new_times)-1):
ti_ = new_times[i]
tf_ = new_times[i+1]
assert tf_>=ti_
times_ = get_random_time_mesh(ti_+min_dt, tf_-min_dt, min_dt)
#print(ti_+min_dt, tf_-min_dt, times_)
possible_times += times_
possible_times = np.array(possible_times) if extra_times is None else np.random.permutation(possible_times)[:extra_times]
valid_indexs = np.random.uniform(size=len(possible_times))>=dropout_p
possible_times = possible_times[valid_indexs]
augmented_time_mesh = np.sort(np.concatenate([times, possible_times])) # sort
return augmented_time_mesh | [
{
"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 | synthsne/generators/time_meshs.py | opimentel-github/sne-lightcurves-synthetic |
# Copyright 2015 Jared Rodriguez (jared.rodriguez@rackspace.com)
# 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.
from mercury_agent.capabilities import capability
from mercury_agent.configuration import get_configuration
from mercury_agent.inspector import inspect
from mercury_agent.inspector.inspect import global_device_info
from mercury_agent.inspector.inspectors import health
@capability('inspector', description='Run inspector')
def inspector():
"""
Manually run inspectors
:return: results
"""
return inspect.inspect()
@capability('check_hardware', description='Check hardware for errors')
def check_hardware():
"""
Checks hardware for inconsistencies and defects. Returns a list of discovered critical errors.
:return:
"""
configuration = get_configuration().agent
errors = []
_health_data = health.system_health_inspector(global_device_info)
if _health_data['corrected_hardware_event_count'] >= configuration.hardware.mce_threshold:
errors.append(
'MCE count is {} which is above the configured threshold of {}'.format(
_health_data['corrected_hardware_event_count'],
configuration.hardware.mce_threshold))
return {
'errors': errors,
'error_count': len(errors)
}
| [
{
"point_num": 1,
"id": "every_function_under_20_lines",
"question": "Is every function in this file shorter than 20 lines?",
"answer": true
},
{
"point_num": 2,
"id": "every_function_has_docstring",
"question": "Does every function in this file have a docstring?",
"answer": true... | 3 | mercury_agent/procedures/inspector.py | jr0d/mercury-agent |
import asyncio
import base64
import threading
import cv2
import numpy as np
from flask_socketio import SocketIO, emit
from flask import Flask, render_template
import multiprocessing
class Streamer():
def __init__(self) -> None:
"""Constructor
"""
@staticmethod
async def stream_socket(
url_server: str,
app: 'Flask' = None,
socket_options: 'dict' = None,
socket_msg: 'str' = "mvfy_visual_img",
)-> 'function':
app = Flask(__name__) if app is None else app
socketio = SocketIO(app, **socket_options)
threading.Thread(target=lambda: socketio.run(url_server)).run()
async def wraper_function(img, extension: str = ".jpg", size: tuple = (1920, 1080)):
if size is not None:
frame = cv2.resize(img, size)
_, buffer = cv2.imencode(extension, frame, [cv2.IMWRITE_JPEG_QUALITY, 80])
data = base64.b64encode(buffer)
socketio.emit(socket_msg, {
"data": data
})
return wraper_function
@staticmethod
async def stream_local(
img: np.array,
size: tuple = (1920, 1080),
title: str = "title"
) -> None:
if size is not None:
img = cv2.resize(img, size)
cv2.imshow(title, img) | [
{
"point_num": 1,
"id": "more_functions_than_classes",
"question": "Does this file define more functions than classes?",
"answer": true
},
{
"point_num": 2,
"id": "has_nested_function_def",
"question": "Does this file contain any function defined inside another function?",
"answe... | 3 | mvfy/visual/utils/streamer.py | erwingforerocastro/mvfy_visual_py |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Date : Feb-09-21 22:23
# @Author : Kelly Hwong (dianhuangkan@gmail.com)
import numpy as np
import tensorflow as tf
class XOR_Dataset(tf.keras.utils.Sequence):
"""XOR_Dataset."""
def __init__(
self,
batch_size=1,
shuffle=False,
seed=42,
):
self.X = np.array([[0, 0], [0, 1], [1, 0], [1, 1]])
self.y = np.array([[0], [1], [1], [0]])
assert batch_size <= 4
self.batch_size = batch_size # one by one learning
self.index = self._set_index_array()
self.shuffle = shuffle
def __getitem__(self, batch_index):
"""Gets batch at batch_index `batch_index`.
Arguments:
batch_index: batch_index of the batch in the Sequence.
Returns:
batch_x, batch_y: a batch of sequence data.
"""
batch_size = self.batch_size
sample_index = \
self.index[batch_index * batch_size:(batch_index+1) * batch_size]
batch_x = np.empty((batch_size, 2))
batch_y = np.empty(batch_size)
for _, i in enumerate(sample_index):
batch_x[_, ] = self.X[i, :]
batch_y[_] = self.y[i, :]
return batch_x, batch_y
def __len__(self):
"""Number of batches in the Sequence.
Returns:
The number of batches in the Sequence.
"""
return int(np.ceil(self.index.shape[0] / self.batch_size))
def __iter__(self):
"""Create a generator that iterate over the Sequence."""
for item in (self[i] for i in range(len(self))):
yield item
def _set_index_array(self):
"""_set_index_array
"""
N = 4
return np.arange(0, N)
def main():
pass
if __name__ == "__main__":
main()
| [
{
"point_num": 1,
"id": "has_multiple_inheritance",
"question": "Does any class in this file use multiple inheritance?",
"answer": false
},
{
"point_num": 2,
"id": "every_function_has_docstring",
"question": "Does every function in this file have a docstring?",
"answer": false
... | 3 | xor_gate_nn/datasets/keras_fn/datasets.py | AI-Huang/XOR_Gate_NN |
class Side:
def __init__(self, border_style='SOLID', color='FF000000', width=1):
self._border_style = border_style
self._color = color
self._width = width
@property
def border_style(self):
return self._border_style.upper()
@property
def color(self):
return self._color
@property
def width(self):
return self._width
class Border:
def __init__(self, left=None, right=None, top=None, bottom=None):
# TODO: validate the sides ensuring Side class is used
self.left, self.right, self.top, self.bottom = left, right, top, bottom
| [
{
"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 | gspread2/styles/borders.py | futuereprojects/gspread2 |
from django.db import models
from pygments.lexers import get_all_lexers
from pygments.styles import get_all_styles
from pygments.lexers import get_lexer_by_name
from pygments.formatters.html import HtmlFormatter
from pygments import highlight
LEXERS = [item for item in get_all_lexers() if item[1]]
LANGUAGE_CHOICES = sorted([(item[1][0], item[0]) for item in LEXERS])
STYLE_CHOICES = sorted((item, item) for item in get_all_styles())
class Snippet(models.Model):
created = models.DateTimeField(auto_now_add=True)
title = models.CharField(max_length=100, blank=True, default='')
code = models.TextField()
linenos = models.BooleanField(default=False)
language = models.CharField(choices=LANGUAGE_CHOICES, default='python', max_length=100)
style = models.CharField(choices=STYLE_CHOICES, default='friendly', max_length=100)
owner = models.ForeignKey('auth.User', related_name='snippets', on_delete=models.CASCADE)
highlighted = models.TextField()
def save(self, *args, **kwargs):
"""
Use the `pygments` library to create a highlighted HTML
representation of the code snippet.
"""
lexer = get_lexer_by_name(self.language)
linenos = 'table' if self.linenos else False
options = {'title': self.title} if self.title else {}
formatter = HtmlFormatter(style=self.style, linenos=linenos,
full=True, **options)
self.highlighted = highlight(self.code, lexer, formatter)
super(Snippet, self).save(*args, **kwargs)
class Meta:
ordering = ('created',) | [
{
"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 | snippets/models.py | miritih/snippetsApi |
from django.db import models
from django.core.urlresolvers import reverse
from django.conf import settings
class List(models.Model):
owner = models.ForeignKey(settings.AUTH_USER_MODEL, blank=True, null=True)
def get_absolute_url(self):
return reverse('view_list', args=[self.id])
@property
def name(self):
return self.item_set.first().text
class Item(models.Model):
text = models.TextField(default='')
list = models.ForeignKey(List, default=None)
class Meta:
ordering = ('id',)
unique_together = ('list', 'text')
def __str__(self):
return self.text
| [
{
"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 | lists/models.py | bgroveben/TDDWithPython |
r"""Setup fixtures for testing :py:class:`lmp.model.LSTMModel`."""
import pytest
import torch
from lmp.model import LSTMModel
from lmp.tknzr import BaseTknzr
@pytest.fixture
def lstm_model(
tknzr: BaseTknzr,
d_emb: int,
d_hid: int,
n_hid_lyr: int,
n_pre_hid_lyr: int,
n_post_hid_lyr: int,
p_emb: float,
p_hid: float,
) -> LSTMModel:
r"""Example ``LSTMModel`` instance."""
return LSTMModel(
d_emb=d_emb,
d_hid=d_hid,
n_hid_lyr=n_hid_lyr,
n_pre_hid_lyr=n_pre_hid_lyr,
n_post_hid_lyr=n_post_hid_lyr,
p_emb=p_emb,
p_hid=p_hid,
tknzr=tknzr,
)
@pytest.fixture
def batch_prev_tkids(lstm_model: LSTMModel) -> torch.Tensor:
r"""Example input batch of token ids."""
# Shape: (2, 3).
return torch.randint(
low=0,
high=lstm_model.emb.num_embeddings,
size=(2, 3),
)
@pytest.fixture
def batch_next_tkids(
lstm_model: LSTMModel,
batch_prev_tkids: torch.Tensor,
) -> torch.Tensor:
r"""Example target batch of token ids."""
# Same shape as `batch_prev_tkids`.
return torch.cat(
[
batch_prev_tkids[..., :-1],
torch.randint(
low=0,
high=lstm_model.emb.num_embeddings,
size=(batch_prev_tkids.shape[0], 1),
),
],
dim=1,
)
| [
{
"point_num": 1,
"id": "every_function_under_20_lines",
"question": "Is every function in this file shorter than 20 lines?",
"answer": false
},
{
"point_num": 2,
"id": "no_function_exceeds_5_params",
"question": "Does every function in this file take 5 or fewer parameters (excluding... | 3 | test/lmp/model/_lstm/conftest.py | a868111817/language-model-playground |
import file_hasher as f
import unittest
import sys
import os
testdir = os.path.dirname(__file__)
srcdir = '../lib'
sys.path.insert(0, os.path.abspath(os.path.join(testdir, srcdir)))
class TestFileHasher(unittest.TestCase):
def setUp(self):
self.file_hasher = f.FileHasher("./test_file.txt", "sha1")
def test_file_hasher(self):
self.assertEqual(
self.file_hasher.hasher(),
"da39a3ee5e6b4b0d3255bfef95601890afd80709")
| [
{
"point_num": 1,
"id": "every_function_has_docstring",
"question": "Does every function in this file have a docstring?",
"answer": false
},
{
"point_num": 2,
"id": "more_functions_than_classes",
"question": "Does this file define more functions than classes?",
"answer": true
}... | 3 | hash_generator_cli/tests/test_file_hasher.py | clemdep/hash-generator-cli |
# -*- coding: utf-8 -*-
"""
CredentialsStoreInterface Interface
This class describes a shared interface for accessing user credentials
"""
# Builtins
import abc
# Internals
from conjur.data_object import CredentialsData, ConjurrcData
class CredentialsStoreInterface(metaclass=abc.ABCMeta): # pragma: no cover
"""
CredentialsStoreInterface
This class is an interface that outlines a shared interface for credential stores
"""
@abc.abstractmethod
def save(self, credential_data: CredentialsData):
"""
Method that writes user data to a credential store
"""
raise NotImplementedError()
@abc.abstractmethod
def load(self, conjurrc_conjur_url: str) -> CredentialsData:
"""
Method that loads credentials
"""
raise NotImplementedError()
@abc.abstractmethod
def update_api_key_entry(self, user_to_update: str,
credential_data: CredentialsData, new_api_key: str):
"""
Method to update the API key from the described entry
"""
raise NotImplementedError()
@abc.abstractmethod
def remove_credentials(self, conjurrc: ConjurrcData):
"""
Method to remove credentials from a store
"""
raise NotImplementedError()
@abc.abstractmethod
def is_exists(self, conjurrc_conjur_url: str) -> bool:
"""
Method to check if credentials exist in a store
"""
raise NotImplementedError()
@abc.abstractmethod
def cleanup_if_exists(self, conjurrc_conjur_url: str):
"""
Method to cleanup credential leftovers if exist.
For example, if a user delete item manually from the local pc keyring,
this function will make sure no leftovers left.
"""
raise NotImplementedError()
| [
{
"point_num": 1,
"id": "every_function_has_docstring",
"question": "Does every function in this file have a docstring?",
"answer": true
},
{
"point_num": 2,
"id": "all_params_annotated",
"question": "Does every function parameter in this file have a type annotation (excluding self/c... | 3 | conjur/interface/credentials_store_interface.py | jdumas/conjur-api-python3 |
import numpy as np
from tensorflow.keras import backend as K
def extract_image_patches(X, ksizes, strides,
padding='valid',
data_format='channels_first'):
raise NotImplementedError
def depth_to_space(input, scale, data_format=None):
raise NotImplementedError
def moments(x, axes, shift=None, keep_dims=False):
mean_batch = np.mean(x, axis=tuple(axes), keepdims=keep_dims)
var_batch = np.var(x, axis=tuple(axes), keepdims=keep_dims)
return mean_batch, var_batch
| [
{
"point_num": 1,
"id": "all_params_annotated",
"question": "Does every function parameter in this file have a type annotation (excluding self/cls)?",
"answer": false
},
{
"point_num": 2,
"id": "every_function_has_docstring",
"question": "Does every function in this file have a docst... | 3 | keras_contrib/backend/numpy_backend.py | HaemanthSP/keras-contrib |
from py4j.java_gateway import JavaGateway
from py4j.protocol import Py4JNetworkError
# TODO: ugly stuff! makes a copy of the array to separate result from Py4J (java gateway)
def pythonify(gateway_obj):
res_copy = []
for res in gateway_obj:
res_copy.append(res)
return res_copy
class PrismHandler:
def __init__(self):
self.gateway = JavaGateway()
self.prism_handler = self.gateway.entry_point.getPrismHandler()
def load_model_file(self, model_file, test=False):
if test:
real_path = '../test/' + model_file
else:
real_path = '../' + model_file
self.prism_handler.loadModelFile(real_path)
def check_bool_property(self, property_string):
result = self.prism_handler.checkBoolProperty(property_string)
return pythonify(result)
def check_quant_property(self, property_string):
result = self.prism_handler.checkQuantProperty(property_string)
return pythonify(result)
def synthesize_strategy(self, path, property_string):
strat = self.prism_handler.synthesizeStrategy(property_string)
# strat.exportToFile(path)
# strat.getNextMove(0)
# TODO: ugly, but works. fix later
strategy = {}
f = open('prismhandler/adv.tra', 'r')
for line in f:
split_line = line.split()
if len(split_line) == 2:
strategy[split_line[0]] = split_line[1]
return strategy
| [
{
"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 | prismhandler/prism_handler.py | KTH-RPL-Planiacs/least-limiting-advisers |
from random import randint
import pytest
from round_robin_generator.matchup_generation_circle import apply_offset
@pytest.mark.parametrize(
"p,expected", [(2, 7), (3, 8), (4, 2), (5, 3), (6, 4), (7, 5), (8, 6)]
)
def test_apply_offset(p, expected):
assert apply_offset(p, 8, 2) == expected
@pytest.mark.parametrize("p", range(1, 10))
def test_apply_offset__offset_0(p):
assert apply_offset(p, 10, 0) == p, "Should be idempotent on offset 0"
@pytest.mark.parametrize("n", range(1, 10))
def test_applyoffset__p_equals_1(n):
assert apply_offset(1, n, randint(1, n)) == 1, "1 should be fixed"
| [
{
"point_num": 1,
"id": "all_function_names_snake_case",
"question": "Are all function names in this file written in snake_case?",
"answer": true
},
{
"point_num": 2,
"id": "every_function_has_docstring",
"question": "Does every function in this file have a docstring?",
"answer":... | 3 | tests/test_generate_matchups.py | avadavat/round_robin_generator |
import json
from symro.src.automenu import Command
class SpecialCommand(Command):
def __init__(self,
symbol: str,
line_index: int = -1):
super(SpecialCommand, self).__init__()
self.symbol: str = symbol
self.line_index: int = line_index
def __str__(self) -> str:
arg_tokens = []
for arg in self.get_ordered_args():
arg_tokens.append(str(arg))
for name, value in self.get_named_args().items():
if isinstance(value, list) or isinstance(value, dict):
value = json.dumps(value)
arg_tokens.append("{0}={1}".format(name, value))
arg_str = ""
if len(arg_tokens) > 0:
arg_str = "(" + ", ".join(arg_tokens) + ")"
return "@{0}{1}".format(self.symbol, arg_str)
| [
{
"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/scripting/specialcommand.py | ari-bou/symro |
from typing import List
from celery import shared_task
from mipengine.node_tasks_DTOs import TableInfo
from mipengine.node.monetdb_interface import remote_tables
@shared_task
def get_remote_tables(context_id: str) -> List[str]:
"""
Parameters
----------
context_id : str
The id of the experiment
Returns
------
List[str]
A list of remote table names
"""
return remote_tables.get_remote_table_names(context_id)
@shared_task
def create_remote_table(table_info_json: str, monetdb_socket_address: str):
"""
Parameters
----------
table_info_json : str(TableInfo)
A TableInfo object in a jsonified format
monetdb_socket_address : str
The monetdb_socket_address of the monetdb that we want to create the remote table from.
"""
table_info = TableInfo.parse_raw(table_info_json)
remote_tables.create_remote_table(
table_info=table_info, monetdb_socket_address=monetdb_socket_address
)
| [
{
"point_num": 1,
"id": "every_function_under_20_lines",
"question": "Is every function in this file shorter than 20 lines?",
"answer": true
},
{
"point_num": 2,
"id": "all_params_annotated",
"question": "Does every function parameter in this file have a type annotation (excluding se... | 3 | mipengine/node/tasks/remote_tables.py | madgik/MIP-Engine |
# O(1) time | O(1) space - assuming a 9x9 input board
def solveSudoku(board):
solvePartialSudoku(0, 0, board)
return board
def solvePartialSudoku(row, col, board):
currentRow = row
currentCol = col
if currentCol == len(board[currentRow]):
currentRow += 1
currentCol = 0
if currentRow == len(board):
return True # board is completed
if board[currentRow][currentCol] == 0:
return tryDigitsAtPosition(currentRow, currentCol, board)
return solvePartialSudoku(currentRow, currentCol + 1, board)
def tryDigitsAtPosition(row, col, board):
for digit in range(1, 10):
if isValidAtPosition(digit, row, col, board):
board[row][col] = digit
if solvePartialSudoku(row, col + 1, board):
return True
board[row][col] = 0
return False
def isValidAtPosition(value, row, col, board):
rowIsValid = value not in board[row]
columnIsValid = value not in map(lambda r: r[col], board)
if not rowIsValid or not columnIsValid:
return False
# Check subgrid constraint.
subgridRowStart = (row // 3) * 3
subgridColStart = (col // 3) * 3
for rowIdx in range(3):
for colIdx in range(3):
rowToCheck = subgridRowStart + rowIdx
colToCheck = subgridColStart + colIdx
existingValue = board[rowToCheck][colToCheck]
if existingValue == value:
return False
return True | [
{
"point_num": 1,
"id": "every_function_under_20_lines",
"question": "Is every function in this file shorter than 20 lines?",
"answer": false
},
{
"point_num": 2,
"id": "has_nested_function_def",
"question": "Does this file contain any function defined inside another function?",
... | 3 | Recursion/Solve Sudoku/SolveSudoku.py | joydeepnandi/Algo |
import os
import logging
import pandas as pd
from pathlib import Path
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
DIR_PATH = Path(os.path.dirname(os.path.abspath(__file__)))
SINCE_PATH = DIR_PATH / Path('data/since.txt')
ARTICLES_PATH = DIR_PATH / Path('data/articles.csv')
def record_data_pull_time(timestamp):
with open(SINCE_PATH, 'a+') as f:
f.write('{}\n'.format(timestamp))
def read_times_api_queried():
try:
with open(SINCE_PATH, 'r+') as f:
sinces = f.readlines()
return [s.split('\n')[0] for s in sinces]
except FileNotFoundError:
return []
def get_most_recent_since():
sinces = read_times_api_queried()
if len(sinces) == 0:
return None
return sinces[-1]
def save_articles(articles):
if articles is None:
logger.info(f'no new articles found.')
return
logger.info(f'saving {len(articles)} articles.')
try:
articles_prev = pd.read_csv(ARTICLES_PATH)
articles = pd.concat([articles_prev, articles])
articles_deduped = articles.drop_duplicates(subset=['resolved_id'])
articles_deduped.to_csv(ARTICLES_PATH, index=False, encoding='utf8')
except FileNotFoundError:
articles.to_csv(ARTICLES_PATH, index=False, encoding='utf8')
| [
{
"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 | storage.py | cgrinaldi/pocket_analytics |
from vulnman.api.viewsets import ProjectRelatedObjectViewSet
from api.v1 import generics
from api.v1.serializers import vulnerability as serializers
from api.v1.serializers.proofs import ImageProofSerializer, TextProofSerializer
from apps.findings import models
class AgentVulnerabilityViewSet(generics.AgentModelViewSet):
queryset = models.Vulnerability.objects.all()
search_fields = ["name", "template__vulnerability_id"]
serializer_class = serializers.VulnerabilitySerializer
class AgentTextProofViewSet(generics.AgentModelViewSet):
queryset = models.TextProof.objects.all()
search_fields = ["name", "description", "text"]
serializer_class = serializers.TextProofSerializer
class ProofViewSet(ProjectRelatedObjectViewSet):
# TODO: improve this one
# Used to drag&drop reorder proofs in UI
def get_queryset(self):
if models.TextProof.objects.filter(pk=self.kwargs.get("pk")).exists():
return models.TextProof.objects.filter(pk=self.kwargs.get("pk"))
return models.ImageProof.objects.filter(pk=self.kwargs.get("pk"))
def get_serializer_class(self):
if models.TextProof.objects.filter(pk=self.kwargs.get("pk")).exists():
return TextProofSerializer
return ImageProofSerializer
| [
{
"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 | api/v1/viewsets/vulnerability.py | vulnman/vulnman |
import json
class Timeout(Exception):
"""
Used when a timeout occurs.
"""
pass
class HTTPException(Exception):
def __init__(self, response, *args, **kwargs):
try:
errors = json.loads(response.content.decode('utf8'))['errors']
message = '\n'.join([error['message'] for error in errors])
except Exception:
if hasattr(response, 'status_code') and response.status_code == 401:
message = response.content.decode('utf8')
else:
message = response
super(HTTPException, self).__init__(message, *args, **kwargs)
class HTTPBadRequest(HTTPException):
"""Generic >= 400 error
"""
pass
class HTTPUnauthorized(HTTPException):
"""401
"""
pass
class HTTPForbidden(HTTPException):
"""403
"""
pass
class HTTPNotFound(HTTPException):
"""404
"""
pass
class HTTPConflict(HTTPException):
"""409 - returned when creating conflicting resources
"""
pass
class HTTPTooManyRequests(HTTPException):
"""429 - returned when exceeding rate limits
"""
pass
class HTTPServerError(HTTPException):
"""Generic >= 500 error
"""
pass
def detect_and_raise_error(response):
if response.status_code == 401:
raise HTTPUnauthorized(response)
elif response.status_code == 403:
raise HTTPForbidden(response)
elif response.status_code == 404:
raise HTTPNotFound(response)
elif response.status_code == 409:
raise HTTPConflict(response)
elif response.status_code == 429:
exc = HTTPTooManyRequests(response)
exc.retry_after_secs = int(response.headers['Retry-After'])
raise exc
elif response.status_code >= 500:
raise HTTPServerError(response)
elif response.status_code >= 400:
raise HTTPBadRequest(response)
| [
{
"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 | oura/exceptions.py | kevingoldsmith/python-ouraring |
"""empty message
Revision ID: 455970924ed2
Revises: ab6b56596f03
Create Date: 2021-05-28 18:10:58.753066
"""
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import postgresql
# revision identifiers, used by Alembic.
revision = '455970924ed2'
down_revision = 'ab6b56596f03'
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.add_column('shows', sa.Column('start_datetime', sa.DateTime(), nullable=False))
op.drop_column('shows', 'start_time')
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.add_column('shows', sa.Column('start_time', postgresql.TIME(), autoincrement=False, nullable=False))
op.drop_column('shows', 'start_datetime')
# ### 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": "all_return_types_annotated",
"question": "Does every function in this file have a return type annotation?",
"answe... | 3 | migrations/versions/455970924ed2_.py | mattj241/Fyyur |
def validateSubSequence(array, sequence):
"""
### Description
validateSubSequence -> validates if a sequence of elements is a subsequence of a list.
### Parameters
- array: the list where it will validate the subsequence.
- sequence: the potential subsequence of elements
### Returns
- True when the sequence is a valid subsequence of array.
- False when the sequence is not a valid subsequence of array.
"""
arrIdx = 0
seqIdx = 0
while arrIdx < len(array) and seqIdx < len(sequence):
if array[arrIdx] == sequence[seqIdx]:
seqIdx += 1
arrIdx += 1
return seqIdx == len(sequence)
def validateSubSequenceFor(array, sequence):
"""
### Description
validateSubSequence -> validates if a sequence of elements is a subsequence of a list.
### Parameters
array: the list where it will validate the subsequence.
sequence: the potential subsequence of elements
### Returns
- True when the sequence is a valid subsequence of array.
- False when the sequence is not a valid subsequence of array.
"""
seqIdx = 0
for element in array:
if seqIdx == len(sequence):
break
if element == sequence[seqIdx]:
seqIdx += 1
return seqIdx == len(sequence)
if __name__ == "__main__":
print(validateSubSequence([5, 1, 22, 25, 6, -1, 8, 10], [1, 6, -1, 10]))
print(validateSubSequenceFor([5, 1, 22, 25, 6, -1, 8, 10], [1, 6, -1, 10])) | [
{
"point_num": 1,
"id": "all_params_annotated",
"question": "Does every function parameter in this file have a type annotation (excluding self/cls)?",
"answer": false
},
{
"point_num": 2,
"id": "every_function_has_docstring",
"question": "Does every function in this file have a docst... | 3 | valid_subsequence.py | GerardCod/algoexpert-python |
# EG11-02 Stock Item class failed
class StockItem(object):
'''
Stock item for the fashion shop
'''
def __init__(self, stock_ref, price, color):
self.stock_ref = stock_ref
self.__price = price
self.__stock_level = 0
self.color = color
@property
def price(self):
return self.__price
@property
def stock_level(self):
return self.__stock_level
class Dress(StockItem):
def __init__(self, stock_ref, price, color, pattern, size):
self.item_name = 'Dress'
self.pattern = pattern
self.size = size
x = Dress(stock_ref='D01', price=100, color='red', pattern='swirly', size=12)
print(x.pattern)
print(x.price)
| [
{
"point_num": 1,
"id": "more_functions_than_classes",
"question": "Does this file define more functions than classes?",
"answer": true
},
{
"point_num": 2,
"id": "every_class_has_docstring",
"question": "Does every class in this file have a docstring?",
"answer": false
},
{
... | 3 | chapter11/02 Stock Item class failed.py | munnep/begin_to_code_with_python |
#!/usr/bin/env python
import requests
import json
import logging
logger = logging.getLogger(__name__)
class TuLing():
def __init__(self):
self.__key__ = '2f1446eb0321804291b0a1e217c25bb5'
self.__appid__ = 137762
def __build_req_url(self, content):
return 'http://www.tuling123.com/openapi/api?key=%s&info=%s&userid=%s' % (
self.__key__, content, self.__appid__)
def UserAgent(self, url):
rsp = requests.get(url)
return rsp.content
def getdata(self, content):
try:
requrl = self.__build_req_url(content)
res = self.UserAgent(requrl).decode('utf-8')
jsons = json.loads(res, encoding='utf-8')
if str(jsons["code"]) == '100000':
return jsons["text"]
except Exception as e:
logger.error(e)
return "К сожалению, что-то пошло не так."
| [
{
"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 | servermanager/Api/commonapi.py | mtuktarov/mtuktarov.com |
# -*- coding: utf-8 -*-
import binascii
import hashlib
import hmac
from urllib.parse import quote
def mk_soucrce(method, url_path, params):
str_params = quote("&".join(k + "=" + str(params[k]) for k in sorted(params.keys())), '')
source = '%s&%s&%s' % (
method.upper(),
quote(url_path, ''),
str_params
)
return source
def hmac_sha1_sig(method, url_path, params, secret):
source = mk_soucrce(method, url_path, params)
print('source:%s' % source)
secret_bytes = bytes(secret, 'latin-1')
source_bytes = bytes(source, 'latin-1')
hashed = hmac.new(secret_bytes, source_bytes, hashlib.sha1)
return binascii.b2a_base64(hashed.digest())[:-1]
| [
{
"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 | python/sign.py | unbiased-tech/sdk |
class Trainer():
def __init__(self, name):
self.name = name
self.pokemon = []
def add_pokemon(self, pokemon):
if pokemon not in self.pokemon:
self.pokemon.append(pokemon)
return f'Caught {pokemon.name} with health {pokemon.health}'
return f'This pokemon is already caught'
def release_pokemon(self, pokemon_name):
for pokemon in self.pokemon:
if pokemon_name == pokemon.name:
self.pokemon.remove(pokemon)
return f'You have released {pokemon_name}'
return f'Pokemon is not caught'
def trainer_data(self):
result=f"Pokemon Trainer {self.name}\nPokemon count {len(self.pokemon)}\n"
for pokemon_obj in self.pokemon:
result+=f"- {pokemon_obj.pokemon_details()}\n"
return result | [
{
"point_num": 1,
"id": "has_multiple_inheritance",
"question": "Does any class in this file use multiple inheritance?",
"answer": false
},
{
"point_num": 2,
"id": "no_function_exceeds_5_params",
"question": "Does every function in this file take 5 or fewer parameters (excluding self... | 3 | defining_classes/pokemon_battle/trainer.py | PetkoAndreev/Python-OOP |
import sqlite3
from flask import Flask, jsonify, request
app = Flask(__name__)
app.debug = True
api_key = "RANDOM ACCESS KEY HERE"
def CheckAPIKey(key):
if key == api_key:
return True
else:
return False
@app.route('/')
def HomeDir():
return jsonify({'msg': "invalid_endpoint"})
@app.route('/api/v1/hwid')
def HwidDir():
db = sqlite3.connect('auth.db')
c = db.cursor()
opt = request.args.get('type')
hwid = request.args.get('hwid')
key = request.args.get('apikey')
if opt == 'add':
two_step = CheckAPIKey(key)
if two_step == True:
c.execute(f'INSERT INTO hwids VALUES ("{hwid}")')
db.commit()
return jsonify({'msg': "success"})
if two_step == False:
return jsonify({'msg': "invalid_apikey"})
if opt == 'check':
c.execute(f"SELECT * FROM hwids WHERE hwid='{hwid}'")
if hwid in str(c.fetchall()):
return jsonify({'msg': "success"})
else:
return jsonify({'msg': "invalid_hwid"})
else:
return jsonify({'msg': "invalid_type"})
if __name__ == "__main__":
app.run() | [
{
"point_num": 1,
"id": "every_function_has_docstring",
"question": "Does every function in this file have a docstring?",
"answer": false
},
{
"point_num": 2,
"id": "any_function_over_40_lines",
"question": "Is any function in this file longer than 40 lines?",
"answer": false
}... | 3 | Flask Server.py | Dropout1337/HWID-Authentication-API |
import os
from fitnick.base.base import introspect_tokens
def refresh_authorized_client():
import requests
with requests.session() as session:
with open('fitnick/base/fitbit_refresh_token.txt', 'r') as f:
refresh_token = f.read().strip()
with open('fitnick/base/fitbit_refresh_token_old.txt', 'w') as f:
# write the old token to file, just in case..
f.write(refresh_token)
data = {
'grant_type': 'refresh_token',
'refresh_token': refresh_token,
'expires_in': 31536000 # 12 hours
}
r = session.post(
url='https://api.fitbit.com/oauth2/token',
data=data,
headers={
'clientId': '22BWR3',
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': f"Basic {os.environ['FITBIT_AUTH_HEADER']}"}
)
try:
os.environ['FITBIT_ACCESS_KEY'] = r.json()['access_token']
os.environ['FITBIT_REFRESH_TOKEN'] = r.json()['refresh_token']
with open('fitnick/base/fitbit_access_key.txt', 'w') as f:
f.write(r.json()['access_token'])
with open('fitnick/base/fitbit_refresh_token.txt', 'w') as f:
f.write(r.json()['refresh_token'])
except KeyError:
print('ERROR: {}', r.json())
print(r.json())
return
def auto_refresh():
access_token_valid, refresh_token_valid = introspect_tokens()
if not access_token_valid:
if refresh_token_valid:
refresh_authorized_client()
else:
print('access token valid')
def main():
auto_refresh()
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": "all_function_names_snake_case",
"question": "Are all function names in this file written in snake_case?",
"answer"... | 3 | refresh_token.py | kcinnick/fitnick |
from durable.lang import *
with ruleset('replacetoken'):
# antecedent
@when_all(count(1), m.word.imatches(".*today.*"))
def match_today(c):
c.s.replace_str = "today"
c.s.replace_with = datetime.datetime.now().strftime('%d:%m:%Y')
# consequent
print('Hello {0}'.format(c.m.word))
@when_all(+m.paragraph)
def replace_op(c):
print('Hello {0}'.format(c.m.paragraph))
# on ruleset start
@when_start
def start(host):
host.post('replacetoken', { 'word': 'world', 'paragraph':'Hello world in rules', })
run_all()
| [
{
"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 | testpy/xpms_dynamic.py | prade/rules-debug |
import subprocess
import time
from selenium.webdriver import Chrome
import pywebio
import template
import util
from pywebio.input import *
from pywebio.platform.flask import start_server
from pywebio.utils import to_coroutine
async def target():
template.basic_output()
await template.coro_background_output()
await to_coroutine(template.basic_input())
await actions(buttons=['Continue'])
await template.flask_coro_background_input()
def test(server_proc: subprocess.Popen, browser: Chrome):
template.test_output(browser)
time.sleep(1)
template.test_input(browser)
time.sleep(1)
template.save_output(browser, '6.flask_coroutine.html')
def start_test_server():
pywebio.enable_debug()
start_server(target, port=8080, host='127.0.0.1', cdn=False)
if __name__ == '__main__':
util.run_test(start_test_server, test, address='http://localhost:8080?_pywebio_debug=1&_pywebio_http_pull_interval=400')
| [
{
"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 | test/6.flask_coroutine.py | Floboy/PyWebIO |
# -*- coding: utf-8 -*-
"""
Tencent is pleased to support the open source community by making 蓝鲸智云PaaS平台社区版 (BlueKing PaaS Community
Edition) available.
Copyright (C) 2017-2020 THL A29 Limited, a Tencent company. All rights reserved.
Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://opensource.org/licenses/MIT
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 django.utils import timezone
class Stack(list):
def top(self):
return self[len(self) - 1]
def push(self, item):
self.append(item)
class ConstantDict(dict):
"""ConstantDict is a subclass of :class:`dict`, implementing __setitem__
method to avoid item assignment::
>>> d = ConstantDict({'key': 'value'})
>>> d['key'] = 'value'
Traceback (most recent call last):
...
TypeError: 'ConstantDict' object does not support item assignment
"""
def __setitem__(self, key, value):
raise TypeError("'%s' object does not support item assignment" % self.__class__.__name__)
def calculate_elapsed_time(started_time, archived_time):
"""
@summary: 计算节点耗时
@param started_time: 执行开始时间
@param archived_time: 执行结束时间
@return:
"""
if archived_time and started_time:
elapsed_time = (archived_time - started_time).total_seconds()
elif started_time:
elapsed_time = (timezone.now() - started_time).total_seconds()
else:
elapsed_time = 0
return round(elapsed_time)
class ActionResult(object):
def __init__(self, result, message, extra=None):
self.result = result
self.message = message
self.extra = extra
| [
{
"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_class_has_docstring",
"question": "Does every class in this file have a docstring?",
"answer": ... | 3 | pipeline/engine/utils.py | springborland/bk-sops |
import json
import os
import re
from typing import Any
from ikea_api.endpoints import Cart, OrderCapture
token = os.environ["TOKEN"]
payloads = {
"add_items": {"90428328": 1},
"update_items": {"90428328": 5},
"remove_items": ["90428328"],
}
class_args = {"OrderCapture": ("101000")}
functions_to_skip = ["_error_handler", "copy_items", "set_coupon"]
def save_json(r: Any, *args: Any, **kwargs: Any):
directory = "response_examples"
try:
os.mkdir(directory)
except FileExistsError:
pass
module = re.findall(r".([^.]+$)", r.__module__)[0]
try:
os.mkdir(os.path.join(directory, module))
except FileExistsError:
pass
path = os.path.join(directory, module, r.__name__ + ".json")
res: Any = r(*args, **kwargs)
with open(path, "a+") as f:
f.seek(0)
f.truncate()
j = json.dumps(res).encode().decode("unicode-escape")
f.write(j)
def save_responses_for_class(cl: Any, token: str):
for s in cl.__dict__:
if cl.__name__ in class_args:
cur_cl = cl(token, class_args[cl.__name__])
else:
cur_cl = cl(token)
if not re.match(r"_", s) and s not in functions_to_skip:
f = getattr(cur_cl, s)
if s in payloads:
save_json(f, payloads[s])
else:
save_json(f)
def main():
Cart(token).add_items(payloads["add_items"])
for cl in OrderCapture, Cart:
save_responses_for_class(cl, token)
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": true
},
{
"point_num": 2,
"id": "all_params_annotated",
"question": "Does every function parameter in this file have a type annotation (excluding se... | 3 | response_examples/update_response_examples.py | sqr/ikea-api-client |
from tkinter import *
from tkinter import ttk
class MainTkinter:
def __init__(self, master):
master.title('Play Game')
master.config(relief = RIDGE)
frame = ttk.Frame(master)
frame.config(padding = (30, 15))
frame.pack()
playButton = ttk.Frame(master)
playButton.config(padding = (30, 15))
playButton.pack()
player1 = ttk.Label(frame, text = "Player 1", padding = (30, 15)).grid(row = 0, column = 0)
player2 = ttk.Label(frame, text = "Player 2", padding = (30, 15)).grid(row = 0, column = 1)
players = ['Human', 'MCTS', 'MiniMax', 'Bot']
for i in range(len(players)):
ttk.Button(frame, text = players[i]).grid(row = i+1, column = 0)
ttk.Button(frame, text = players[i]).grid(row = i+1, column = 1)
ttk.Button(frame, text = '3x3').grid(row = len(players)+1, column = 0)
ttk.Button(frame, text = '10x10').grid(row = len(players)+1, column = 1)
ttk.Button(playButton, text = 'PLAY').grid()
def main():
root = Tk()
app = MainTkinter(root)
root.mainloop()
if __name__ == "__main__": main()
| [
{
"point_num": 1,
"id": "more_functions_than_classes",
"question": "Does this file define more functions than classes?",
"answer": true
},
{
"point_num": 2,
"id": "has_multiple_inheritance",
"question": "Does any class in this file use multiple inheritance?",
"answer": false
},... | 3 | src/MainTkinter.py | nugusha/Tic-Tac-Toe |
"""Support for Pocket Casts."""
from datetime import timedelta
import logging
from pycketcasts import pocketcasts
import voluptuous as vol
from homeassistant.components.sensor import PLATFORM_SCHEMA, SensorEntity
from homeassistant.const import CONF_PASSWORD, CONF_USERNAME
import homeassistant.helpers.config_validation as cv
_LOGGER = logging.getLogger(__name__)
ICON = "mdi:rss"
SENSOR_NAME = "Pocketcasts unlistened episodes"
SCAN_INTERVAL = timedelta(minutes=5)
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
{vol.Required(CONF_PASSWORD): cv.string, vol.Required(CONF_USERNAME): cv.string}
)
def setup_platform(hass, config, add_entities, discovery_info=None):
"""Set up the pocketcasts platform for sensors."""
username = config.get(CONF_USERNAME)
password = config.get(CONF_PASSWORD)
try:
api = pocketcasts.PocketCast(email=username, password=password)
_LOGGER.debug("Found %d podcasts", len(api.subscriptions))
add_entities([PocketCastsSensor(api)], True)
except OSError as err:
_LOGGER.error("Connection to server failed: %s", err)
return False
class PocketCastsSensor(SensorEntity):
"""Representation of a pocket casts sensor."""
def __init__(self, api):
"""Initialize the sensor."""
self._api = api
self._state = None
@property
def name(self):
"""Return the name of the sensor."""
return SENSOR_NAME
@property
def native_value(self):
"""Return the sensor state."""
return self._state
@property
def icon(self):
"""Return the icon for the sensor."""
return ICON
def update(self):
"""Update sensor values."""
try:
self._state = len(self._api.new_releases)
_LOGGER.debug("Found %d new episodes", self._state)
except OSError as err:
_LOGGER.warning("Failed to contact server: %s", err)
| [
{
"point_num": 1,
"id": "more_functions_than_classes",
"question": "Does this file define more functions than classes?",
"answer": true
},
{
"point_num": 2,
"id": "all_params_annotated",
"question": "Does every function parameter in this file have a type annotation (excluding self/cl... | 3 | homeassistant/components/pocketcasts/sensor.py | learn-home-automation/core |
def print_line(numbers):
line = ""
for i in numbers:
line = line + str(i) + "\t"
print(line)
def grade_school_multiplication_table(n=3):
for i in range(1, n+1):
numbers = list(range(1*i, (n+1)*i,i))
#print(numbers)
print_line(numbers)
# range(start,end,increment)
str_N = input("please enter a number for grade school multiplication table")
N = int(str_N)
#N = 10
grade_school_multiplication_table(N)
| [
{
"point_num": 1,
"id": "every_function_has_docstring",
"question": "Does every function in this file have a docstring?",
"answer": false
},
{
"point_num": 2,
"id": "any_function_over_40_lines",
"question": "Is any function in this file longer than 40 lines?",
"answer": false
}... | 3 | 2021/lab-solutions-2021-10-29/grade_school_multiplication_table.py | ati-ozgur/course-python |
from django.views.generic.edit import UpdateView
from django.urls import reverse_lazy
from django.utils.decorators import method_decorator
from django.contrib.auth.decorators import login_required
from user.models import User
from user.forms import UpdateUserForm
class EditProfileView(UpdateView):
model = User
form_class = UpdateUserForm
template_name = 'edit_health_professional.html'
@method_decorator(login_required)
def dispatch(self, *args, **kwargs):
return super(EditProfileView, self).dispatch(*args, **kwargs)
def get_object(self):
return self.request.user
def get_context_data(self, **kwargs):
context = super(EditProfileView, self).get_context_data(**kwargs)
is_health_professional = hasattr(self.request.user, 'healthprofessional')
if is_health_professional:
template = "dashboardHealthProfessional/template.html"
else:
template = "dashboardPatient/template.html"
context['template'] = template
return context
def get_success_url(self):
return reverse_lazy('edit_profile') | [
{
"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 | medical_prescription/user/views/editprofile.py | ristovao/2017.2-Receituario-Medico |
from jadi import interface
class Package(object):
def __init__(self, manager):
self.manager = manager
self.id = None
self.name = None
self.version = None
self.description = None
self.is_installed = None
self.is_upgradeable = None
self.installed_version = None
@interface
class PackageManager(object):
id = None
name = None
update_command = None
def __init__(self, context):
self.context = context
def list(self, query=None):
raise NotImplementedError
def get_package(self, _id):
raise NotImplementedError
def update_lists(self, progress_callback):
raise NotImplementedError
def get_apply_cmd(self, selection):
raise NotImplementedError
| [
{
"point_num": 1,
"id": "every_class_has_docstring",
"question": "Does every class 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 self/cls)... | 3 | plugins/packages/api.py | lllanos/InfraDocker_Ajenti |
# -*- coding: utf-8 -*-
"""
Created on Mon Feb 18 02:43:27 2019
@author: z
"""
import numpy as np
import scipy.stats as ss
import matplotlib.pyplot as plt
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
h = 1
sd = 1
n = 50
n_n = 1000
def gen_data(n, h, sd1, sd2):
""" xxx """
x1 = ss.norm.rvs(-h, sd1, n)
y1 = ss.norm.rvs(0, sd1, n)
x2 = ss.norm.rvs(h, sd2, n)
y2 = ss.norm.rvs(0, sd2, n)
return (x1, y1, x2, y2)
def plot_data(x1, y1, x2, y2):
plt.figure()
plt.plot(x1, y1, "o", ms=2)
plt.plot(x2, y2, "o", ms=2)
plt.xlabel("$X_1$")
plt.ylabel("$X_2$")
def plot_probs(ax, clf, class_no):
xx1, xx2 = np.meshgrid(np.arange(-5, 5, 0.1), np.arange(-5, 5, 0.1))
probs = clf.predict_proba(np.stack((xx1.ravel(), xx2.ravel()), axis=1))
Z = probs[:,class_no]
Z = Z.reshape(xx1.shape)
CS = ax.contourf(xx1, xx2, Z)
cbar = plt.colorbar(CS)
plt.xlabel("$X_1$")
plt.ylabel("$X_2$")
(x1, y1, x2, y2) = gen_data(n_n, 1.5, 1, 1.5)
X = np.vstack((np.vstack((x1,y1)).T, np.vstack((x2,y2)).T))
y = np.hstack((np.repeat(1, n_n), np.repeat(2, n_n)))
X_train, X_test, y_train, y_test = train_test_split(X, y, train_size=0.5, random_state=1)
clf = LogisticRegression()
clf.fit(X_train, y_train)
print("测试数据:",clf.score(X_test, y_test))
print("单点分类概率:",clf.predict_proba(np.array([-2, 0]).reshape(1, -1)));
print("单点分类:",clf.predict(np.array([-2, 0]).reshape(1, -1)));
plt.figure(figsize=(5,8))
ax = plt.subplot(211)
plot_probs(ax, clf, 0)
plt.title("Pred. prob for class 1")
ax = plt.subplot(212)
plot_probs(ax, clf, 1)
plt.title("Pred. prob for class 2");
plot_data(x1, y1, x2, y2)
| [
{
"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 | Python/Courese/Linear Regression/Logistic Regression.py | linghtiin/test |
from fractions import Fraction
def left_rect(f,x,h):
return f(x)
def mid_rect(f,x,h):
return f(x + h/2)
def right_rect(f,x,h):
return f(x+h)
def trapezium(f,x,h):
return (f(x) + f(x+h))/2.0
def simpson(f,x,h):
return (f(x) + 4*f(x + h/2) + f(x+h))/6.0
def cube(x):
return x*x*x
def reciprocal(x):
return 1/x
def identity(x):
return x
def integrate( f, a, b, steps, meth):
h = (b-a)/steps
ival = h * sum(meth(f, a+i*h, h) for i in range(steps))
return ival
# Tests
for a, b, steps, func in ((0., 1., 100, cube), (1., 100., 1000, reciprocal)):
for rule in (left_rect, mid_rect, right_rect, trapezium, simpson):
print(('%s integrated using %s\n from %r to %r (%i steps) = %r' %
(func.__name__, rule.__name__, a, b, steps,
integrate( func, a, b, steps, rule))))
a, b = Fraction.from_float(a), Fraction.from_float(b)
for rule in (left_rect, mid_rect, right_rect, trapezium, simpson):
print(('%s integrated using %s\n from %r to %r (%i steps and fractions) = %r' %
(func.__name__, rule.__name__, a, b, steps,
float(integrate( func, a, b, steps, rule)))))
# Extra tests (compute intensive)
for a, b, steps, func in ((0., 5000., 5000000, identity),
(0., 6000., 6000000, identity)):
for rule in (left_rect, mid_rect, right_rect, trapezium, simpson):
print(('%s integrated using %s\n from %r to %r (%i steps) = %r' %
(func.__name__, rule.__name__, a, b, steps,
integrate( func, a, b, steps, rule))))
a, b = Fraction.from_float(a), Fraction.from_float(b)
for rule in (left_rect, mid_rect, right_rect, trapezium, simpson):
print(('%s integrated using %s\n from %r to %r (%i steps and fractions) = %r' %
(func.__name__, rule.__name__, a, b, steps,
float(integrate( func, a, b, steps, rule)))))
| [
{
"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/numerical-integration-1.py | ethansaxenian/RosettaDecode |
from urllib import urlencode
from django.test import TestCase
from django.core.urlresolvers import reverse
class DefaultTestCase(TestCase):
def test_challenge(self):
response = self.client.get(
'%s?%s' % (reverse('challenge'), urlencode({
'hub.challenge': 'challenge',
'hub.verify_token': 'token',
'hub.mode': 'subscribe',
})))
self.assertEqual(response.content, 'challenge')
def test_privacy(self):
response = self.client.get(reverse('privacy'))
self.assertTemplateUsed(response, 'privacy.html')
def test_home(self):
response = self.client.get(reverse('home'))
self.assertTemplateUsed(response, 'home.html')
| [
{
"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 | vxmessenger/webapp/tests/test_webapp.py | praekeltfoundation/vumi-messenger |
import discord
from discord.ext import commands
bot = commands.Bot(command_prefix='-')
def inteam(ctx):
guild = bot.get_guild(GUILDID)
role = bot.get_role(ROLEID)
role in ctx.author.roles # GUILDID = The GuildID from the Support Server and RoleID is the Support RoleID.
@bot.event
async def on_ready():
print("The Bot is now online!")
@bot.event
async def on_message(message):
if message.author.id == bot.user.id:
return
if message.author != message.author.bot:
if not message.guild:
guild = bot.get_guild(GUILDID) # The GuildID from the Support Server.
channel = bot.get_guild(CHANNELID) # The ChannelID where the direct messages are sent.
embed = discord.Embed(title="New Direct Message", description=f'Author:\n{message.author.mention}\nID:\n{message.author.id}\nMessage Cotent:\n{message.content}', color=discord.Color.green())
embed.set_thumbnail(url=f'{message.author.avatar_url}')
await channel.send(embed=embed)
await bot.process_commands(message)
@bot.command()
@commands.guild_only()
@commands.cooldown(1, 15, commands.BucketType.user)
@commands.check(inteam)
async def dm(ctx, member: discord.Member, *, text):
embed = discord.Embed(title="New Answer", description=f'Message:\n{text}', color=discord.Color.green())
embed.set_author(url=f'{ctx.author.avatar_url}')
await member.send(embed=embed)
await ctx.send(f'The answer was sent to {member.id}!')
bot.run("TOKEN") # Your Bot Token | [
{
"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 | main.py | InvalidLenni/discordpymodmail |
from flask import Blueprint, request, jsonify, render_template
from apps.home.models import News, Classify
count = Blueprint('count', __name__)
@count.route('/admin/newcount/', methods=['POST', 'GET'])
def news_count():
if request.method == 'GET':
data = {}
title = []
count = []
news = News.query.order_by(News.classify_id).limit(7).all()
for new in news:
title.append(new.classify_id)
count.append(new.view_count)
data['title'] = title
data['count'] = count
return render_template('admin/news_count.html', data=data)
@count.route('/admin/leibiecount/', methods=['POST', 'GET'])
def leibie_count():
if request.method == 'GET':
data = {}
title = []
count = []
leibies = Classify.query.order_by(Classify.c_id).all()
for leibie in leibies:
title.append(leibie.c_name)
count.append(leibie.view_count)
data['title'] = title
data['count'] = count
return render_template('admin/leibie_count.html', data=data)
@count.route('/admin/yudingcount/', methods=['POST', 'GET'])
def yuding_count():
if request.method == 'GET':
data = {}
title = []
count = []
leibies = Classify.query.order_by(Classify.c_id).all()
for leibie in leibies:
title.append(leibie.c_name)
count.append(leibie.sub_count)
data['title'] = title
data['count'] = count
return render_template('admin/yuding_count.html', data=data)
| [
{
"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 | apps/admin/admin_count.py | zcd1997/flask_news_projects |
from CoolProp.CoolProp import PropsSI
import pandas as pd
class State:
self.fluid = T
self.T = T
self.p = p
self.h = PropsSI('H', 'T', T, 'P', p, fluid)
self.s = PropsSI('S', 'T', T, 'P', p, fluid)
self.D = PropsSI('D', 'T', T, 'P', p, fluid)
class Flow(State):
self.m_dot = T
def def_state_init(fluid):
# Standard temperature and preussre
T = 273.15
p = 101325.
state = pd.Series(index=['fluid','T','p','h','s','D'])
state.fluid = fluid
state.T = T
state.p = p
state.h = PropsSI('H', 'T', T, 'P', p, fluid)
state.s = PropsSI('S', 'T', T, 'P', p, fluid)
state.D = PropsSI('D', 'T', T, 'P', p, fluid)
return state
def def_state_tp(fluid, T, p):
state = pd.Series(index=['fluid','T','p','h','s','D'])
state.fluid = fluid
state.T = T
state.p = p
state.h = PropsSI('H', 'T', T, 'P', p, fluid)
state.s = PropsSI('S', 'T', T, 'P', p, fluid)
state.D = PropsSI('D', 'T', T, 'P', p, fluid)
return state
def def_state_ph(fluid, p, h):
state = pd.Series(index=['fluid', 'T', 'p', 'h', 's','D'])
state.fluid = fluid
state.T = PropsSI('S', 'P', p, 'H', h, fluid)
state.p = p
state.h = h
state.s = PropsSI('S', 'P', p, 'H', h, fluid)
state.D = PropsSI('D', 'P', p, 'H', h, fluid)
return state
def def_state_ps(fluid, p, s):
state = pd.Series(index=['fluid', 'T', 'p', 'h', 's','D'])
state.fluid = fluid
state.T = PropsSI('H', 'P', p, 'S', s, fluid)
state.p = p
state.h = PropsSI('H', 'P', p, 'S', s, fluid)
state.s = s
state.D = PropsSI('D', 'P', p, 'S', s, fluid)
return state
| [
{
"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 | estorage/archive/state.py | EnergyModels/estorage |
from django.apps import AppConfig
from django.utils.translation import ugettext_lazy
class PluginApp(AppConfig):
name = 'pretix_fsp_mail_template'
verbose_name = 'FSP Mail Template'
class PretixPluginMeta:
name = ugettext_lazy('FSP Mail Template')
author = 'Felix Gohla'
description = ugettext_lazy('Das Plugin beinhaltet eine E-Mail Vorlage für den FSP Ticketshop.')
visible = True
version = '1.0.0'
def ready(self):
from . import signals # NOQA
default_app_config = 'pretix_fsp_mail_template.PluginApp'
| [
{
"point_num": 1,
"id": "has_multiple_inheritance",
"question": "Does any class in this file use multiple inheritance?",
"answer": false
},
{
"point_num": 2,
"id": "more_functions_than_classes",
"question": "Does this file define more functions than classes?",
"answer": false
}... | 3 | pretix_fsp_mail_template/__init__.py | felix-gohla/pretix-fsp-mail-template |
from flask import request, Response
import DbInteractions.userLogin as ul
import DbInteractions.dbhandler as dbh
import json
# Delete endpoint, takes in a login token, upon success it deletes row from user session table(logs user out). If success returns true, return a response of None.
def delete():
success = False
try:
logintoken = request.cookies['logintoken']
success = ul.delete_login(logintoken)
except:
return Response("Something went wrong with logging out", mimetype="application/json", status=400)
if(success):
return Response(None, status=200)
else:
return Response("Something went wrong with logging out", mimetype="application/json", status=400)
# Function to create a new row in user_session table(log a user in). After getting password, use helper function to get the hashed+salted password. Send data to dbinteractions function
# Convert the returned data to json, and if success returns true, return the converted data in the response
def post():
user_json = None
success = False
try:
email = request.json.get('email')
username = request.json.get('username')
password = request.json['password']
pass_hash = dbh.get_password(password, email=email, username=username)
success, user = ul.post_login(
email, username, pass_hash)
user_json = json.dumps(user, default=str)
except:
return Response("Something went wrong logging in.", mimetype="application/json", status=403)
if(success):
return Response(user_json, mimetype="application/json", status=200)
else:
return Response("Something went wrong logging in.", mimetype="application/json", status=403)
| [
{
"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 | Endpoints/login.py | Schollar/arktracker_backend |
"""Core Model"""
from django.db import models
from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, \
PermissionsMixin
class UserManager(BaseUserManager):
"""User Manager"""
def create_user(self, email, password=None, **extra_fields):
"""Create and save a new user"""
if not email:
raise ValueError('Users must have an email address')
user = self.model(email=self.normalize_email(email), **extra_fields)
user.set_password(password)
user.save(using=self._db)
return user
def create_superuser(self, email, password):
"""Create and save a new superuser"""
user = self.create_user(email, password)
user.is_staff = True
user.is_superuser = True
user.save(using=self._db)
return user
class User(AbstractBaseUser, PermissionsMixin):
"""Custom User model that support using email instead of username"""
email = models.EmailField(max_length=255, unique=True)
name = models.CharField(max_length=255)
is_active = models.BooleanField(default=True)
is_staff = models.BooleanField(default=False)
objects = UserManager()
USERNAME_FIELD = 'email'
| [
{
"point_num": 1,
"id": "has_multiple_inheritance",
"question": "Does any class in this file use multiple inheritance?",
"answer": true
},
{
"point_num": 2,
"id": "has_nested_function_def",
"question": "Does this file contain any function defined inside another function?",
"answe... | 3 | application/core/models.py | DanishDanialZurkanain/recipe-app-api |
from rtamt.operation.abstract_operation import AbstractOperation
class NotOperation(AbstractOperation):
def __init__(self):
self.input = []
def update(self, *args, **kargs):
out = []
input_list = args[0]
for in_sample in input_list:
out_time = in_sample[0]
out_value = - in_sample[1]
out.append([out_time, out_value])
return out
def update_final(self, *args, **kargs):
return self.update(args[0])
def offline(self, *args, **kargs):
out = []
input_list = args[0]
for in_sample in input_list:
out_time = in_sample[0]
out_value = - in_sample[1]
out.append([out_time, out_value])
return out
| [
{
"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 | rtamt/operation/stl_ct/not_operation.py | BentleyJOakes/rtamt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.