text string | size int64 | token_count int64 |
|---|---|---|
#Chapter 4 - Creating and Manipulating your own Databases
#*******************************************************************************************#
#Creating Tables with SQLAlchemy
# Import Table, Column, String, Integer, Float, Boolean from sqlalchemy
fr... | 8,130 | 2,226 |
import sys
from datetime import datetime
import yfinance as yf
def get_ticker_symbol(ticker: yf.Ticker) -> str:
try:
return ticker.get_info()['symbol']
except ImportError:
return ""
def get_stock_state(ticker: yf.Ticker) -> {}:
stock_info = ticker.history("1d").iloc[0].to_dict()
sto... | 2,735 | 1,047 |
# _____ _ _
# | __ \ | (_)
# | |__) |___ _ __ ___ ___ __| |_
# | _ // _ \ '_ ` _ \ / _ \/ _` | |
# | | \ \ __/ | | | | | __/ (_| | |
# |_| \_\___|_| |_| |_|\___|\__,_|_|
# Azure Vision API Key 1: 8ce845a5fcb44327aeed5dbd0debc2c0
# Azure Vision API K... | 4,214 | 1,428 |
```python
def solution(board,moves):
basket=[]
answer=[]
for move in moves:
for i in range(len(board)): # range(len(board)) ์ ์๋ ์ธํ๊ฐฏ์๋งํผ ๋ฐ๋ณต
if board[i][move-1]>0: # board[][] ์์ ์ธํ์ด ์กด์ฌํ ๋์๋ง ์คํํ๋๋ก
basket.append(board[i][move-1])
board[i][move-1]=0 # board[][... | 660 | 311 |
import numpy as np
import math
extraNumber = 4 * math.pi * pow(10,-7)
def introducedEMF():
freq = input("Input the frequency (Hz): ")
turns = input("Input how many turns of the squrare frame: ")
area = input("Input the area (m) (ignore the 10^-2): ")
magField = input("Input magnetic Field Ma... | 578 | 209 |
#**********************************************************
#* CATEGORY SOFTWARE
#* GROUP MARKET DATA
#* AUTHOR LANCE HAYNIE <LANCE@HAYNIEMAIL.COM>
#* DATE 2020-10-20
#* PURPOSE UNUSUAL OPTIONS ACTIVITY
#* FILE PAGINATION.PY
#**********************************************************
#* MODIFICATIONS
#* 2020-10-20 - ... | 1,917 | 688 |
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import division, print_function, unicode_literals
from time import strftime, gmtime
from email.header import make_header
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from .utils import strip_tags, for... | 4,297 | 1,291 |
import tensorflow as tf
import numpy as np
from model.train import fit
from keras.datasets import mnist
def LeNet(input_shape):
iw,ih,c = input_shape
net = tf.Graph()
with net.as_default():
x = tf.placeholder(tf.float32,shape=(None,iw,ih,c),name='x')
y = tf.placeholder(tf.int32,name='y')
... | 2,709 | 1,117 |
from _filament.core import *
| 29 | 10 |
"""
Module to execute the simulation for a given instance.
"""
""" import packages """
import logging
from importlib import import_module
import numpy.random as rdm
import copy
import numpy as np
""" import project configurations """
import configurations.settings_simulation as config
""" import project librar... | 20,865 | 6,428 |
import requests
from allauth.socialaccount.providers.discord.views import DiscordOAuth2Adapter
from allauth.socialaccount.providers.oauth2.views import OAuth2CallbackView, OAuth2LoginView
from .permissions import Permissions
from .provider import DiscordProviderWithGuilds
# Create your views here.
class DiscordGuil... | 1,957 | 585 |
# -*- mode: python; encoding: utf-8 -*-
#
# Copyright 2012 Jens Lindstrรถm, Opera Software ASA
#
# 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... | 10,174 | 2,662 |
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
# zaleลผnoลci Pythona: BeatifulSoup
# instalacja z pakietu
# Debian /Ubuntu: apt-get install python-bs4
# albo
# easy_install beautifulsoup4
# lub
# pip install beautifulsoup4
# skrypt robi spis firm ze stron mambiznes.pl
# i wypluwa CSV:
# Kolumny:
# fid
# nazwa - Nazwa f... | 3,175 | 1,251 |
def no_delete(cmd):
cmd._delete_ctx = False
return cmd
| 63 | 22 |
from django.db import models
from .queryset import ContractQuerySet
class BaseContractManager(models.Manager):
def get_queryset(self):
return super().get_queryset().defer("search_vector")
ContractManager = BaseContractManager.from_queryset(ContractQuerySet)
| 275 | 77 |
import pytest
from visma.api import VismaClientException
from visma.models import Article, ArticleAccountCoding, Unit
class TestCRUDArticle:
@pytest.fixture()
def article(self):
article = Article.objects.all()[0]
yield article
@pytest.fixture()
def coding(self):
coding = Art... | 1,520 | 450 |
#!/usr/bin/env python3
import sys
import ujson as json
import json as json_orig
import traceback
import re
import argparse
import os.path
import operator
import requests
from threading import Thread
from queue import Queue
from requests.packages.urllib3.exceptions import InsecureRequestWarning
requests.packages.urllib... | 6,549 | 2,114 |
# MIT licensed
# Copyright (c) 2020 lilydjwg <lilydjwg@gmail.com>, et al.
# Copyright (c) 2017 Felix Yan <felixonmars@archlinux.org>, et al.
from flaky import flaky
import pytest
pytestmark = [pytest.mark.asyncio, pytest.mark.needs_net]
@flaky(max_runs=10)
async def test_debianpkg(get_version):
assert await get_v... | 818 | 342 |
class bcolors():
HEADER = '\033[95m'
OKBLUE = '\033[94m'
OK = '\033[92m'
WARNING = '\033[96m'
FAIL = '\033[91m'
TITLE = '\033[93m'
ENDC = '\033[0m'
| 158 | 108 |
import csv
import math
from wpilib import Timer
from wpilib.command import Command
from commands.statespace import StateSpaceDriveController
from data_logger import DataLogger
from pidcontroller import PIDController
from drivecontroller import DriveController
def read_trajectories(fnom):
from os.path import dir... | 6,093 | 2,304 |
from abc import ABC, abstractmethod
class TestFramework(ABC):
@abstractmethod
def functionArgs(self, testName):
"""functionArgs.
:param testName: Name of test
"""
pass
@abstractmethod
def assertLessThan(self, x, y):
"""Should return code which checks x < y."""
... | 2,608 | 832 |
from datetime import datetime
def format_time_filter():
start_time = datetime.now().utcnow().replace(hour=0, minute=0, second=0, microsecond=0).timestamp()
end_time = datetime.utcnow().replace(second=0, microsecond=0).timestamp()
data = {
"start_time": start_time,
"end_time": end_time
}... | 337 | 108 |
import numpy as np
import matplotlib.pyplot as plt
from scipy import linalg as la
def PCA(dat, center=False, percentage=0.8):
M, N = dat.shape
if center:
mu = np.mean(dat,0)
dat -= mu
U, L, Vh = la.svd(dat, full_matrices=False)
V = Vh.T.conjugate()
SIGMA = np.diag(L)
X = U... | 923 | 350 |
# --------------------------------------------------------
# Licensed under The MIT License [see LICENSE for details]
# --------------------------------------------------------
import os
import torch
import torch.nn.functional as F
import numpy as np
from core import networks
from core.utils import *
from core.loss i... | 25,502 | 8,079 |
import gym
import datetime
import os
import numpy as np
from agent import DeepQAgent
def main():
env = gym.make("LunarLander-v2")
timestamp = '{:%Y-%m-%d-%H:%M}'.format(datetime.datetime.now())
o_dir = "LunarLander-v2/{}/models".format(timestamp)
if not os.path.exists(o_dir):
os.makedirs(o_d... | 1,800 | 589 |
import datetime
from prefect import task, Flow, Parameter
from prefect.engine.cache_validators import partial_parameters_only
from prefect.environments.execution import RemoteEnvironment
from prefect.environments.storage import Docker
from prefect.engine.result_handlers import JSONResultHandler, S3ResultHandler
from p... | 1,298 | 425 |
# -*- coding: utf-8 -*-
import os
from django.contrib.auth.models import AbstractUser
from django.db import models
from django.conf import settings
# Create your models here.
# ็จๆท
# class User(AbstractUser):
# u_name = models.CharField(max_length=20, verbose_name='ๆต็งฐ', default='')
# birthday = models.DateFie... | 9,616 | 3,568 |
from io import StringIO
from typing import List
import os
import csv
import re
import pytest
from django.core.management import call_command
from django.core.management.base import CommandError
from django.core.files.temp import NamedTemporaryFile
import accounts.models
from supply_chains.management.commands.ingest_c... | 6,385 | 2,180 |
while True:
try:
x = int(input("Please enter a number: "))
break
except ValueError:
print("Oops! That was no valid number. Try again...")
class B(Exception):
pass
class C(B):
pass
class D(C):
pass
for cls in [B, C, D]:
try:
raise cls()
except D:
... | 2,909 | 898 |
# This program has been developed by students from the bachelor Computer Science
# at Utrecht University within the Software and Game project course in 2019
# (c) Copyright Utrecht University (Department of Information and Computing Sciences)
# NOQA
| 250 | 64 |
"""
Lidar
"""
import time
import math
import pickle
import serial
import logging
import numpy as np
from donkeycar.utils import norm_deg, dist, deg2rad, arr_to_img
from PIL import Image, ImageDraw
class YdLidar(object):
'''
https://pypi.org/project/PyLidar3/
'''
def __init__(self, port='/dev/ttyUSB0',... | 9,511 | 3,173 |
from bootstrap.lib.options import Options
from bootstrap.lib.logger import Logger
from .extract_engine import ExtractEngine
from .predict_engine import PredictEngine
def factory():
if Options()['engine']['name'] == 'extract':
engine = ExtractEngine()
elif Options()['engine']['name'] == 'predict... | 477 | 135 |
from daipecore.decorator.notebook_function import notebook_function
@notebook_function
def load_data():
return 155
| 121 | 40 |
from SNLI_BERT import ModelTrainer
from SNLI_BERT import adjustBatchInputLen
from pytorch_transformers import BertTokenizer, BertModel, AdamW, WarmupLinearSchedule
from torch import nn
import torch
import config
class Model(nn.Module):
def __init__(self, inv_dict):
super(Model, self).__init__()
self... | 2,982 | 950 |
import tensorflow as tf
from tensorflow.keras import datasets, layers, models
import matplotlib.pyplot as plt
import sys
num_classes = 10
print("Num GPUs Available: ", len(tf.config.list_physical_devices('GPU')))
print("Num CPUs Available: ", len(tf.config.list_physical_devices('CPU')))
print(tf.config.list_physical_d... | 2,443 | 956 |
from submission import Submission
class JulesSubmission(Submission):
def run(self, s):
# :param s: input in string format
# :return: solution flag
# your solution code goes here
def find_for_row(row):
for fi in range(len(row)):
for si in range(fi + 1, l... | 698 | 219 |
#!/usr/bin/python3
## Tommy
from botbase import *
_aachen_c = re.compile(r"eit Ende Februar 2020 (?:wurden beim Robert.Koch.Institut \(RKI\) )?insgesamt ([0-9.]+)")
_aachen_d = re.compile(r"Die Zahl der gemeldeten Todesfรคlle liegt bei ([0-9.]+)")
_aachen_a = re.compile(r"Aktuell sind ([0-9.]+) Menschen nachgewiesen")
... | 1,248 | 503 |
from mach_utils import *
import logging
from argparse import ArgumentParser
from fc_network import FCNetwork
import tqdm
from dataset import XCDataset,XCDataset_massive
import json
from typing import Dict, List
from trim_labels import get_discard_set
from xclib.evaluation import xc_metrics
from xclib.data import data_u... | 12,967 | 4,318 |
import logging
predictLogger = logging.getLogger(__name__)
def predictDiversion(trajectory, classification, decfunout, threshold):
severities = computeSeverities(trajectory, decfunout, threshold)
(diversionDetections, firstDetectionIndex) = catchDiversionAlerts(trajectory, classification, threshold)
... | 5,824 | 1,974 |
from gazette.spiders.base.fecam import FecamGazetteSpider
class ScChapecoSpider(FecamGazetteSpider):
name = "sc_chapeco"
FECAM_QUERY = "cod_entidade:71"
TERRITORY_ID = "4204202"
| 192 | 90 |
from styx_msgs.msg import TrafficLight
import cv2
import numpy as np
import tensorflow as tf
from keras.models import load_model
import os
class TLClassifier(object):
def __init__(self):
self.true_path = os.path.dirname(os.path.realpath('models/'))
self.init_classifier()
self.ini... | 3,101 | 1,045 |
"""
Open API spec creation and server helpers
"""
import json
import re
from copy import deepcopy
from functools import partial
from pathlib import Path
from typing import Dict, List, Tuple, Type, Optional, Callable, Awaitable, Union
from datetime import date, datetime
from aiohttp import web
from aiohttp_swagger3 imp... | 25,394 | 7,309 |
#!/usr/bin/env python3
from xmovement import XMovement
import nxt
brick = nxt.locator.find_one_brick(debug=True)
realport = nxt.motor.PORT_A
print("START")
#motor.debug_info()
xmovement = XMovement(realport, brick)
try:
while True:
position = int(input())
xmovement.set_position(position)
... | 384 | 152 |
# Generated by Django 3.2.7 on 2021-09-22 09:28
import cloudinary.models
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import phonenumber_field.modelfields
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.... | 1,996 | 602 |
import glob
import os
import sys
from sgfmill.sgfmill import sgf
import global_vars_go as gvg
import loader
import utils
import board3d as go_board
import numpy as np
kifuPath = "./kifu"
num_games = gvg.num_games
from_game = gvg.from_test_games
lb_size = 250.
correct = 0
total = 0
num_lb = int((num_g... | 2,477 | 898 |
import os
import gpxpy
import gpxpy.gpx
from gpx_split.log_factory import LogFactory
class Writer:
"""
This class will write a track segment into a gpx file.
"""
def __init__(self, dest_dir):
self.dest_dir = dest_dir
self.logger = LogFactory.create(__name__)
def write(self, na... | 714 | 255 |
from typing import cast
import pandas as pd
import os
import numpy as np
import glob
from sklearn.model_selection import train_test_split
def prepare_data(random_state,path):
new_df = []
path1 = path
#path1 = ['C:\CassFlipkratScrappingProject\S1_Dataset','C:\CassFlipkratScrappingProject\S2_Dataset']
... | 1,303 | 507 |
import os
import numpy as np
from allennlp.predictors import Predictor
from isanlp.annotation_rst import DiscourseUnit
from symbol_map import SYMBOL_MAP
class AllenNLPSegmenter:
def __init__(self, model_dir_path, cuda_device=-1):
self._model_path = os.path.join(model_dir_path, 'segmenter_neural', 'model... | 3,882 | 1,100 |
import sys
sys.path.append('../G26/Instrucciones')
sys.path.append('../G26/Utils')
sys.path.append('../G26/Librerias/storageManager')
from instruccion import *
from Lista import *
from TablaSimbolos import *
from jsonMode import *
class Use(Instruccion):
def __init__(self, dbid):
self.dbid = dbid
de... | 963 | 290 |
# Exercรญcio Python 105: Analisando e gerando Dicionรกrios
# Faรงa um programa que tenha uma funรงรฃo notas() que pode receber vรกrias notas de alunos
# e vai retornar um dicionรกrio com as seguintes informaรงรตes:
#
# - Quantidade de notas
# - A maior nota
# - A menor nota
# - A mรฉdia da turma
# - A situaรงรฃo (opcional)
#
# Adi... | 2,337 | 812 |
# Auto generated by generator.py. Delete this line if you make modification.
from scrapy.spiders import Rule
from scrapy.linkextractors import LinkExtractor
XPATH = {
'name' : "//div[@class='product-name']/h1",
'price' : "//div[@class='span8']/div[@class='price-box']/p[@class='special-price']/span[2] | //div[@... | 1,410 | 584 |
#
# 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 us... | 2,741 | 802 |
nz = 512 # noize vector size
nsf = 4 # encoded voxel size, scale factor
nvx = 32 # output voxel size
batch_size = 64
learning_rate = 2e-4
dataset_path_i = "/media/wangyida/D0-P1/database/ShapeNetCore.v2/*/*/*/model_normalized.binvox.thinned"
dataset_path_o = "/media/wangyida/D0-P1/database/ShapeNetCore.v2/*/*/*/model_... | 385 | 169 |
# -*- coding: utf-8 -*-
# Copyright 2015 Mirantis, 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 requir... | 1,971 | 618 |
from .dummy import Backend
| 27 | 9 |
# -*- coding: utf-8 -*-
# author:lyh
# datetime:2020/5/28 22:28
"""
394. ๅญ็ฌฆไธฒ่งฃ็
็ปๅฎไธไธช็ป่ฟ็ผ็ ็ๅญ็ฌฆไธฒ๏ผ่ฟๅๅฎ่งฃ็ ๅ็ๅญ็ฌฆไธฒใ
็ผ็ ่งๅไธบ: k[encoded_string]๏ผ่กจ็คบๅ
ถไธญๆนๆฌๅทๅ
้จ็ encoded_string ๆญฃๅฅฝ้ๅค k ๆฌกใๆณจๆ k ไฟ่ฏไธบๆญฃๆดๆฐใ
ไฝ ๅฏไปฅ่ฎคไธบ่พๅ
ฅๅญ็ฌฆไธฒๆปๆฏๆๆ็๏ผ่พๅ
ฅๅญ็ฌฆไธฒไธญๆฒกๆ้ขๅค็็ฉบๆ ผ๏ผไธ่พๅ
ฅ็ๆนๆฌๅทๆปๆฏ็ฌฆๅๆ ผๅผ่ฆๆฑ็ใ
ๆญคๅค๏ผไฝ ๅฏไปฅ่ฎคไธบๅๅงๆฐๆฎไธๅ
ๅซๆฐๅญ๏ผๆๆ็ๆฐๅญๅช่กจ็คบ้ๅค็ๆฌกๆฐ k ๏ผไพๅฆไธไผๅบ็ฐๅ 3a ๆ 2[4] ็่พๅ
ฅใ
็คบไพ:
s = "3[a]2[bc]", ่ฟๅ "aaabcb... | 1,256 | 602 |
import os
import glob
import random
from PIL import Image
from matplotlib import pyplot as plt
from ipywidgets import Button, Output, HBox, VBox, Label, BoundedIntText
from IPython.display import Javascript, display
class ImagesLoader:
def __init__(self, images_path, images_extension):
self.images_path = ... | 5,872 | 1,755 |
import magic
import os
import random
import string
from ahye.settings import LOCAL_UPLOADS_DIR
def generate_filename(image_data, detect_extension=True):
alphanum = string.ascii_letters + string.digits
retval = ''
while not retval or os.path.exists(os.path.join(LOCAL_UPLOADS_DIR, retval)):
retval... | 1,066 | 349 |
import json
import boto3
from elasticsearch import Elasticsearch, RequestsHttpConnection
from requests_aws4auth import AWS4Auth
from boto3.dynamodb.conditions import Key
user_table = 'user-profile'
dynamodb = boto3.resource('dynamodb')
table = dynamodb.Table(user_table)
cognito = boto3.client('cognito-idp')
region = '... | 3,650 | 1,104 |
#!/usr/bin/env python
# -*- coding: utf-8 -*- #
from __future__ import unicode_literals
PLUGIN_PATHS = ['plugins']
PLUGINS = ['jinja_filters']
AUTHOR = u'Fluxoid Ltd.'
DESCRIPTION = u'Site description'
FOOTER_TEXT = u'Copyright © Fluxoid Ltd. 2017'
SITENAME = u'Cyclismo by Fluxoid Ltd.'
SITEURL = 'http://127.0.0... | 1,168 | 463 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# vim :set ft=py:
import blosc
from .compat_util import (OrderedDict,
)
# miscellaneous
FORMAT_VERSION = 3
MAGIC = b'blpk'
EXTENSION = '.blp'
# header lengths
BLOSC_HEADER_LENGTH = 16
BLOSCPACK_HEADER_LENGTH = 32
METADATA_HEADER_LENGTH = 32
... | 838 | 365 |
import torch
import torch.nn as nn
from torch.nn import Module
from torchvision import transforms
from nn_interpretability.interpretation.deconv.deconv_base import DeconvolutionBase
class DeconvolutionPartialReconstruction(DeconvolutionBase):
"""
Partial Input Reconstruction Deconvolution is a decision-based... | 2,595 | 721 |
from grab.spider import Spider
class FirstSpider(Spider):
pass
| 68 | 22 |
from .oracle_database import database_manager | 45 | 10 |
import sqlalchemy as sa
import ujson
from sqlalchemy.pool import NullPool
from irrd.conf import get_setting
def get_engine():
return sa.create_engine(
get_setting('database_url'),
poolclass=NullPool,
json_deserializer=ujson.loads,
)
| 269 | 88 |
import sys
import json
import base64
status = sys.argv[1]
if status.lower() == "warnig":
print('Status is WARN')
exit(1)
elif status.lower() == 'critical':
print('Status is CRITICAL')
exit(2)
elif status.lower() == 'unknown':
print('Status is UNKNOWN')
exit(3)
else:
print('Status is OK')
... | 333 | 123 |
import crypt
import io
import json
import logging
import re
import requests
import uuid
import yaml
from flask import current_app as app
from base64 import b64encode
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric import rsa
from cryptography.hazmat.backends imp... | 15,804 | 4,821 |
#!/usr/bin/env python3
# 2ๆฌกๅ
็ดฏ็ฉๅ S ใฎ [x1, x2) ร [y1, y2) ็ทๅ
def ac2(s, x1, x2, y1, y2):
return s[x2][y2] - s[x1][y2] - s[x2][y1] + s[x1][y1]
import numpy as np
_, *d = open(0)
n, k = map(int, _.split())
B = np.zeros((2*k, 2*k))
for e in d:
*z, c = e.split()
x, y = map(int, z)
B[x % (2*k)][(y + k * (z ==... | 416 | 259 |
# main imports
import numpy as np
import pandas as pd
import sys, os, argparse
import joblib
# image processing
from PIL import Image
from ipfml import utils
from ipfml.processing import transform, segmentation, compression
# modules and config imports
sys.path.insert(0, '') # trick to enable import of main folder mo... | 7,374 | 2,181 |
from __future__ import print_function, absolute_import, division # makes these scripts backward compatible with python 2.6 and 2.7
# pyKratos imports
from .Element import Element
# Other imports
import numpy as np
class TriangleElement(Element):
def __init__(self, elem_id, nodes):
super(TriangleElement... | 2,699 | 904 |
from collections import defaultdict
from ...account.models import Address, CustomerEvent, User
from ..core.dataloaders import DataLoader
class AddressByIdLoader(DataLoader):
context_key = "address_by_id"
def batch_load(self, keys):
address_map = Address.objects.in_bulk(keys)
return [address_... | 971 | 311 |
"""Utility functions to manage representations.
This module contains functions that will help in managing extracted
representations, specifically on sub-word based data.
"""
import numpy as np
from tqdm import tqdm
def bpe_get_avg_activations(tokens, activations):
"""Aggregates activations by averaging assuming ... | 11,770 | 3,421 |
# -*- coding: utf-8 -*-
from urllib import urlencode
from xml.etree import ElementTree
from requests import get
from datetime import datetime
from pytz import timezone
matka_api = "http://api.matka.fi/?"
matka_api_timezone = timezone("Europe/Helsinki")
api_user = "matkanaattori"
api_pass = "ties532soa"
class MatkaEx... | 2,298 | 749 |
import sys
try:
from . import minivect
except ImportError:
print >>sys.stderr, "Did you forget to update submodule minivect?"
print >>sys.stderr, "Run 'git submodule init' followed by 'git submodule update'"
raise
from . import _numba_types
from ._numba_types import *
__all__ = _numba_types.__all__
| 319 | 104 |
# Time: O(n)
# Space: O(1)
import collections
class Solution(object):
def maxConsecutiveAnswers(self, answerKey, k):
"""
:type answerKey: str
:type k: int
:rtype: int
"""
result = max_count = 0
count = collections.Counter()
for i in xrange(len(answ... | 580 | 177 |
"""The eliqonline component."""
| 32 | 11 |
class Fiz_contact:
def __init__(self, lastname, firstname, middlename, email, telephone, password, confirmpassword):
self.lastname=lastname
self.firstname=firstname
self.middlename=middlename
self.email=email
self.telephone=telephone
self.password=password
sel... | 354 | 108 |
##############################################################################
#
# Copyright (c) 2009 Zope Foundation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOF... | 1,587 | 458 |
TORRENTS_PER_PAGE = 25
| 23 | 15 |
import vtk
import numpy as np
class LinearSubdivisionFilter:
InputData = None
Output = None
NumberOfSubdivisions = 1
def SetInputData(self, polydata):
self.InputData = polydata
def GetOutput(self):
return self.Output
def SetNumberOfSubdivisions (self, subdivisions):
self.NumberOfSubdivisions = subdivis... | 3,320 | 1,347 |
# coding: utf-8
"""
Transaction Management Bus (TMB) API
No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) # noqa: E501
OpenAPI spec version: V3.2.0
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from __future__ import a... | 1,310 | 448 |
#!/usr/bin/env python
# hsslms.py
#
# This provides a command line interface for the pyhsslms.py
# implementation of HSS/LMS Hash-based Signatures as defined
# in RFC 8554.
#
#
# Copyright (c) 2020-2021, Vigil Security, LLC
# All rights reserved.
#
# Redistribution and use, with or without modification, are permitted
... | 11,214 | 4,164 |
"""Methods for parsing the unicode spec, and retrieving a list of Emoji and Modifiers.
Note that the model of 'Emoji' here isn't sufficiently general to represent everything in the spec -
a visual / user-facing emoji could be, for example, a super complicated Zero-Width-Join sequence. I
wanted to go in favor of ease-o... | 5,273 | 1,621 |
# -*- coding: utf-8 -*-
from setuptools import setup
setup(
name='superpose3d',
packages=['superpose3d'],
description='Diamond\'s 1988 rotational superposition algorithm (+scale tranforms)',
long_description='''Register 3-D point clouds using rotation, translation, and scale transformations.
## Usage
... | 4,212 | 1,305 |
# project/server/main/views.py
import os
#################
#### imports ####
#################
from flask import render_template, Blueprint
from project.server import app
################
#### config ####
################
main_blueprint = Blueprint('main', __name__,)
################
#### routes ####
###########... | 602 | 178 |
from .__init__ import (
__pkg_name__,
__pkg_version__,
__pkg_description__,
)
import sys
if sys.version_info < (3, 6):
sys.stdout.write(f"Sorry, {__pkg_name__} requires Python 3.6 or above\n")
sys.exit(1)
from .dirconfig import (
init_config,
crypt_change_password,
crypt_rebuild_meta,... | 5,598 | 1,623 |
from jumpscale.core.base import Base, fields
class BackupTokens(Base):
tname = fields.String()
token = fields.String()
| 129 | 44 |
import os
import tempfile
from glob import glob
import json
from collections import OrderedDict
import numpy as np
from .adding_features import adding_no_features
def iterate_json_data(filepath,
columns_to_keep=None,
feature_adder=adding_no_features,
... | 3,511 | 962 |
from mongoengine import *
from datetime import datetime
class AccountModel(Document):
meta = {'collection': 'account'}
id = StringField(required=True, primary_key=True)
username = StringField(required=True)
password = StringField(required=True)
register_on = DateTimeField(required=True, default=da... | 333 | 88 |
# Generated by Django 3.0.4 on 2020-03-21 19:02
from django.db import migrations
import phonenumber_field.modelfields
class Migration(migrations.Migration):
dependencies = [
('users', '0009_auto_20200321_1438'),
]
operations = [
migrations.AlterField(
model_name='customuser'... | 473 | 172 |
# -*- coding: utf-8 -*-
###########
# IMPORTS #
###########
# Standard
from os.path import (
abspath as _os_abspath,
dirname as _os_dirname,
isfile as _os_isfile,
join as _os_join
)
from json import (
load as _json_load
)
#############
# CONSTANTS #
#############
_replacements = [
('NaN'... | 5,471 | 1,757 |
import logging
import re
import os
import mimetypes
from flask import Response
LOG = logging.getLogger(__name__)
MB = 1 << 20
BUFF_SIZE = 10 * MB
def partial_response(path, start, end=None):
LOG.info('Requested: %s, %s', start, end)
file_size = os.path.getsize(path)
# Determine (end, length)
if end ... | 1,428 | 508 |
import socketserver, threading
from RestfulApiHandler import RestfulApiHandler
if __name__ == "__main__":
server = socketserver.ThreadingTCPServer(('0.0.0.0', 32002), RestfulApiHandler)
t = threading.Thread(target= server.serve_forever, args = ())
t.start() | 270 | 92 |
from django.conf.urls import include, url
from . import views
urlpatterns = [
url(r'^task$', views.ShowTask.as_view(), name='show_task'),
url(r'^task/add/$', views.AddTask.as_view(),name='add_task'),
url(r'^(?P<slug>[\w\-]+)$', views.ShowTask.as_view(), name='show'),
]
| 292 | 112 |
import hashlib
import hmac
import requests
import time
from functools import reduce
class CryptoMKT(object):
BASE_URL = 'https://api.cryptomkt.com'
API_VERSION = 'v1'
ENDPOINT_BALANCE = 'balance'
ENDPOINT_BOOK = 'book'
ENDPOINT_MARKETS = 'market'
ENDPOINT_TICKER = 'ticker'
ENDPOINT_TRAD... | 4,344 | 1,406 |
# Copyright (c) 2010-2021 openpyxl
from .tokenizer import Tokenizer
| 69 | 30 |
# -*- coding: utf-8 -*-
"""
Combination of
http://scipy-central.org/item/52/1/zplane-function
and
http://www.dsprelated.com/showcode/244.php
with my own modifications
"""
# Copyright (c) 2011 Christopher Felton
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Le... | 5,925 | 2,115 |
"""
igen stands for "invoice generator".
The project is currently inactive.
"""
| 81 | 24 |
N,A,B=map(int,input().split())
print("Ant" if 0<N%(A+B)<=A else "Bug") | 70 | 38 |
import string
import math
from codestat_token import Token
from codestat_tokenizer import Tokenizer
from token_builders import (
InvalidTokenBuilder,
NullTokenBuilder,
WhitespaceTokenBuilder,
NewlineTokenBuilder,
EscapedStringTokenBuilder,
PrefixedStringTokenBuilder,
IntegerTokenBuilder,
IntegerExponen... | 30,518 | 13,545 |