text string | size int64 | token_count int64 |
|---|---|---|
#!/usr/bin/env python3
# -*-coding:utf-8-*-
"""
This module is used to extract features from the data
"""
import numpy as np
from scipy.fftpack import fft
from scipy.fftpack.realtransforms import dct
import python_speech_features
eps = 0.00000001
def file_length(soundParams):
"""Returns the file length, in sec... | 7,458 | 2,943 |
from .combine_sector_results import *
from .DiagnosticsLog import *
from .EstimationModel import *
from .format_regression_table import *
from .save_and_load import *
from .SlimResults import *
from .Specification import *
from .visualize_results import * | 255 | 73 |
# Part of the Engi-WebGL suite.
from bpy.props import *
from bpy_extras.io_utils import ExportHelper
from mathutils import *
from functools import reduce
import os, sys, os.path, bpy, bmesh, math, struct, base64, itertools
bl_info = {
'name': 'Curve Export (.json)',
'author': 'Lasse Nielsen',
'version': (0, 2),
'... | 2,435 | 983 |
import mimetypes
from pathlib import Path
from organize.utils import DotDict, flatten
from .filter import Filter
class MimeType(Filter):
"""
Filter by MIME type associated with the file extension.
Supports a single string or list of MIME type strings as argument.
The types don't need to be fully s... | 2,678 | 752 |
from conans import ConanFile, CMake, tools
class LibprotobufMutatorConan(ConanFile):
name = "libprotobuf-mutator"
version = "20200506"
license = "Apache-2.0"
settings = "os", "compiler", "build_type", "arch"
generators = "cmake"
exports_sources = "patches/*",
build_requires = "protoc_insta... | 1,857 | 663 |
import numpy as np
VEC_FORWARD = np.array([0, 0, 1])
VEC_UP = np.array([0, 1, 0])
VEC_RIGHT = np.array([1, 0, 0])
STYLE_NOMOVE = np.array([1, 0, 0, 0, 0, 0])
STYLE_TROT = np.array([0, 1, 0, 0, 0, 0])
STYLE_JUMP = np.array([0, 0, 1, 0, 0, 0])
STYLE_SIT = np.array([0, 0, 0, 1, 0, 0])
STYLE_STAND = np.array([0... | 524 | 334 |
#!/usr/bin/python
import argparse,codes3d,configparser, os
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Create a BED file detailing the locations of genes in the genome, and a database containing additional gene information. Note: If a file in .gtf format is supplied, no other arguments ... | 2,222 | 685 |
import numpy as np
from Optimizer.path import get_x_substeps
from Kinematic import frames, chain as kc
def initialize_frames(shape, robot, mode='hm'):
return frames.initialize_frames(shape=shape + (robot.n_frames,), n_dim=robot.n_dim, mode=mode)
def initialize_frames_jac(shape, robot, mode='hm'):
f = initi... | 5,900 | 2,506 |
import dns.resolver
import dns.ipv4
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('-l', "--list", help="List of dns names you want IP's for")
parser.add_argument('-o', "--output", help="Output file to save list")
args = parser.parse_args()
ip_list = [...]
subs = open(args.list, 'r', newline='... | 977 | 302 |
import pandas
import numpy as np
import math
import os
import sys
import re
from utils import *
DIR_PATH = os.path.dirname(os.path.realpath(__file__))
percentiles = [ 10, 25, 50, 75, 90, 95, 99, 99.9 ]
DATA_FOLDER = DIR_PATH + '/data'
def getResult(trial_string, thread, client_num=2):
print("thread: {}".format(t... | 8,416 | 2,974 |
from typing import Optional
from platypush.backend import Backend
from platypush.context import get_plugin
from platypush.message.event.foursquare import FoursquareCheckinEvent
class FoursquareBackend(Backend):
"""
This backend polls for new check-ins on the user's Foursquare account and triggers an event wh... | 1,821 | 574 |
import os
import time
import pandas as pd
from src.utils import get_project_root
from src.data.item_names_replacement import REPLACE_DICT1, REPLACE_DICT1
YEARS = [str(x) for x in list(range(2013,2021))]
ROOT_DIR = get_project_root()
def string_to_float(number):
#Custom function for converting 'sales_value' colum... | 2,980 | 1,060 |
"""
This file contains assorted general utility functions used by other
modules in the aiml_bot package.
"""
# TODO: Correctly handle abbreviations.
def split_sentences(text: str) -> list:
"""Split the string s into a list of sentences."""
if not isinstance(text, str):
raise TypeError(text)
positi... | 1,143 | 305 |
import os, time, random
from collections import defaultdict
from System import Console, ConsoleColor, ConsoleKey
from System.Threading import Thread, ThreadStart
class Screen(object):
red = ConsoleColor.Red; green = ConsoleColor.Green; blue = ConsoleColor.Blue;black = ConsoleColor.Black
dimension = (21,39)
... | 5,858 | 1,839 |
#
#! coding:utf-8
import xml.etree.ElementTree as ET
from xml.etree import ElementTree
import base64
import binascii
import numpy as np
import matplotlib.pyplot as plt
from collections import OrderedDict
SubType = {'1':'ASD','2':'CSD','3':'TF','4':'???','5':'COH'}
average_type = {'0':'Fixed','1':'Exponential','2':'Ac... | 14,376 | 4,750 |
# Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | 2,291 | 696 |
import torch
from torch.utils import data
import sys
from sklearn.utils import shuffle
import numpy as np
import argparse
import matplotlib.pyplot as plt
class UserSet(data.Dataset):
def __init__(self, path, tsplit, idim=100, seed=0, Nsongs=180198, pc_split=0.1, tag2vector_path=""):
"""
path : str
path + fn... | 11,672 | 4,842 |
import json
from typing import List
from LocationObject import LocationObject
def parse(file_path: str) -> List[LocationObject]:
with open(file_path, "r") as file:
data = json.loads(file.read().replace("\n", ""))
locations: List[LocationObject] = []
for object in data:
city = ... | 892 | 232 |
#!/usr/bin/env python3
#-*- codin:utf-8 -*-
'''
用django + celery + redis演示异步队列任务。
不过文章写的太简略了,文章没啥意思,水平到了可以直接看代码。
python manage.py migrate -- looks at the INSTALLED_APPS setting and creates any necessary database tables according to the database settings in your mysite/settings.py file and the database migrations shipp... | 736 | 289 |
import os
from datetime import datetime
from sqlalchemy.orm import sessionmaker
import nfp.servicos.model as tables
from nfp import CONEXAO
class ControleExecucao(object):
uri = ''
tarefa = None
tarefa_nova = False
engine = CONEXAO
def configurar_base_de_dados(self):
self.DBSession = ses... | 7,786 | 2,527 |
# -*- coding: utf-8 -*-
"""
Artifactory repository endpoint
"""
__copyright__ = "Copyright (C) 2016 Veritas Technologies LLC. All rights reserved."
# project imports
from ..http import HTTP
from .repotype import RepositoryType
from .virtual import Virtual
from .local import Local
from .remote import Remote
# define a... | 2,458 | 697 |
"""Adoption application."""
from flask import Flask, request, redirect, render_template
from models import db, connect_db, Pets
from wtforms import StringField, IntegerField, TextAreaField, BooleanField
from wtforms.validators import DataRequired,InputRequired,AnyOf,URL, NumberRange
from flask_wtf import FlaskForm
fro... | 2,887 | 949 |
"""
Utilities for (weighted) bootstrap resampling applied to geoscientific point-data.
"""
import numpy as np
import pandas as pd
from .meta import subkwargs
from .spatial import great_circle_distance, _get_sqare_grid_segment_indicies
from .log import Handle
logger = Handle(__name__)
try:
import sklea... | 17,810 | 5,218 |
# TODO: add unit tests for test_nhdplus_utils.py
| 49 | 18 |
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
from task import SequenceLearning
sns.set(style='white', palette='colorblind', context='poster')
np.random.seed(0)
'''how to use'''
# init
n_param, n_branch = 16, 4
pad_len = 0
n_parts = 2
n_samples = 256
p_rm_ob_enc = 0
p_rm_ob_rcl = 0
n_rm_fixe... | 1,809 | 812 |
def lateRide(n):
hours = n // 60
minutes = n % 60
return (hours // 10) + (hours % 10) + (minutes // 10) + (minutes % 10)
| 133 | 65 |
"""
Custom exceptions
"""
from __future__ import annotations
__all__ = [
"AlreadyRegistered",
"ConsumerError",
"EventBusError",
"UnknownEvent",
]
class EventBusError(Exception):
"""
Base of exceptions raised by the bus.
"""
class UnknownEvent(EventBusError):
"""
Raised when an r... | 704 | 210 |
from sparse_ct.tool import plot_grid
from sparse_ct.data import image_to_sparse_sinogram
from sparse_ct.reconstructor_2d import (
IRadonReconstructor,
SartReconstructor,
SartTVReconstructor,
DgrReconstructor,
SartBM3DReconstructor)
import logging
logging.basicConfig(
filename='dgr_example_32_... | 9,580 | 3,410 |
from pathlib import Path
from typing import Optional
from starlette.config import Config
from starlette.datastructures import CommaSeparatedStrings
from ..models.pydantic.database import DatabaseURL
p: Path = Path(__file__).parents[2] / ".env"
config: Config = Config(p if p.exists() else None)
DATABASE: str = confi... | 1,340 | 476 |
fruit = str(input())
day_of_the_week = str(input())
quantity = float(input())
price = 0
if fruit == 'banana' or \
fruit == 'apple' or \
fruit == 'orange' or \
fruit == 'grapefruit' or \
fruit == 'kiwi' or \
fruit == 'pineapple' or \
fruit == 'grapes':
if day_of_the_... | 1,607 | 557 |
import unittest
from trajectories.dynamic_time_warper import *
from trajectories.trajectory import Trajectory
from trajectories.point import Point
class TestDTW(unittest.TestCase):
def test_1D_DTW(self):
t1 = [1,2,2,10,2,1]
t2 = [3,3,5,5,2]
self.assertEqual(45, dtw(t1, t2, -1, metricI))
... | 1,368 | 583 |
while True:
h1,m1,h2,m2=map(int,input().split())
i=f=0
if m1+m2+h1+h2==0:break
if h1==0:i=(24*60)+m1
else:i=(h1*60)+m1
if h2==0:f=(24*60)+m2
else:f=(h2*60)+m2
print(f-i) if f>i else print((24*60)-(i-f))
| 235 | 142 |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.shortcuts import render
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.db.models import Count
from django.template import RequestContext
from django.views.decorators.csrf import csrf_exempt
from django.htt... | 4,820 | 1,521 |
import datetime
from ..databases.postgresql import session
from ..models.bookmark_model import Bookmark
# Select one
async def select_one(user_id: int, post_id: int):
bookmark = session.query(Bookmark).filter(Bookmark.user_id == user_id, Bookmark.post_id == post_id).first()
return bookmark
# Insert
async def ... | 1,022 | 338 |
#!/usr/bin/python3
#
# User management application
#
"""
六、用python写一个cgi程序,功能如下:
1. 查询用户 (get)
2. 创建用户 (post)
3. 修改用户 (post)
4. 删除用户 (post)
要点:
1. 通过变量 REQUEST_METHOD 来判断是get还是post
2. 通过变量 QUERY_STRING 来判断是创建还是修改还是删除
3. 通过subprocess.getoutput, 或者os.system 来运行shell命令
4. 相关命令如下:
... | 3,326 | 1,274 |
bl_info = {
"name": "Universal Exporter",
"category": "Import & Export",
}
import bpy
class Export(bpy.types.Operator):
"""Export blender project"""
bl_idname = "object.export_scene"
bl_label = "Export Blender Scene"
bl_options = {'REGISTER', 'UNDO'}
def execute(self, context):
s... | 1,979 | 525 |
import random
# Parameters
states_num: int = 900
trans_per_state: int = 3
transitions_num: int = trans_per_state * states_num
num_non_zero_start_probs: int = 2
emit_range: int = 20
file_name: str = "random_" + \
str(states_num) + "_" + str(transitions_num) + "_" + \
str(emit_range) + "_" + str(num_non_zero_st... | 2,024 | 727 |
# Given a string which consists of lowercase or uppercase letters, find the length of the longest palindromes that can be built with those letters.
#
# This is case sensitive, for example "Aa" is not considered a palindrome here.
#
# Note:
# Assume the length of given string will not exceed 1,010.
#
#
# Example:
... | 1,764 | 622 |
from django.apps import AppConfig
class GetpaidRestConfig(AppConfig):
name = "getpaid_rest_framework"
| 108 | 35 |
import socketio
import socketio
sio = socketio.Client()
@sio.event
def connect():
print('connection established')
@sio.event
def my_message(data):
print('message received with ', data)
sio.emit('my response', {'response': 'my response'})
@sio.event
def disconnect():
print('disconne... | 392 | 142 |
import requests
import requests_cache
requests_cache.install_cache()
from ricecooker.config import LOGGER
STUDIO_URL = 'https://studio.learningequality.org'
NODES_ENDPOINT = STUDIO_URL + '/api/get_nodes_by_ids_complete/'
LICENSES_LIST_ENDPOINT = STUDIO_URL + '/api/license'
# TODO https://studio.learningequa... | 2,042 | 658 |
# Supostamente não funciona
from aresta import Aresta
from insert import insert_sort
from collections import defaultdict
def kruskal(arestas):
arestas, vertices = insert_sort(arestas, defaultdict())
# Inicializa a árvore de fato
arvore = list()
# vertices terá o número de chaves do dicionário retorna... | 2,163 | 885 |
# coding: utf-8
import sys
__author__ = "Paulo Sérgio dos Santos Araujo"
__license__ = "MIT"
__version__ = "1.0.0"
__email__ = "paulo.araujo [at] splab.ufcg.edu.br"
class Msn:
"""
Essa classe feita para disciplina de Métodos de Software Númericos - UFCG 2018.2
se propõe a encontrar as raízes de uma certa... | 1,983 | 757 |
"""
Project: Data Types Notes
Author: Mr. Buckley
Last update: 8/25/2018
Description: Goes over comments, int, float, str, and type casting
"""
# *** COMMENTS ***
# This is a comment (with a "#")
# Comments are only for the user's eyes, the program doesn't read them.
# Describe what sections of code do with... | 1,096 | 388 |
import os
import zarr
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.utils.data import DataLoader
from torch.utils.data import Dataset
from tqdm import tqdm, trange
class FaceDataset(Dataset):
def __init__(self, path, transforms=None):
self.path = path
self.keys = (... | 3,812 | 1,304 |
import os
import scrapy
from pepper.items import PepperItem
class PepperSpider(scrapy.Spider):
name = 'pepper'
start_urls = ['https://blog.drpepper.com.br']
def parse(self, response):
images = response.xpath(
'.//img[contains(@class,"size-full")]'
)
images += respons... | 1,066 | 320 |
# Copyright 2021 UW-IT, University of Washington
# SPDX-License-Identifier: Apache-2.0
from django.test import TestCase
from django.test.client import Client
from django.test.utils import override_settings
import simplejson as json
from spotseeker_server.models import Spot, SpotExtendedInfo
from spotseeker_server.org_... | 4,334 | 1,338 |
__all__ = ["des"] | 17 | 8 |
from spotdl.metadata.providers.spotify import ProviderSpotify
from spotdl.metadata.providers.youtube import ProviderYouTube
from spotdl.metadata.providers.youtube import YouTubeSearch
| 185 | 50 |
from math import floor
class Integer:
def __init__(self, value):
self.value = value
@classmethod
def from_float(cls, float_value):
if isinstance(float_value, float):
return cls(floor(float_value))
else:
return 'value is not a float'
@classmethod
d... | 1,476 | 479 |
import datetime
from typing import Optional
from pydantic import BaseModel
class TokenBase(BaseModel):
access_token: str
class Token(TokenBase):
refresh_token: str
class TokenData(BaseModel):
username: Optional[str] = None
class VerificationToken(BaseModel):
user_id: int
exp: datetime.datet... | 324 | 96 |
import json
from urllib.request import urlopen
import requests
from bs4 import BeautifulSoup
def get_sti():
# https://github.com/hongtaocai/googlefinance
return '<a href="https://chart.finance.yahoo.com/t?s=%5eSTI&lang=en-SG®ion=SG&width=300&height=180" >'
def get_fx():
url = 'https://eservices.mas.... | 1,988 | 899 |
# -*- coding: utf-8 -*-
#
# Copyright (c) 2017~2999 - cologler <skyoflw@gmail.com>
# ----------
#
# ----------
from .common import LifeTime, IServiceProvider, ICallSiteResolver
from .descriptors import CallableDescriptor
class CallSiteResolver(ICallSiteResolver):
def __init__(self, service_provider: IServiceProvi... | 637 | 197 |
from joblib import Memory
cachedir = "cache"
memory = Memory(cachedir, verbose=10)
# @memory.cache
def filter_ff_stories(books, max_rating, min_words, max_words, min_chapters, max_chapters, max_books):
print("filtering ff stories")
ratings = {"K":1, "K+":2, "T":3, "M":4, "MA":5 }
rating_number = ratings... | 1,124 | 362 |
import sys
import helpers.printer
import helpers.parser
import helpers.config
import program.obfuscation
import program.bypass
modes = helpers.config.Modes
bypass_methods = helpers.config.BypassMethods
obfuscation_methods = helpers.config.ObfuscationMethods
printer = helpers.printer.Printer()
parser = helpers.parser.... | 2,167 | 649 |
import torch
import torchvision
import torchvision.transforms as transforms
from torch.utils.data.sampler import SubsetRandomSampler
from torch.utils.data import DataLoader
import os
path = os.path.abspath(__file__)
dir_path = os.path.dirname(path)
resnet_18_default = 224
def _get_dataset(resize=resnet_18_default):
... | 1,169 | 429 |
from scipy import io
import numpy as np
import random
import tensorflow as tf
class_num = 10
image_size = 32
img_channels = 3
def OneHot(label,n_classes):
label=np.array(label).reshape(-1)
label=np.eye(n_classes)[label]
return label
def prepare_data():
classes = 10
data1 = io.loadmat('./data/... | 3,680 | 1,556 |
"""
User models module
"""
from sqlalchemy import Column, Integer, String
from app.models import Base
class User(Base):
"""User class"""
id: int = Column(Integer, primary_key=True, index=True)
firstname: str = Column(String(50), nullable=False, index=True)
lastname: str = Column(String(50), nullabl... | 530 | 177 |
from pathlib import Path
from fhir.resources.valueset import ValueSet as _ValueSet
from oops_fhir.utils import ValueSet
from oops_fhir.r4.code_system.v3_role_code import v3RoleCode
__all__ = ["ParentRelationshipCodes"]
_resource = _ValueSet.parse_file(Path(__file__).with_suffix(".json"))
class ParentRelationsh... | 782 | 254 |
counter = 0
interpolations = None
padding = None
def AddCounter(tag):
global counter
#print("\nSetting:\n" +tag +": " + str(counter) + "\n")
counter += 1
def SetPad(pad):
global padding
padding = pad
def GetPad():
global padding
return padding
| 253 | 88 |
"""Code related to ``django-plugins``.
First, it creates a ``ProjectAppPluginPoint`` for the ``bgjobs`` app.
Second, it creates a new plugin point for the registering ``BackgroundJob``
specializations.
"""
from djangoplugins.point import PluginPoint
from projectroles.plugins import ProjectAppPluginPoint
from .urls ... | 1,540 | 438 |
import discord as nextcord
import asyncio
from discord.ext import commands
import json
import time
import typing
def log(*,text):
...
class AutoMod(commands.Cog):
def __init__(self,bot):
self.bot=bot
self._cd = commands.CooldownMapping.from_cooldown(5, 5, commands.BucketType.membe... | 4,562 | 1,463 |
# Adam
# A program that reads in a text
# file and outputs the number of e's it contains
# The program takes the filename from
# an argument on the command line.
# I found information on this website:
# https://www.sanfoundry.com/python-program-read-file-counts-number/
#fname = input("Enter file name: ")
#l = input(... | 960 | 315 |
""" Tests for tinypages build using sphinx extensions """
from os.path import (join as pjoin, dirname, isdir)
import sphinx
SPHINX_ge_1p5 = sphinx.version_info[:2] >= (1, 5)
from sphinxtesters import PageBuilder
HERE = dirname(__file__)
PAGES = pjoin(HERE, 'tinypages')
from texext.tests.test_plotdirective import f... | 3,936 | 1,214 |
import logging
from django.core.exceptions import ObjectDoesNotExist
from django.db import transaction
from django.http import HttpRequest
from rest_framework.exceptions import NotFound
from rest_framework.test import APIRequestFactory
from rest_framework.views import exception_handler, APIView
from typing import List,... | 3,708 | 1,058 |
S = input()
arr = []
now = []
counter = 0
for s in S:
now.append(s.lower())
if s.isupper():
if counter == 0:
counter += 1
else:
arr.append(''.join(now))
now = []
counter = 0
arr.sort()
for word in arr:
for i, s in enumerate(word):
if i ... | 436 | 150 |
from lesson12_projects.house3.data.const import E_TURNED_KNOB, MSG_TURN_KNOB, E_FAILED
class OutState:
def update(self, req):
self.on_entry(req)
# 入力
msg = self.on_trigger(req)
# 外に居ます。 'Turn knob' とメッセージを送ってくるのが正解です
if msg == MSG_TURN_KNOB:
self.on_turned_kn... | 738 | 289 |
# -*- coding: utf-8 -*-
"""setup.py"""
import os
import sys
from setuptools import setup
from setuptools.command.test import test as TestCommand
class Tox(TestCommand):
user_options = [('tox-args=', 'a', 'Arguments to pass to tox')]
def initialize_options(self):
TestCommand.initialize_options(self)
... | 2,171 | 722 |
from sys import stdin, stdout
from struct import pack, unpack
def float2half(float_val):
f = unpack('I', pack('f', float_val))[0]
if f == 0: return 0
if f == 0x80000000: return 0x8000
return ((f>>16)&0x8000) | ((((f&0x7f800000)-0x38000000)>>13)&0x7c00) | ((f>>13)&0x03ff)
def half2float(h):
if h ==... | 2,266 | 913 |
from config import *
from template import *
from dictasobject import DictAsObject
class RemoteFileHelper:
def __init__(self, service):
self.service = service
self.config = DictAsObject({
'ini' : self.config_ini,
'parser' : self.config_parser,
'shellvars' : self.config_shellvars,... | 2,234 | 664 |
import os
import torch
import torch.nn as nn
import torch.optim as optim
from torch.utils.tensorboard import SummaryWriter
from tqdm import tqdm
import matplotlib.pyplot as plt
import architecture.default
from architecture.default import Defender
DEBUG=False
BATCH_SIZE=32
FIXED_POLICY=False
NORMALIZE=False
K=10
PENAL... | 4,400 | 1,458 |
import pygame
import random
from time import sleep
white = (255, 255, 255)
black = (0, 0, 0)
red = (255, 0, 0)
green = (0, 255, 0)
blue = (0, 0, 255)
pygame.init()
largura = 320
altura = 320
fundo = pygame.display.set_mode((largura, altura))
pygame.display.set_caption("TicTacToe")
def texto(msg, cor, tam, x, y):
... | 7,785 | 3,049 |
#/usr/bin/env python
# -*- coding: Utf8 -*-
import event
class Plugin:
def __init__(self, client):
self.client = client
self.notices = {}
#:nisay!~nisay@53.ip-192-99-70.net PRIVMSG #testbobot :!notice user message
@event.privmsg()
def get_notice(self, e):
target = e.values['t... | 2,332 | 702 |
"""
Copyright (C) 2012 Alan J Lockett
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute,... | 5,794 | 1,793 |
nome = str(input('Digite seu nome completo: ')).strip()
if 'silva' in nome.lower():
print('Sim, seu nome tem Silva.')
else:
print('Não , seu nome não tem Silva') | 169 | 57 |
"""empty message
Revision ID: 8b664608a7c7
Revises: ec21e19825ff
Create Date: 2021-06-01 14:37:20.327189
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '8b664608a7c7'
down_revision = 'ec21e19825ff'
branch_labels = None
depends_on = None
def upgrade():
# ... | 1,527 | 608 |
from django.shortcuts import render
from django.http import HttpResponse
from django.template import loader
from .models import Location,Category,Image
def index(request):
'''Main view function for the start page'''
images = Image.get_images()
template = loader.get_template('index.html')
context = {
... | 1,393 | 365 |
x = (input("enters hours"))
y = (input("enters rate"))
def compute_pay(hours, rate):
"""The try block ensures that the user enters a
value between from 0-1 otherwise an error message pops up"""
try:
hours = float(x)
rate = float(y)
if hours <= 40:
pay= float(hours * rate... | 509 | 174 |
# import argparse
#
#
# def main(audio_path, textgrid_path, output_path):
# data = list()
# for
# print(1)
#
# if __name__ == "__main__":
# # -------------MENU-------------- #
# # command line arguments
# parser = argparse.ArgumentParser()
# parser.add_argument("audio_path", help="The path t... | 628 | 199 |
import phonenumbers
from phonenumbers import geocoder, carrier
def get_information_about_number(phone_numbers):
number = phonenumbers.parse(phone_numbers, "en")
phone_location = geocoder.description_for_number(number, "en")
phone_carrier = carrier.name_for_number(number, "en")
print("The Locat... | 557 | 182 |
# TODO: 1. Add indicator that node should be run by python
# line above indicates that python is responsible for running this node
import os
import csv
import rospy
import numpy as np
import pygame
from utilities import pipline
import cv2
from cv_bridge import CvBridge, CvBridgeError
from sensor_msgs.msg import Im... | 3,494 | 1,005 |
# -*- coding: utf-8 -*-
# Generated by Django 1.11 on 2018-02-01 23:04
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('rest', '0011_auto_20180201_2256'),
]
operations = [
migrations.RenameModel(
... | 393 | 153 |
import logging
import os
import json
import requests
try:
from alerta.plugins import app # alerta >= 5.0
except ImportError:
from alerta.app import app # alerta < 5.0
from alerta.plugins import PluginBase
LOG = logging.getLogger('alerta.plugins.beacon')
BEACON_HEADERS = {
'Content-Type': 'applicati... | 2,669 | 839 |
"""The abstract class module for all hosts."""
# Standard Library Imports
from abc import ABC, abstractmethod, abstractclassmethod
# Third Party Imports
# Local Application Imports
from util.helpers import get_typeof_repo_names
from util.message import Message
class Host(ABC):
"""The abstract class for all host... | 5,542 | 1,505 |
from sqlalchemy import (
Column,
Integer,
String,
DateTime,
)
from .models import Base
class RewardManagerTransaction(Base):
__tablename__ = "reward_manager_txs"
signature = Column(String, nullable=False, primary_key=True)
slot = Column(Integer, nullable=False)
created_at = Column(DateT... | 488 | 159 |
from nonebot import on_command, CommandSession,permission as perm
import asyncio
import traceback
from helper import getlogger,msgSendToBot,CQsessionToStr,data_read,data_save
from module.roll import match_roll
logger = getlogger(__name__)
__plugin_name__ = 'ROLL骰'
__plugin_usage__ = r"""
roll命令
"""
#预处理
def headdeal(se... | 2,326 | 930 |
import time
import requests
# Http endpoint
cur = time.time()
print(requests.post("http://127.0.0.1:8000/my-dag", json=["5", [1, 2], "sum"]).text)
print(f"Time spent: {round(time.time() - cur, 2)} secs.")
# Http endpoint
cur = time.time()
print(requests.post("http://127.0.0.1:8000/my-dag", json=["1", [0, 2], "max"]).... | 384 | 169 |
# Generated by Django 3.0.5 on 2020-04-26 09:09
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
("companyprofile", "0007_company_created_date"),
("careeropportunity", "0014_auto_20191031_1239"),
]
operatio... | 697 | 227 |
import os
import os.path
import logging
import sys
import IValidator
import re
sys.path.append(os.path.abspath(os.path.join('0', '../extensions')))
from extensions_logging import logmyerror
class Email_Validate(IValidator.IValidator):
def formValidate_BSL(self,email):
try:
regex_emailCheck = r... | 790 | 225 |
from django.contrib import admin
from psmate.models import News
class BlogAdmin(admin.ModelAdmin):
prepopulated_fields = {'slug': ('title',)}
admin.site.register(News, BlogAdmin)
| 188 | 61 |
# coding:utf-8
import re
from Helper.common import *
class APIUsagePatternSearcher:
def __init__(self, OPTIONS, custom_args, numOfRecs):
self.OPTIONS = OPTIONS
self.custom_args = custom_args
self.numOfRecs = numOfRecs
def searchAPIUsagePatterns(self):
# Collect in allProjects ... | 4,706 | 1,296 |
class Solution:
# @param {string} s
# @return {string[]}
def restoreIpAddresses(self, s):
if not s or len(s) < 4: return []
res = []
cur = []
self.helper(s, res, cur, 0)
return res
def helper(self, s, res, cur, level):
if level == 4:
i... | 873 | 307 |
while True :
n = int(input())
if n == 0 :
break
else :
arr = input().split()
check = True
for i in range(n) :
if int(arr[int(arr[i]) - 1]) != i + 1 :
check = False
if check :
print('ambiguous')
else :
print('... | 335 | 102 |
"""Add-On functions for speech interface."""
from __future__ import annotations
from typing import TYPE_CHECKING, List
from voiceassistant.addons.create import Addon, CoreAttribute, addon_begin, addon_end
from voiceassistant.exceptions import IntegrationError
from .base import Integration
if TYPE_CHECKING:
fro... | 2,140 | 714 |
from math import cos, sin
import numpy as np
import tensorflow as tf
from .....simulator import Agent
# from simulator import Agent
tf.set_random_seed(1234)
class TensorflowNoveltyDetector(Agent):
def execute(self, action):
raise NotImplementedError()
def __init__(self, world, learning=True, x=0.0,... | 4,602 | 1,388 |
from __future__ import print_function
import os
import sys
from errno import ENOENT
from os.path import dirname, abspath, join, isdir
from setuptools import setup, find_packages
from distutils.command.upload import upload
from pywincffi import __version__
try:
WindowsError
except NameError:
WindowsError = ... | 4,093 | 1,207 |
import shutil
with open('test.csv', 'r') as f:
lines = f.readlines()
for line in lines:
image, gender = line.split(",")
print(image)
if 'female' in gender:
shutil.move("test/" + image, "test/female/" + image)
else:
shutil.move("test/" + image, "test/male/... | 331 | 110 |
import random
from helpers import Leaf, Rect, RoomList
from renderer import MapRenderer
from typing import List, Any
class BSPTree:
def __init__(self):
self.level: List = []
self.room: object = None
self._leafs: List = []
self.MAX_LEAF_SIZE: int = 32
self.ROOM_MAX_SIZE: int... | 2,941 | 1,019 |
class Exporter:
# Extensions for output files
FILE_EXT = ".txt"
PLOTS_FILE_EXT = ".pdf"
"""Exporter: Exports statistical data captured from YCSB output to a file."""
def __init__(self, stats_set):
"""__init__
:param stats_set: StatisticsSet object containing data to be export... | 1,382 | 367 |
# This an autogenerated file
#
# Generated with CRSAxialFrictionModel
from typing import Dict,Sequence,List
from dmt.entity import Entity
from dmt.blueprint import Blueprint
from .blueprints.crsaxialfrictionmodel import CRSAxialFrictionModelBlueprint
from typing import Dict
from sima.sima.moao import MOAO
from sima.si... | 4,387 | 1,267 |