text string | size int64 | token_count int64 |
|---|---|---|
from django.contrib import admin
# Register your models here.
from .models import Milk
from .models import Brand
from .models import Company
admin.site.register(Milk)
admin.site.register(Brand)
admin.site.register(Company)
| 226 | 66 |
"""
class lesson
""" | 24 | 10 |
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@File : tokenzier.py
@Time : 2021/09/11 16:00:04
@Author : Jia Qianjing
@Version : 1.0
@Contact : jiaqianjing@gmail.com
@Desc : None
'''
import json
import os
from typing import List
import numpy as np
from pypinyin import Style, pinyin
from ..... | 9,797 | 3,133 |
import os
import argparse
from collections import defaultdict
import torch
import torch.distributed as dist
from torch.nn.parallel import DistributedDataParallel as DDP
from torch.multiprocessing import Process
from tqdm import trange
from tensorboardX import SummaryWriter
from pycocotools.coco import COCO
from yolov... | 9,949 | 3,130 |
#!/usr/bin/env python
# coding=UTF-8
import sys
from blessings import Terminal
import time
import numpy as np
import argparse
# import subprocess;
# subprocess.call(["printf", "\033c"]);
def process_input():
out = None
args = sys.argv[1:]
if args:
out = args[0]
return out
def main():
sys.s... | 1,708 | 655 |
# bot.py
import os
import discord
from discord.ext import commands
from dotenv import load_dotenv
from time import sleep
load_dotenv()
TOKEN = os.getenv('DISCORD_TOKEN')
try:
with open('/app/flag.txt', 'r') as r:
FLAG = r.read().strip()
except FileNotFoundError:
FLAG = os.getenv('FLAG', 'bts{tmpflag}... | 3,359 | 1,198 |
# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT!
import grpc
from google.ads.google_ads.v4.proto.resources import campaign_bid_modifier_pb2 as google_dot_ads_dot_googleads__v4_dot_proto_dot_resources_dot_campaign__bid__modifier__pb2
from google.ads.google_ads.v4.proto.services import campaign_bid_... | 3,734 | 1,238 |
from django.db import models
from django.contrib.auth.models import User
from django.utils.translation import ugettext_lazy as _
class GithubOrganization(models.Model):
# Auto fields
pub_date = models.DateTimeField(_('Publication date'), auto_now_add=True)
modified_date = models.DateTimeField(_('Modified ... | 4,369 | 1,316 |
import threading
import Queue
import os
import logging
import json
import time
import random
import requests
import multitail2
import errno
import tempfile
from requests.auth import HTTPBasicAuth
from utils import Datapoint
class MetricForwarder(threading.Thread):
'''
Simple metric data forwarder.
Forward... | 8,840 | 2,454 |
from .cli import run
run()
| 27 | 10 |
#
# pr9_3_1
from audiolazy import lazy_lpc
from scipy.signal import lfilter, find_peaks
from LPC import LPC
from Universal import *
if __name__ == '__main__':
filename = 'snn27.wav'
speech = Speech()
x, fs = speech.audioread(filename, None) # read one frame data
u = lfilter(b=np.array([1, -0.99]), a=1, x=x) # ... | 2,119 | 1,063 |
from methods import *
'''
This file contains the test functions of every function defined in methods.py, which is imported.
This file is imported by the main file ( application.py )
'''
def sort_transactions_test(list_of_transactions):
list_of_transactions = [['7', '120', 'out', 'first'], ['7', '105', 'out', 'seco... | 8,356 | 3,429 |
""" Darshan Error classes and functions. """
class DarshanBaseError(Exception):
"""
Base exception class for Darshan errors in Python.
"""
pass
class DarshanVersionError(NotImplementedError):
"""
Raised when using a feature which is not provided by libdarshanutil.
"""
min_version = ... | 679 | 219 |
#!/usr/bin/env python
# This software was developed in whole or in part by employees of the
# Federal Government in the course of their official duties, and with
# other Federal assistance. Pursuant to title 17 Section 105 of the
# United States Code portions of this software authored by Federal
# employees are not su... | 6,618 | 2,049 |
"""
Not tested as they seemed obvious:
- "SleepTime": 31045, // Total amount of time sleeping including nocturnal awakenings (sleepOffset - sleepOnset)
- "WASO": 3932, // Total amount of time passed in nocturnal awakenings. It is the total time passed in non-wake stage
// from sleep Onset to sleep offse... | 17,684 | 5,996 |
import mouse
import keyboard
from PIL import Image
import pyscreenshot
from time import sleep
import os
def ver():
while True:
img = pyscreenshot.grab()
width, height = img.size
pixel_values = list(img.getdata())
print (pixel_values[width*mouse.get_position()[1]+mouse.get_position()[0]])
... | 602 | 219 |
import torch
from torch import nn
import sys
from src import models
from src import ctc
from src.utils import *
import torch.optim as optim
import numpy as np
import time
from torch.optim.lr_scheduler import ReduceLROnPlateau
import os
import pickle
from sklearn.metrics import classification_report
from sklearn.metric... | 8,124 | 2,602 |
#!/usr/bin/python2
# -*- coding: utf-8 -*-
import os, sys
import binascii
import struct
import StringIO
# chunk names are 4 bytes long
# not quite sure how long the header is but I guess 8 bytes for now :>
# actually it's not really a header but the first chunk
# 4 bytes for the name (FORM) and 4 bytes for the length ... | 4,145 | 1,430 |
try:
width=float(input("Ieraksti savas istabas platumu (metros): "))
height=float(input("Ieraksti savas istabas augstumu (metros): "))
length=float(input("Ieraksti savas istabas garumu (metros): "))
capacity=round(width*height*length, 2)
print(f"Tavas istabas tilpums ir {capacity} m\u00b3.")
except ... | 413 | 168 |
# Program to check how effective is Java's String's Hash Collision
# for generating hash codes for Indian Phone No.s
import random
from pprint import pprint
SAMPLE_SPACE = 10000
def genJavaHashCode(phone: str) -> int:
"""
s[0]*31^(n-1) + s[1]*31^(n-2) + … + s[n-1]
where :
s[i] – is the it... | 1,381 | 504 |
from arrhenius import stringify
"""
This script generates cool table with termodynamic parameters, taken from 'termodyn-acid.data.txt' and 'termodyn-anion.data.txt'
"""
head = '''
\\begin{center}
\\begin{tabular}{ x{1cm} x{2cm} x{2cm} x{2cm} x{2cm} x{2cm} } \\hline
Acid & E$_A$ \\newline kJ/mol & A \\ne... | 1,701 | 746 |
#!/usr/bin/env python3
import re, copy, urllib.request, urllib.parse, argparse, json
import networkx as nx
KEGG_DOWNLOAD_HTEXT_ENDPOINT = 'http://www.genome.jp/kegg-bin/download_htext?'
EXCLUDES = ['Global and overview maps', 'Drug Development', 'Chemical structure transformation maps']
class Node(dict):
def __i... | 9,930 | 2,862 |
import os
TWO_WEEKS = 1209600
SECRET_KEY = os.getenv('SECRET_KEY', None)
assert SECRET_KEY
TOKEN_EXPIRES = TWO_WEEKS
DATABASE_URL = os.getenv(
'DATABASE_URL',
'postgres://postgres@{0}:5432/postgres'.format(os.getenv('DB_PORT_5432_TCP_ADDR', None)))
assert DATABASE_URL
REDIS_HOST = os.getenv('REDIS_HOST', ... | 416 | 196 |
file = open("input.txt", "r")
num_valid = 0
for line in file:
# policy = part before colon
policy = line.strip().split(":")[0]
# get min/max number allowed for given letter
min_max = policy.split(" ")[0]
letter = policy.split(" ")[1]
min = int(min_max.split("-")[0])
max = int(min_max.split("-")[1])
... | 597 | 205 |
import argparse
import logging
import numpy as np
def Parse_Arguments():
parser = argparse.ArgumentParser()
# argument related to datasets and data preprocessing
parser.add_argument("--domain", dest="domain", type=str, metavar='<str>', default='res', help="domain of the corpus {res, lt, res_15}")
... | 4,209 | 1,428 |
import h5py
import numpy
import sklearn
import sklearn.datasets
from matplotlib import pyplot
def load_dataset():
data_dir = '/Users/fpena/Courses/Coursera-Deep-Learning/Assignments/datasets/'
train_dataset = h5py.File(data_dir + 'train_catvnoncat.h5', "r")
train_set_x_orig = numpy.array(train_dataset["t... | 3,503 | 1,413 |
from BaseModel import BaseModel
class TwoDigitYear(BaseModel):
def __init__(self):
super(TwoDigitYear, self).__init__()
def generate_confidence(self, preceding_stripes, slot_values, following_stripes):
# only care about ints for this model, so strip out anything that isn't
valid_valu... | 669 | 205 |
import numpy as np
class Compressor():
def __init__(self,
num_particles: int, num_spin_orbitals: int, rdm_ideal=None) -> None:
self.num_particles = num_particles
self.num_spin_orbitals = num_spin_orbitals
self.rdm_ideal = rdm_ideal
pass
def compress(self, rdm):
... | 5,078 | 2,070 |
from node.behaviors import Attributes
from node.behaviors import AttributesLifecycle
from node.behaviors import DefaultInit
from node.behaviors import DictStorage
from node.behaviors import Lifecycle
from node.behaviors import NodeAttributes
from node.behaviors import Nodespaces
from node.behaviors import Nodify
from n... | 5,285 | 1,512 |
class Empleado(object):
"Clase para definir a un empleado"
def __init__(self, nombre, email):
self.nombre = nombre
self.email = email
def getNombre(self):
return self.nombre
jorge = Empleado("Jorge", "jorge@mail.com")
jorge.guapo = "Por supuesto"
# Probando hasattr, getattr, seta... | 547 | 209 |
import torch
from torch import nn
# LabelSmoothingLoss from: https://github.com/dreamgonfly/transformer-pytorch/blob/master/losses.py
# License: https://github.com/dreamgonfly/transformer-pytorch/blob/master/LICENSE
class LabelSmoothingLoss(nn.Module):
def __init__(self, classes, smoothing=0.0):
super(Labe... | 852 | 297 |
# Copyright (C) 2017 Matthew C. Zwier and Lillian T. Chong
#
# This file is part of WESTPA.
#
# WESTPA 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, either version 3 of the License, or
# (at your option) any... | 931 | 297 |
#!/usr/bin/python
import sys
import logging
from m3_common import m3_common
#m3_common.configure_root_logger()
#logger = logging.getLogger(__name__)
from m3_logging import get_logger
logger = get_logger(__name__)
class mbus_message_generator(m3_common):
TITLE = "MBus Message Generator"
def add_parse_args(... | 3,044 | 1,113 |
import unittest
import numpy as np
import prml.nn as nn
class TestGaussian(unittest.TestCase):
def test_gaussian_draw_forward(self):
mu = nn.array(0)
sigma = nn.softplus(nn.array(-1))
gaussian = nn.Gaussian(mu, sigma)
sample = []
for _ in range(1000):
sample.ap... | 1,172 | 451 |
# Generated by Django 2.1.3 on 2018-11-24 13:52
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
class Migration(migrations.Migration):
dependencies = [
('monsterapi', '0022_auto_20181123_2339'),
]
operations = [
migrations.CreateMod... | 1,087 | 358 |
def f(n):
for i in range(n):
yield n
| 49 | 20 |
from . import main_api
__all__=[
"main_api"
] | 50 | 22 |
import sys
import argparse
import matplotlib.pyplot as plt
import numpy as np
import pickle
def load_obj(name):
pkl_path = ""
with open(pkl_path + name + ".pkl", 'rb') as f:
return pickle.load(f)
def load_prun_obj(name):
pkl_path = ""
with open(pkl_path + name + ".pkl", 'rb') as f:
r... | 5,852 | 2,386 |
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
#
# The MIT License (MIT)
#
# Copyright (c) 2020
# Alberto Francisco Kummer Neto (afkneto@inf.ufrgs.br),
# Luciana Salete Buriol (buriol@inf.ufrgs.br) and
# Olinto César Bassi de Araújo (olinto@ctism.ufsm.br)
#
# Permission is hereby granted, free of charge, to any person ... | 2,502 | 926 |
#!/usr/bin/env python3
"""
This Python script is designed to perform unit testing of Wordhoard's
Homophones module.
"""
__author__ = 'John Bumgarner'
__date__ = 'September 20, 2020'
__status__ = 'Quality Assurance'
__license__ = 'MIT'
__copyright__ = "Copyright (C) 2021 John Bumgarner"
import unittest
from wordhoard... | 936 | 303 |
from __future__ import annotations
from typing import Literal, TypedDict, Union, final
from typing_extensions import NotRequired
from .asset import AssetData
class YoutubeLinkEmbedMetadata(TypedDict):
type: Literal["YouTube"]
id: str
timestamp: NotRequired[str]
class TwitchLinkEmbedMetadata(TypedDict... | 3,492 | 1,101 |
# from collections import deque
import numpy as np
import random
import torch
import pickle as pickle
from torch.autograd import Variable
class rpm(object):
# replay memory
def __init__(self, buffer_size):
self.buffer_size = buffer_size
self.buffer = []
self.priorities = []
... | 2,933 | 905 |
from app import handler
from app import line_bot_api, handler
from linebot.models import (
MessageEvent, TextMessage, TextSendMessage, ImageSendMessage
)
import random
import re
import urllib
def google_isch(q_string):
q_string= {'tbm': 'isch' , 'q' : q_string}
url = f"http://www.google.com/search?{urllib... | 1,519 | 525 |
import boto3
import botocore
from ruamel.yaml import YAML
yaml = YAML()
CLIENT = boto3.client('s3', # region_name='us-east-1',
config=botocore.client.Config(signature_version=botocore.UNSIGNED))
RESOURCE = boto3.resource('s3')
REF_DIFF = {'SWU4': 'http://fcon_1000.projects.nitrc.org/indi/CoRR/h... | 5,885 | 2,305 |
# -*- coding: utf-8 -*-
__all__ = ['PrometheusCounterConverter', 'PrometheusCounters']
from .PrometheusCounterConverter import PrometheusCounterConverter
from .PrometheusCounters import PrometheusCounters
| 207 | 66 |
from django.conf import settings
from django.conf.urls import include, url
from django.contrib import admin
from datenight.views import HomePageView
urlpatterns = [
# Examples:
url(r'^$', HomePageView.as_view(), name='home'),
# url(r'^blog/', include('blog.urls')),
url(r'^admin/rq/', include('django... | 635 | 219 |
# -*- coding: utf-8 -*-
from flask import flash, make_response, request
import json
from flask_babel import lazy_gettext, gettext
from datetime import datetime
from flask_login import current_user
from flask_appbuilder.actions import action
from flask_appbuilder import expose
from flask import redirect
from plugins.com... | 8,337 | 2,471 |
# - Generated by tools/entrypoint_compiler.py: do not edit by hand
"""
Models.OvaModelCombiner
"""
from ..utils.entrypoints import EntryPoint
from ..utils.utils import try_set, unlist
def models_ovamodelcombiner(
training_data,
predictor_model=None,
model_array=None,
use_probabilitie... | 3,601 | 1,033 |
# -*- coding: utf-8 -*-
'''Public section, including homepage and signup.'''
from flask import (Blueprint, request, render_template, flash, url_for,
redirect, session)
from flask.ext.login import login_user, login_required, logout_user
from kraken.extensions import login_manager
from kraken.user.mo... | 2,496 | 737 |
# Generated by Django 2.2.7 on 2020-05-29 19:44
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('game', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='message',
name='visible',
fiel... | 374 | 124 |
import unittest
from prime_permutations import *
class PrimePermutationsTest(unittest.TestCase):
def test_prime_permutations(self):
self.assertEqual(sorted(prime_permutations()), sorted([2969, 6299, 9629]))
if __name__ == '__main__':
unittest.main()
| 271 | 98 |
import numpy as np
import numpy.linalg as la
import matplotlib.pyplot as plt
capacity = 6
prob_demand_mass = np.array([0.7, 0.2, 0.1])
prob_demand_supp = np.array([0, 1, 2])
T = 50
P = np.array([[0, 0, 0, 0, prob_demand_mass[0], prob_demand_mass[1], prob_demand_mass[2]],
[0, 0, 0, 0, prob_demand_mass[0... | 1,495 | 664 |
import requests
import json
from pprint import pprint
from pymongo import MongoClient
def get_vparis():
url = "https://opendata.paris.fr/api/records/1.0/search/?dataset=velib-disponibilite-en-temps-reel&q=&rows" \
"=251&facet=name&facet=is_installed&facet=is_renting&facet=is_returning&facet=nom_arrondis... | 1,177 | 440 |
#from twython import Twython
from twitter import Twitter, OAuth, TwitterHTTPError, TwitterStream
import json
CONSUMER_KEY = 'pxeqo0ylpUayIIl5Nlc2kBmkb'
CONSUMER_SECRET = 'JUAAG5ilMS9TxZN1Y0ZKwPhsamtE3gFoIYTnKfwWTGqGmF6zXL'
ACCESS_TOKEN = '395150986-GiB9RbBtrjjiEetZ977wtQwYGVWCuhiPMir0962F'
ACCESS_SECRET = 'DUk5aVVGGy... | 681 | 326 |
# -*- coding: utf-8 -*-
from app.data.DataManager import DataManager
from app.model.Simulator import Simulator
from app.data.Client import Driver
from app.tools.Logger import logger_sensitivity as logger
from app.model.ScenarioGenerator import ScenarioGeneratorFactory as SGF
from app.config.env import ScenarioGenerat... | 2,903 | 889 |
import importlib
from dataclasses import dataclass
from typing import FrozenSet, Callable, List
@dataclass
class Action:
name: str
precondition: FrozenSet[str]
positive_effect: FrozenSet[str]
negative_effect: FrozenSet[str]
@dataclass
class Problem:
actions: List[Action]
init: FrozenSet[str]... | 2,129 | 682 |
# -*- coding: utf-8 -*-
import numpy as np
import pytest
from recursiveNN.nodes import Val,Var,VSF, Add,Mul,Dot,CTimes,Transpose, Node
def test_variables_of_expressions():
ran=lambda x : np.random.random(x)-0.5
x=Var('x',ran((1,4)))
y=Var('y',ran((1,4)))
z=Var('z',ran((1,4)))
expr=Add(Add(Add(x,y)... | 1,547 | 775 |
import unittest
import pytest
from src.api.schemas.product_schema import ProductSchema
class ProductSchemaTests(unittest.TestCase):
def setUp(self):
pass
def tearDown(self):
pass
def test_validate_valid_product(self):
product = {"name": "Produt name", "description": "Some descrip... | 569 | 157 |
#coding=utf-8
"""
1.定义类;
2.创建测试方法test开头
3.创建setup_class, teardown_class
4.运行查看结果
"""
import pytest
class TestClass():
def test_a(self):
print('test_a')
def test_b(self):
print('test_b')
def setup_class(self):
print('------setup_class------')
def teardown_class(self):
... | 430 | 177 |
from unittest import TestCase
from click.testing import CliRunner, Result
from poeditor_sync.cmd import poeditor
class CmdReadOnlyTokenTest(TestCase):
def setUp(self) -> None:
super().setUp()
self.runner = CliRunner(env={
'POEDITOR_CONFIG_FILE': 'tests/test.yml',
'POEDITO... | 1,469 | 498 |
import numpy as np
import cv2
import proper
from cats.cats_simus import *
def vortex(wfo, CAL, charge, f_lens, path, Debug_print):
n = int(proper.prop_get_gridsize(wfo))
ofst = 0 # no offset
ramp_sign = 1 #sign of charge is positive
#sampling = n
ramp_oversamp = 11. # vortex is oversampled for a ... | 3,472 | 1,238 |
# Problem code
def search(nums, target):
return search_helper(nums, target, 0, len(nums) - 1)
def search_helper(nums, target, left, right):
if left > right:
return -1
mid = (left + right) // 2
# right part is good
if nums[mid] <= nums[right]:
# we fall for it
if target >= ... | 1,119 | 363 |
#
# PySNMP MIB module CISCO-EMBEDDED-EVENT-MGR-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-EMBEDDED-EVENT-MGR-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 17:39:13 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python vers... | 21,631 | 9,413 |
import paramiko
class _FastTransport(paramiko.Transport):
def __init__(self, sock):
super(_FastTransport, self).__init__(sock)
self.window_size = 2147483647
self.packetizer.REKEY_BYTES = pow(2, 40)
self.packetizer.REKEY_PACKETS = pow(2, 40) | 277 | 109 |
'''
Created on 14. sep. 2017 v2
@author: LJB
'''
from __future__ import division, absolute_import
from numba import jit, float64, int64, void
import numpy as np
import matplotlib.pyplot as plt
import timeit
_DPI = 250
_SIZE = 0.7
def figure_set_default_size():
F = plt.gcf()
DefaultSize = [8 * _SIZE, 6 * _S... | 13,211 | 5,275 |
import turtle
screen = turtle.Screen()
# this assures that the size of the screen will always be 400x400 ...
screen.setup(400, 400)
# ... which is the same size as our image
# now set the background to our space image
screen.bgpic("game.over")
turtle.mainloop()
| 266 | 95 |
#!/usr/bin/env python3
from cryptofeed import FeedHandler
from cryptofeed.defines import TRADES
from cryptoblotter.exchanges import CoinbaseBlotter
from cryptoblotter.trades import SequentialIntegerTradeCallback, ThreshCallback
from cryptoblotter.trades.constants import VOLUME
async def trades(trade):
print(tra... | 844 | 258 |
# Copyright 1999-2020 Alibaba Group Holding 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 a... | 29,665 | 11,145 |
#!/usr/bin/env python
from setuptools import find_packages, setup
with open("README.md", "r", encoding="utf-8") as f:
long_description = f.read()
setup(
name="tplink-wr-api",
version="0.2.1",
url="https://github.com/n1k0r/tplink-wr-api",
author="n1k0r",
author_email="me@n1k0r.me",
descript... | 1,259 | 401 |
"""The module contains functions to preprocess input
datasets into usable format."""
import gc
import gzip
import json
import logging
import multiprocessing as mp
import pathlib
import sys
from itertools import repeat
import numpy as np
import scipy.sparse as smat
logging.basicConfig(
stream=sys.stdout,
format... | 5,835 | 1,925 |
import logging
import pytest
from c4.devices.policyengine import PolicyEngineManager
from c4.messaging import Router, RouterClient
from c4.system.configuration import States, Roles
from c4.system.deviceManager import DeviceManager
from c4.system.messages import (LocalStartDeviceManager, LocalStopDeviceManager,
... | 1,585 | 442 |
# Licensed under a 3-clause BSD style license - see LICENSE.rst
from copy import deepcopy
import pytest
import numpy as np
from astropy import wcs
from . helper import SimModelTAB
def test_wcsprm_tab_basic(tab_wcs_2di):
assert len(tab_wcs_2di.wcs.tab) == 1
t = tab_wcs_2di.wcs.tab[0]
assert tab_wcs_2d... | 3,113 | 1,660 |
# coding: utf-8
# Copyright (c) 2016, 2019, Oracle and/or its affiliates. All rights reserved.
import os
import random
import shutil
import string
import tempfile
import unittest
try:
import unittest.mock as mock
except ImportError:
import mock
from OpenSSL import crypto
from services.dts.src.oci_cli_dts.a... | 11,560 | 3,679 |
#!/usr/bin/env python3
import sys,re,os,re, datetime
import requests
import json
import hashlib
import getopt
from pprint import pprint
from pathlib import Path
################################################################################
## Hashing large files
####################################################... | 7,544 | 2,409 |
import os
pkg_path = os.path.dirname(__file__)
static_folder = os.path.join(pkg_path, 'static')
template_folder = os.path.join(pkg_path, 'templates')
| 151 | 55 |
import sys
import io
import time
import pprint
input_txt = """
10
0 2 1 1 2 3
1 2 3 3 2 1
2 2 3 1 6 10
3 1 4 1
4 1 7 1
5 2 3 1 6 1
6 2 3 1 8 1
7 2 5 1 8 4
8 1 9 100000
9 0
"""
#sys.stdin = open("ALDS1_11_D_in11.txt","r")#io.StringIO(input_txt)
#sys.stdin = io.StringIO(input_txt)
sys.stdin = ope... | 2,421 | 974 |
"""AyudaEnPython: https://www.facebook.com/groups/ayudapython
# ------------------------ REDACCION ORIGINAL ------------------------
1. Crear un programa que pida un número entero e imprimirlo, si no se
ingresa deberá preguntar otra vez por el número entero hasta que
ingrese un número positivo.
2. Crear una lista que... | 1,103 | 369 |
"""
Test expression command options.
Test cases:
o test_expr_options:
Test expression command options.
"""
from __future__ import print_function
import os
import time
import lldb
import lldbsuite.test.lldbutil as lldbutil
from lldbsuite.test.lldbtest import *
class ExprOptionsTestCase(TestBase):
mydir = T... | 2,523 | 770 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""This module contains class MRT_Announcements_Table
Announcements_Table inherits from the Generic_Table class. The Generic_Table
class allows for the conection to a database upon initialization. Also
upon initialization the _create_tables function is called to initiali... | 1,724 | 489 |
# coding=utf-8
"""
Logical permission backends module
"""
from permission.conf import settings
from permission.utils.handlers import registry
from permission.utils.permissions import perm_to_permission
__all__ = ('PermissionBackend',)
class PermissionBackend(object):
"""
A handler based permission backen... | 4,138 | 1,019 |
# -*- coding: utf-8 -*-
# Copyright (c) 2021 Kouadio K. Laurent, zju-ufhb
# This module is part of the WATex core package, which is released under a
# MIT- licence.
"""
===============================================================================
Copyright (c) 2021 Kouadio K. Laurent
Permission is hereby granted, f... | 50,782 | 14,929 |
from ..factory import Type
class location(Type):
latitude = None # type: "double"
longitude = None # type: "double"
| 122 | 41 |
from floodsystem.flood import stations_level_over_threshold
from floodsystem.stationdata import build_station_list, update_water_levels
from floodsystem.analysis import polyfit
from floodsystem.datafetcher import fetch_measure_levels
from floodsystem.utils import sorted_by_key
import numpy as np
from datetime import ti... | 1,816 | 586 |
import logging
import os
import sqlalchemy
import setproctitle
import argparse
import yaml
from apscheduler.scheduler import Scheduler
from cryptokit.rpc_wrapper import CoinRPC
from simplecoin_rpc_client.sc_rpc import SCRPCClient
logger = logging.getLogger('apscheduler.scheduler')
os_root = os.path.abspath(os.path.di... | 3,514 | 1,206 |
from iconservice import *
class IRC2Interface(InterfaceScore):
""" An interface of ICON Token Standard, IRC-2"""
@interface
def name(self) -> str:
pass
@interface
def symbol(self) -> str:
pass
@interface
def decimals(self) -> int:
pass
@interface
def to... | 716 | 231 |
bl_info = {
"name": "Import Planar Code",
"author": "Naoya Tsuruta",
"version": (1, 0),
"blender": (2, 80, 0),
"location": "File > Import > Planar Code",
"description": "Import planar code and construct mesh by assigning vertex positions.",
"warning": "",
"support": "TESTING",
... | 8,686 | 2,958 |
# -*- coding: utf-8 -*-
from django.db import models
from .mixins import SeasonsMixin
from .time_base import TimeMixin
from . import fields
class EquipmentManager(models.Manager):
def get_by_natural_key(self, code):
return self.get(code=code)
class Equipment(SeasonsMixin, TimeMixin, models.Model):
... | 1,233 | 397 |
'''OpenGL extension NV.draw_vulkan_image
This module customises the behaviour of the
OpenGL.raw.GL.NV.draw_vulkan_image to provide a more
Python-friendly API
Overview (from the spec)
This extension provides a new function, DrawVkImageNV(), allowing
applications to draw a screen-aligned rectangle displa... | 2,394 | 721 |
from django.urls import path
from django.utils.translation import gettext_lazy as _
from .views import create_order_view, order_detail_view, generate_order_pdf_view
urlpatterns = [
path('admin/order/<int:order_id>/', order_detail_view, name='admin_order_detail'),
path('admin/order/<int:order_id>/pdf/', genera... | 426 | 140 |
import logging
import matplotlib
import pickle
matplotlib.use('Agg')
import matplotlib.colors as mcolors
import numpy as np
import matplotlib.pyplot as plt
plt.ioff()
font = {# 'family' : 'serif', # Times (source: https://matplotlib.org/tutorials/introductory/customizing.html)
'family': 'sans-serif', # Helvetic... | 21,781 | 7,713 |
import gevent
from gevent.queue import Queue, Empty
from gevent_subprocess import Popen, PIPE
from gsh.plugin import BaseExecutor, BaseInnerExecutor
class SshExecutor(BaseExecutor):
def __init__(self, args, kwargs):
self.ssh_opts = kwargs.get("ssh_opts", [])
super(SshExecutor, self).__init__(args,... | 2,272 | 653 |
from models.indicators import Indicators
import numpy as np
import matplotlib.pyplot as plt
def plot_prices(ax, prices, line_style):
i = np.arange(len(prices))
ax.plot(ax, prices, line_style)
return ax
def plot_macd(ax, prices, slow_period, fast_period, line_style='k-'):
macd = Indicators.macd(price... | 656 | 253 |
from multiprocessing import Process, Queue
from app.es_search import add_to_es, delete_all_es, reindex_es, delete_from_es
from logging import getLogger
from flask_sqlalchemy import SQLAlchemy
import sys
from app import app
from .models import Paste
logger = getLogger(__name__)
def delete_by_date_paste(date):
"""... | 4,318 | 1,172 |
"""
Unit Test for strings.basic problems
"""
from unittest import TestCase
from strings.basic import alphabetize
class TestAlphabetize(TestCase):
"""
Unit Test for alphabetize method
"""
def test_should_return_alphabet(self):
"""
Test alphabetize method using every uppercase and low... | 449 | 150 |
#This script is going to be used API calls but first it will serve as a testing script.
from IOTA_Module import *
from Configuration_Module import *
from Tools_Module import *
from UserProfile_Module import *
from Cryptography_Module import *
from NodeFinder_Module import *
from DynamicPublicLedger_Module import *
imp... | 6,162 | 1,903 |
# Copyright 2017 Cisco Systems, Inc.
# All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless requi... | 2,230 | 700 |
import sqlite3
from pathlib import Path
class Database:
def _cursor(self):
root = Path(__file__).parent
self._conn = sqlite3.connect(f'{root}/knowledge.sqlite')
return self._conn.cursor()
def _commit(self):
self._conn.commit()
def _close(self):
self._conn.close()... | 653 | 189 |
#!/usr/bin/env python
from distutils.core import setup
setup(
name="python-tdlib",
version="1.4.0",
author="andrew-ld",
license="MIT",
url="https://github.com/andrew-ld/python-tdlib",
packages=["py_tdlib", "py_tdlib.constructors", "py_tdlib.factory"],
install_requires=["werkzeug", "simplej... | 358 | 134 |
import numpy as np
import pandas as pd
import scipy.stats as scs
import itertools
from collections import defaultdict
import textwrap
import pingouin as pg
from statsmodels.stats.multicomp import pairwise_tukeyhsd
from sklearn.neighbors import NearestNeighbors
from sklearn.decomposition import PCA
from sklearn.cluster... | 30,937 | 11,434 |
from flask import Flask, request, abort
from linebot import (LineBotApi, WebhookHandler)
from linebot.exceptions import (InvalidSignatureError)
from linebot.models import *
import json
import os
from linebot.exceptions import LineBotApiError
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy.exc import IntegrityE... | 39,442 | 13,781 |