text string | size int64 | token_count int64 |
|---|---|---|
from pygame import *
font.init()
speed_x = 1
speed_y = 1
w,h = 500,500
window = display.set_mode((w,h))
background = transform.scale(image.load("amogus.png"), (w,h))
font1 = font.Font(None,35)
lose1 = font1.render('ПЕРВЫЙ БОТ СЛИТ',True,(180,0,0))
font2 = font.Font(None,35)
lose2 = font1.render('ВТОРОЙ БОТ ... | 2,448 | 1,000 |
#
# Copyright (c) 2010, 2014, Oracle and/or its affiliates. All rights
# reserved.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; version 2 of the License.
#
# This program is distributed in ... | 3,964 | 1,129 |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'TEST.ui'
#
# Created by: PyQt5 UI code generator 5.15.2
#
# WARNING: Any manual changes made to this file will be lost when pyuic5 is
# run again. Do not edit this file unless you know what you are doing.
from PyQt5 import QtCore, QtGui, ... | 3,322 | 1,044 |
"""Module grouping tests for the bodemdiepteinterval search module."""
import datetime
from owslib.fes import PropertyIsEqualTo
from pydov.search.bodemdiepteinterval import BodemdiepteintervalSearch
from pydov.types.bodemdiepteinterval import Bodemdiepteinterval
from pydov.util.dovutil import build_dov_url
from tests... | 1,793 | 650 |
import numpy as np
import pandas as pd
print(3+5/12)
x= 12
y=6
z=3
print(x+z-y) | 81 | 45 |
from distutils.core import setup
setup(name='substitute',
version='1.1.1',
description='A friendly substitute for python mocking frameworks',
author='Johannes Hofmeister',
author_email='substitute@spam.cessor.de',
url='http://cessor.github.io/substitute',
packages=['substitute'],
k... | 438 | 133 |
#
# Copyright 2021. Clumio, Inc.
#
from typing import Any, Dict, Mapping, Optional, Sequence, Type, TypeVar
from clumioapi.models import mssql_database_backup_embedded
from clumioapi.models import mssql_database_backup_links
from clumioapi.models import mssql_database_file
T = TypeVar('T', bound='MssqlDatabaseBackup... | 6,922 | 1,868 |
from allauth.account.forms import SignupForm
from django import forms
from .models import CustomUser
from allauth.account.adapter import DefaultAccountAdapter
class CustomSignupForm(SignupForm):
age = forms.IntegerField()
class Meta:
model = CustomUser
def signup(self, request, user):
us... | 394 | 109 |
import asyncio
import discord
import inspect
from discord.ext import commands
from Cogs import *
# This module is for random funny things I guess...
class Help:
def __init__(self, bot, cogs):
# cogs = an array of the cogs used to start the bot
self.bot = bot
self.cogs = cogs
def message(self, message)... | 485 | 160 |
import logging
import pytest
from dkulib.dku_config.custom_check import CustomCheckError
from dkulib.dku_config.dss_parameter import DSSParameter, DSSParameterError
LOGGER = logging.getLogger(__name__)
class TestDSSParameter:
def test_nominal_case(self):
dss_parameter = DSSParameter(
name='... | 5,351 | 1,503 |
from abc import ABCMeta, abstractmethod
class AbstractScaleIn(object):
__metaclass__ = ABCMeta
@abstractmethod
def scalein(self, command):
pass
| 166 | 48 |
#!/usr/bin/python
# -*- coding: utf-8 -*-
__author__ = 'ar'
# import numpy as np
import multiprocessing as mp
import multiprocessing.pool
from sklearn.cluster import KMeans
import math
import numpy as np
from concurrent.futures import ThreadPoolExecutor
import threading
def my_fun(params):
idx = params[0]
va... | 1,525 | 611 |
# -*- coding: utf-8 -*-
from PySide2 import QtCore, QtGui, QtWidgets
import json
import core_functions as cf
import numpy as np
class Ui_Statistics(object):
def setupUi(self, Statistics):
# Note: this is not how it should be done but currently I don't know
# how to do it differently. This is only... | 6,187 | 1,979 |
class Perros(object): #Declaramos la clase principal Perros
def __init__(self, nombre, peso): #Definimos los parámetros
self.__nombre = nombre #Declaramos los atributos
self.__peso = peso
# Getter, setter y deleter de nombre
@property
def nombre(self): #Definimos el método para obt... | 1,935 | 635 |
# -*- coding: UTF-8 -*-
from ..voc import Voc
from ..coco import Coco
from ..core.sample import Sample
from icv.utils import reset_dir, mkfile
import os
class CocoConverter(object):
def __init__(self, coco):
assert isinstance(coco, Coco)
self.coco = coco
def to_voc(self, voc_root, split=None,... | 1,336 | 449 |
""" game24.py module
The 24 game is played as follows:
You are given a list of four integers, each between 1 and 9, in a fixed order.
By placing operators +,-,* and / between the numbers, and grouping them
with parentheses, determine whether it is possible to reach the value 24.
Example: 5,2,7,8 => ((5*2)-7)*8
Usage:... | 2,097 | 645 |
# -*- coding: utf-8 -*-
# pretrained model parameter에서 slim.conv2d의 variable들을 tf.layers.conv2d로 바꿔줌.
old_check_file = "ckpt_woflow/model.ckpt" #기존 파일이름
new_check_file = "ckpt_woflow/model_renamed.ckpt" # 저장할 새로운 파일이름
import tensorflow as tf
tf.compat.v1.disable_eager_execution()
vars_to_rename = {
"individual/g_co... | 3,819 | 1,730 |
STREAM_MJPEG = "mjpeg"
| 23 | 15 |
import FWCore.ParameterSet.Config as cms
# SiStrip DQM Source
# Hardware Monitoring
from DQM.SiStripMonitorHardware.siStripFEDMonitor_P5_cff import *
# Condition DB Monitoring
from DQM.SiStripMonitorSummary.SiStripMonitorCondData_cfi import *
# DQMEventInfo
DqmEventInfoSiStrip = cms.EDAnalyzer( "DQMEventInfo",
... | 4,511 | 1,756 |
import datetime
import signal
from django.core.management import BaseCommand
from tornado.httpserver import HTTPServer
from tornado.ioloop import IOLoop
from chat.tornado import application
class Command(BaseCommand):
def sig_handler(self, sig, frame):
"""Catch signal and init callback"""
IOLoop... | 978 | 296 |
# coding: utf-8
"""
Prisma Cloud Compute API
No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501
The version of the OpenAPI document: 21.04.439
Generated by: https://openapi-generator.tech
"""
from __future__ import absolute_impor... | 1,407 | 512 |
#
# Lockstep Software Development Kit for Python
#
# (c) 2021-2022 Lockstep, Inc.
#
# For the full copyright and license information, please view the LICENSE
# file that was distributed with this source code.
#
# @author Ted Spence <tspence@lockstep.io>
# @copyright 2021-2022 Lockstep, Inc.
# @version 2022.4
# ... | 1,287 | 376 |
# TODO: define these models and get tests working again
from django.db import models
from lazymodel import ModelWithCaching
class Account(ModelWithCaching):
pass
class PhotoGallery(ModelWithCaching):
pass
| 219 | 63 |
import os
import json
while True:
try:
filename = str(input("Enter the filename for the .csv: "))
stream = open(filename, 'r').read()
break
except Exception:
print("Couldn't open the file. Try again.")
# While the file is a CSV, it is easier to use a quote as the delim... | 2,881 | 900 |
from dendrogenous.test.base import BaseTestCase
class testFunctionalDendrogenous(BaseTestCase):
"""
Functional test of full run
"""
| 146 | 47 |
# -*- coding: utf-8 -*
"""
@Software : PyCharm
@File : config.py
@Author : 梦影
@Time : 2021/04/26 20:21:16
"""
from plugin.common import bot, common
import time
class extend:
@staticmethod
async def select(value): # 查询用户群数据
sql = 'SELECT * FROM `main` WHERE `Value` = %s'
data = await bot.cli... | 1,390 | 554 |
"""
Author: James Campbell
What: Generates a random robots.txt on OSX
Notes: Only works on Python 3.6+. If gshuf doesnt work do brew install coreutils
"""
import subprocess
# change this for the number of words you want
numberofwords = 500
r = subprocess.Popen(f"gshuf -n{numberofwords} /usr/share/dict/words",stdout=... | 611 | 221 |
# Copyright 2021, Blue Brain Project, EPFL
#
# 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 t... | 22,470 | 6,549 |
def calc_addition(a, b):
return a + b
def calc_multiply(a, b):
return a * b
def calc_substraction(a, b):
return a - b
| 142 | 61 |
# -*- coding: utf8 -*-
import http.client
import logging
import shlex
import shutil
import socket
import ssl
import subprocess
from unittest.mock import patch, Mock, call
from .mocks.connexionmock import createHTTPConnectionMock, createHTTPSConnectionMock
import dyndnsupdate
# URL settings
def test_without_setting... | 3,270 | 1,026 |
#!/usr/bin/env python3
# Usage: ./scripts/add_come.py
url = "https://codi.kanthaus.online/come/download"
import urllib.request
with urllib.request.urlopen(url) as response:
markdown = response.read().decode()
import yaml
parts = markdown.split('---')
frontmatter = parts[1]
frontmatter = yaml.safe_load(frontmatte... | 793 | 275 |
import os
from shutil import copy
path_new = "../../../data/vggface2-80"
path_old = "../../../datasets/vggface2/train"
# Create destination folder
if not os.path.exists(path_new):
os.makedirs(path_new)
subfolders = [entry for entry in os.scandir(path_old) if entry.is_dir()][0:80]
for dir in subfolders:
fol... | 918 | 317 |
import time
class DoublyLinkedList:
def __init__(self):
self.head = None
self.current = None
def display(self):
it = self.head
while it is not None:
print(it.value, end=" ")
it = it.next
print("")
def displayReverse(self):
it = self... | 3,935 | 1,305 |
from traces import Domain, TimeSeries
def from_pandas(df, compact=True):
'''TODO'''
domain = Domain(df.index[0], df.index[-1])
data = {col: TimeSeries(df[col].T, domain=domain) for col in df.columns}
if compact:
for val in data.values():
val.compact()
return data
| 306 | 99 |
"""Codewars: Persistent Bugger
6 kyu
URL: https://www.codewars.com/kata/55bf01e5a717a0d57e0000ec/train/python
Write a function, persistence, that takes in a positive parameter num
and returns its multiplicative persistence, which is the number of
times you must multiply the digits in num until you reach a single
d... | 2,075 | 788 |
import os
def get_file_size(absolute_path):
return os.stat(absolute_path).st_size
def sizeof_fmt(num, suffix='B'):
# Thanks https://stackoverflow.com/a/1094933
for unit in ['', 'Ki', 'Mi', 'Gi', 'Ti', 'Pi', 'Ei', 'Zi']:
if abs(num) < 1024.0:
return "%3.1f%s%s" % (num, unit, suffix)
... | 385 | 170 |
from typing import Iterable, MutableMapping
from tqdm import tqdm # type: ignore
import pytest
from text2array import StringStore, Vocab
class TestFromSamples:
@staticmethod
def from_samples(ss, **kwargs):
return Vocab.from_samples(ss, pbar=tqdm(disable=True), **kwargs)
def test_ok(self):
... | 5,953 | 2,215 |
import random
x = 0
y = 100
counter = 0
print("choose a number between 0-100 and let me guess your number")
while True:
a = random.randint(int(x),int(y))
print("your number is", a, end = " ")
guess = int(input("1.too low\n2.too high\n3.congratulations"))
if guess == 3:
print("tha... | 558 | 204 |
# -*- coding: utf-8 -*-
"""
@author: Danush
This file contains all the necessary input parameters for the infinite element
problem.
Any changes here reflects in the main.py file
"""
import numpy as np
def parameter_list():
"""This function returns all the input parameters
n_e - no. of elements to be... | 811 | 320 |
'''
mod_motif.py
usage: python mod_motif.py dataset.dat gff_file output.dat
this will modify the motif scores, found in the `gff_file`
'''
import sys
mchr = open(sys.argv[1])
gff = open(sys.argv[2])
out = open(sys.argv[3], 'w')
mchrl = mchr.readlines()
gffl = gff.readlines()
for i in range(len(mchrl)):
... | 2,477 | 960 |
from JumpScale import j
j.base.loader.makeAvailable(j, 'tools')
from Sandboxer import Sandboxer
j.tools.sandboxer = Sandboxer()
| 129 | 46 |
"""
Reimplementations of constructs introduced in later versions of Python than we
support.
"""
# These are in here because telling if something is an iterable just by calling
# hasattr(obj, "__iter__") behaves differently in Python 2 and Python 3. In
# particular, hasattr(str, "__iter__") is False in Python 2 and Tr... | 5,401 | 1,671 |
# Copyright 2019 Xilinx Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | 7,289 | 2,799 |
import re
def extract_tags(item):
"""Extracts the hashtags from the caption text."""
caption_text = ''
if 'caption' in item and item['caption']:
if isinstance(item['caption'], dict):
caption_text = item['caption']['text']
else:
caption_text = item['caption']
el... | 5,007 | 3,338 |
import csv
import datetime
from scipy.stats import norm
from regional_poll_interpolator import RegionalPollInterpolator
import riding_poll_model
party_long_names = {
'cpc': 'Conservative/Conservateur',
'lpc': 'Liberal/Lib',
'ndp': 'NDP-New Democratic Party/NPD-Nouveau Parti d',
'gpc': 'Green Party/Pa... | 8,045 | 2,654 |
import discord
from app.process_excel import receive_file, read_all_files, delete_file
from app.process_ical import receive_file as ical_receive_file
from datetime import datetime
from dotenv import load_dotenv
import os
dir_path = os.path.dirname(os.path.realpath(__file__))
client = discord.Client()
load_dotenv()
d... | 9,090 | 2,302 |
#!/usr/bin/env python
"""Baseline for relative time embedding: learn regression model in terms of
relative time.
"""
__author__ = 'Jun Li'
__date__ = 'Feberary 2021'
import torch
import torch.nn as nn
from torch.nn import functional as F
from ute.utils.arg_pars import opt
from ute.utils.logging_setup import logger
... | 1,579 | 554 |
import requests
dictToSend = {'input': 'Triple X'} # change the input text here
res = requests.post('http://localhost:5000/convert', json=dictToSend)
print('response from server:', res.text)
| 193 | 61 |
from remi import start, App
from simple_app import MyApp
if __name__ == "__main__":
start(MyApp, standalone=True)
| 120 | 42 |
# coding:utf-8
'''
Created on 2012-3-8
@author: tongjp
'''
import datetime
from django.contrib import auth
from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response
#from django.views.generic.list_detail import object_list,object_detail
from django.contrib.auth.models import User
f... | 2,171 | 628 |
# coding: utf-8
"""
Grafeas API
An API to insert and retrieve annotations on cloud artifacts.
OpenAPI spec version: 0.1
Generated by: https://github.com/swagger-api/swagger-codegen.git
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in co... | 8,831 | 2,444 |
import m1e_communication
m1e_communication.main(2)
| 52 | 22 |
# -*- coding: utf-8 -*-
import os
from flask.ext.script import Manager
from run import application
from domain import models
from database import init_db
manager = Manager(application)
import json
def no_map(model, mapped_models):
return model
def map_activity_type(model, mapped_models):
if "brreg_activ... | 2,116 | 684 |
# runs in debug mode, so the _read() needs to be called manually
import unittest
from debug_switch_user import _schema
class TestDebugSwitchUser(unittest.TestCase):
def test_debug_switch_user(self):
r = _schema.parse_file('src/nav_parent_switch.bin')
r._read()
self.assertEqual(r.code, 1)... | 364 | 121 |
import numpy as np
import sys
import os
import theano
import theano.tensor as T
import lasagne as nn
import utils as u
import models as m
import config as c
#
# trains a vae using convolutional features (and a separately trained network
# for reversing the convolutional feature extraction.
def main(data_file = '', n... | 4,438 | 1,618 |
# coding: utf-8
from enum import Enum
from six import string_types, iteritems
from bitmovin_api_sdk.common.poscheck import poscheck_model
class FileInputStreamType(Enum):
TTML = "TTML"
WEBVTT = "WEBVTT"
| 214 | 77 |
#encoding: utf-8
"""
tools.images -- Toolbox functions for creating image output
Exported namespace: image_blast, array_to_rgba, array_to_image, diffmap
Written by Joe Monaco
Center for Theoretical Neuroscience
Copyright (c) 2007-2008 Columbia Unversity. All Rights Reserved.
"""
import os as _os
import numpy as _N... | 4,088 | 1,433 |
#定义一个嵌套字典变量
users = {'num1': {'name': 'admin', 'passwd': 'admin888', 'sex': '1'}, 'num2': {'name': '赵杰', 'passwd': 'qd123456', 'sex': '0'}}
list1 = [] #定义两个空的列表
list2 = []
for key1 ,value1 in users.items() :
list1.append(value1['name']) #添加用户姓名
list2.append(value1['passwd']) #添加用户密码
prin... | 1,386 | 658 |
# -*- coding: utf-8 -*-
# type: ignore
'''Provide player hand tests.'''
from spades import db
from spades.game.models.card import Card
from spades.game.models.player import Hand
def test_hand(app) -> None:
'''Test hand.'''
hand = Hand()
hand.add_card(Card('A', 'S'))
db.session.add(hand)
db.sessio... | 424 | 155 |
import maya.cmds as cmds
import os
import sys
user = os.environ.get('USER')
path = 'C:/Users/' + user + '/Documents/maya/JM_Custom_Maya_Tools/Scripts'
if path not in sys.path:
sys.path.append(path)
import InitilizeTools
import JMCustomMarkingMenu
version = cmds.about(version = True)
destWindows = 'C:/Users/' + use... | 1,191 | 415 |
#
# Differential evolution MCMC
#
# This file is part of PINTS (https://github.com/pints-team/pints/) which is
# released under the BSD 3-clause license. See accompanying LICENSE.md for
# copyright notice and full license details.
#
from __future__ import absolute_import, division
from __future__ import print_function,... | 10,072 | 3,011 |
import argparse
import base64
import hashlib
import json
import ecdsa
from Crypto.Cipher import PKCS1_OAEP
from Crypto.Hash import SHA256
from Crypto.PublicKey import RSA
from Crypto.Signature import pss
from Crypto.Signature import pkcs1_15
from ecdsa.util import sigdecode_der
from aliyunsdkcore.client import AcsCli... | 23,621 | 7,982 |
class ConvertError(Exception):
# Public
pass
| 55 | 17 |
###################################################################################################################
#GMIT Higher Diploma in Data Analytics
#Scripting and Programming
#Python Project
#Diarmuid Whelan, 2018-04-10
#Iris Dataset initial exploration
#Will provide summary stats and plots for the Iris Dataset
... | 2,057 | 597 |
from stable_baselines_model_based_rl.utils.configuration import Configuration
from stable_baselines_model_based_rl.wrapper.wrapped_model_env import WrappedModelEnv
cfg_path = './sample_output/CartPole-v1/loss=0.0002335651806788519-lag=4.00-2021-08-14-13-15-36/config.yaml'
model_path = './sample_output/CartPole-v1/los... | 784 | 338 |
import sys
import numpy as np
import pytest
from opytimizer.core import function
from opytimizer.optimizers import ihs
from opytimizer.spaces import search
def test_ihs_hyperparams():
hyperparams = {
'HMCR': 0.5,
'PAR_min': 0.5,
'PAR_max': 1,
'bw_min': 2,
'bw_max': 5
... | 1,447 | 614 |
# -*- coding: utf-8 -*-
# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT!
"""Client and server classes corresponding to protobuf-defined services."""
import grpc
from dialogflow_v2beta1.proto import (
intent_pb2 as google_dot_cloud_dot_dialogflow__v2beta1_dot_proto_dot_intent__pb2,
)
from googl... | 14,440 | 4,260 |
# -*- coding: utf-8 -*-
# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://doc.scrapy.org/en/latest/topics/item-pipeline.html
import hashlib
# from bitarray.test_bitarray import to_bytes
from scrapy.pipelines.images import ImagesPipeline
from scrapy.exc... | 2,067 | 617 |
from contextlib import contextmanager
from unittest import mock
import meltano.api.app
import pytest
from flask import request_started
from flask_security.utils import login_user, logout_user
from meltano.api.models import db as _db
from meltano.api.security.identity import create_dev_user
from meltano.core.migration_... | 1,432 | 443 |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.shortcuts import render,redirect
from django.http import HttpResponse, HttpResponseRedirect
from . import queries
import requests
import googlemaps
from .config import *
# Create your views here.
def index(request):
return render(reques... | 4,432 | 1,477 |
import discord, requests, pyfiglet, datetime, aiohttp, urllib3, asyncio
import io
from discord.ext import commands as zeenode
from zeenode.load import token
from zeenode.config import prefix
bot = zeenode.Bot(command_prefix=prefix, self_bot=True)
bot.remove_command('help')
Output = "[ERROR] - "
class M... | 13,683 | 5,105 |
import torch
def argmax_2d(tensor):
assert len(tensor.shape) == 4
N, C, H, W = tensor.shape
tensor = tensor.reshape(N, C, H*W)
_, idx = tensor.max(dim = -1)
row, col = unravel_index(idx, H, W)
return torch.stack([row, col], dim = 2)
def unravel_index(idx, H, W):
row = (idx / W).long()
... | 419 | 174 |
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from django.test import TestCase
class TestHomepageInformation(TestCase):
def test_homepage_shows_correct_information(self):
browser_driver = webdriver.Chrome()
browser_driver.get("http://127.0.0.1:8000/")
self.... | 828 | 260 |
# Do not edit this file, pipeline versioning is governed by git tags
__version__= | 81 | 22 |
sdkman_dir = '/usr/local/sdkman'
def script_wrap(cmds):
sdk_init_tmpl = 'export SDKMAN_DIR={0} && source {0}/bin/sdkman-init.sh'
sdk_init = sdk_init_tmpl.format(sdkman_dir)
result_cmds = [sdk_init] + cmds
return "/bin/bash -c '{0}'".format('; '.join(result_cmds))
def check_run_for_rc_and_result(cmds... | 1,240 | 471 |
# Metrics dataset that comprises of vectors which will be searched for in job postings.
pl = [
['python', False],
['c#', False],
['c', False],
['c++', False],
['ruby', False],
['java', False],
[['javascript', 'js'], False],
[['html', 'html5'], False],
['css', False],
['sql', Fal... | 2,102 | 733 |
from configparser import ConfigParser
import json
import os
from ast import literal_eval
type_caster = {
'int': int,
'str': lambda x: x if x.lower() != 'none' else None,
'float': float,
'bool': lambda x: True if x == 'True' else False if x == 'False' else exec("raise Exception('invalid bool value: {}'.... | 3,850 | 1,214 |
# -*- coding: utf-8 -*-
"""
Label Shift
===========
"""
# sphinx_gallery_thumbnail_number = 2
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
import pandas as pd
from gpdre.benchmarks import LabelShift
from gpdre.applications.covariate_shift.benchmarks import regression_metric
from gpdre.dat... | 2,676 | 931 |
from db_tools import get_all_user_and_mensas, get_all_mensa_subscriptions,\
get_users
users_mensas = get_all_user_and_mensas()
print("unique sending messages %d" % len(users_mensas))
print("unique users %d" % len(get_users()))
mensas = get_all_mensa_subscriptions()
print("unique mensas %d" % len(mensas))
print("... | 353 | 137 |
import oceansat
def version():
print(oceansat.__version__)
| 65 | 25 |
import unittest
from tests.data import AllowedNone, ComposeOptional, Mix, Optional
class TestGenerate(unittest.TestCase):
def test_generate_field_is_generated(self):
entity = Optional()
entity.OptInt.generate()
self.assertTrue(entity.OptInt.generated)
def test_generate_field_value(se... | 2,915 | 827 |
import logging
from asyncio.events import AbstractEventLoop
from typing import TYPE_CHECKING
from and_beyond.client import globals
from and_beyond.client.ui import Ui, UiButton, UiLabel, UiTextInput
from and_beyond.client.ui.label_screen import LabelScreen
from and_beyond.common import USERNAME_REGEX
from zxcvbn impor... | 3,902 | 1,125 |
from pyvit.file.db import jsondb
from pyvit.hw import socketcan
parser = jsondb.JsonDbParser()
b = parser.parse('examples/example_db.json')
dev = socketcan.SocketCanDev('vcan0')
dev.start()
# Read in file and
# decode frame and print
while True:
frame = dev.recv()
signals = b.parse_frame(frame)
if si... | 373 | 130 |
#Importação das bibliotecas
from pandas import read_csv
from dash import Dash, html, dcc, Input, Output
import plotly.express as px
app = Dash(__name__, title='Emissão de CO2')
df = read_csv("annual-co2-emissions-per-country.csv")
df_array = df.values #Tranformando tudo o que estiver no df em uma lista para parar d... | 17,224 | 5,012 |
from typing import List
from app.domain import metric as domain
from app.domain.user_token import LoggedUser
from app.repository.database.metrics import MetricsRepo, metrics_repo
from app.service.authorization import authorize
from sqlalchemy.orm import Session
class CreateMetric:
def __init__(
self,
... | 1,257 | 362 |
import collections
from supriya.ugens.PV_ChainUGen import PV_ChainUGen
class PV_BinScramble(PV_ChainUGen):
"""
Scrambles bins.
::
>>> pv_chain = supriya.ugens.FFT(
... source=supriya.ugens.WhiteNoise.ar(),
... )
>>> pv_bin_scramble = supriya.ugens.PV_BinScramble.... | 683 | 274 |
"""
turtlegraphics.py
This module supports simple Turtle Graphics. The Turtle class represents
a turtle object in a graphics window. To instantiate a turtle, enter
turtle = Turtle() # Default window size 200 x 200
or
turtle = Turtle(width = 500, height = 500) # Window size 500 x 500
The turtl... | 8,490 | 2,648 |
SIZE = 1000
NUM_SENSORS = 2
DETERMINE_EFFECTIVENESS_TRIALS = 10 | 63 | 41 |
from rest_framework import serializers, fields
from rest_framework.exceptions import PermissionDenied
from ..models import ArticleComment, EquipmentComment, Equipment
from . import UserSerializer
class IsLiked(serializers.BooleanField):
def get_attribute(self, instance):
if self.context['request'].user.i... | 4,310 | 1,165 |
import os
import torch
import torch.utils.data as data
import torchvision.transforms as transform
import numpy as np
from PIL import Image
import cv2
class AlzhDataset(data.Dataset):
def __init__(self, type, root='/data/tm/alzh/New_dataset/train', transform=None):
self.transform = transform
if type... | 2,614 | 855 |
# -*- coding: utf-8 -*-
"""
Created on Fri Aug 27 12:05:33 2021
@author: Zahra Ghavasieh
Draws a Gantt chart given params
"""
# Importing the matplotlib.pyplot
import matplotlib.pyplot as plt
# Colours used for bars in chart
clrs = [
#'black', # Groom
'tab:orange', # In Place Activi... | 3,346 | 1,209 |
from setuptools import setup, find_packages
setup(
name='trafficsignrecognition',
version='0.1',
description="Traffic Sign Detection and Recognition",
author='Epameinondas Antonakos',
author_email='antonakosn@gmail.com',
packages=find_packages(),
install_requires=['menpofit>=0.4,<0.5',
... | 367 | 131 |
import os
import sys
import numpy as np
import rasterio
import dask
import dask.array as da
import certifi
import boto3
from botocore.exceptions import ClientError
"""
This file calculates yearly NDVI statistics (min, mean, max, standard deviation)
per pixel for Landsat tiles in an S3 bucket and outputs a .tif file. ... | 5,834 | 1,828 |
from apps.fifth_edition.models import NPC
from django.test import TestCase
from rest_framework.test import APIClient
class TestNPCViewGET(TestCase):
"""
Test class to verify functionality of the NPCViewGET API view.
"""
def setUp(self):
"""
Method to create required test data
... | 7,588 | 2,160 |
import textwrap
from conan.tools.microsoft import MSBuild
from conans.model.conf import ConfDefinition
from conans.test.utils.mocks import ConanFileMock, MockSettings
def test_msbuild_cpu_count():
c = ConfDefinition()
c.loads(textwrap.dedent("""\
tools.microsoft.msbuild:max_cpu_count=23
tools... | 815 | 256 |
from main.authorization import is_admin, is_guest, is_user
from django.contrib.messages.api import get_messages
from django.test.client import Client
from main.forms import LoginForm, RegisterForm
from main.models import User
from django.test import TestCase
from django.urls import reverse
class TestAuthentication(Te... | 3,549 | 998 |
#!/usr/bin/env python
"""Contains an example of midi input, and a separate example of midi output.
By default it runs the output example.
python midi.py --output
python midi.py --input
"""
import sys
import os
import pygame
import pygame.midi
from pygame.locals import *
try: # Ensure set available for output exa... | 1,695 | 566 |
class Solution(object):
def minCut(self, s):
"""
:type s: str
:rtype: int
"""
H = [[True for _ in xrange(len(s))] for _ in xrange(len(s))]
def isPalindrome(self, s):
if s == s[::-1]:
return True | 271 | 101 |
#coding:utf-8
from decision_tree import *
def prune(tree, mingain):
if tree.tb.results == None:
prune(tree.tb, mingain)
if tree.fb.results == None:
prune(tree.fb, mingain)
if tree.tb.results != None and tree.fb.results != None:
tb, fb = [], []
for v, c in tree.tb.results.... | 837 | 308 |
from gazette.spiders.base.fecam import FecamGazetteSpider
class ScImbitubaSpider(FecamGazetteSpider):
name = "sc_imbituba"
FECAM_QUERY = "cod_entidade:116"
TERRITORY_ID = "4207304"
| 195 | 91 |