code stringlengths 1 199k |
|---|
from __future__ import print_function
import sys
import json
from datetime import datetime, timedelta
from time import time, sleep
from pymongo import MongoClient, ASCENDING
from vnpy.trader.vtObject import VtBarData
from vnpy.trader.app.ctaStrategy.ctaBase import MINUTE_DB_NAME
from vnpy.trader.gateway.tkproGateway.Da... |
from flask.ext.wtf import Form
from models import User
from wtforms import StringField, PasswordField, validators
class RegistrationForm(Form):
first_name = StringField('First Name', [validators.Length(min=4, max=25)])
last_name = StringField('Last Name', [validators.Length(min=4, max=25)])
email = StringF... |
import math
import random
def test():
tmp1 = []
tmp2 = []
print('build')
for i in xrange(1024):
tmp1.append(chr(int(math.floor(random.random() * 256))))
tmp1 = ''.join(tmp1)
for i in xrange(1024):
tmp2.append(tmp1)
tmp2 = ''.join(tmp2)
print(len(tmp2))
print('run')
for i in xrange(2000):
res = tmp2.enco... |
import os
from setuptools import setup, find_packages
with open(os.path.join(os.path.dirname(__file__), 'README.rst')) as readme:
README = readme.read()
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
setup(
name='drf-generators',
version='0.5.0',
description='Generate DRF... |
from test_framework.test_framework import NavCoinTestFramework
from test_framework.cfund_util import *
import time
class CommunityFundPaymentRequestStateTest(NavCoinTestFramework):
"""Tests the state transition of payment requests of the Community fund."""
def __init__(self):
super().__init__()
... |
import json
import requests
class HttpRequestable(object):
def __init__(self):
super(HttpRequestable, self).__init__()
def post(self, url, data):
r = requests.post(url, data=data)
if r.status_code != requests.codes.ok:
r.raise_for_status()
response = r.json()
... |
"""
Copyright (c) 2006-2015 sqlmap developers (http://sqlmap.org/)
See the file 'doc/COPYING' for copying permission
"""
import re
from lib.core.enums import HTTP_HEADER
from lib.core.settings import WAF_ATTACK_VECTORS
__product__ = "Anquanbao Web Application Firewall (Anquanbao)"
def detect(get_page):
retval = Fal... |
from __future__ import print_function
import os
import sys
from collections import namedtuple
from MPLSinventory.regexstructure import RegexStructure
from MPLSinventory.tools import search, search_all
from MPLSinventory.ip_address_tools import IPv4Address
"""Module that provides classes to analyse and store the output ... |
import CatalogItem
from CatalogAccessoryItemGlobals import *
from toontown.toonbase import ToontownGlobals
from toontown.toonbase import TTLocalizer
from toontown.toon import ToonDNA
import random, types
from direct.showbase import PythonUtil
from direct.gui.DirectGui import *
from pandac.PandaModules import *
class Ca... |
from __future__ import absolute_import, unicode_literals
from django.conf.urls import url
from .views import AuthRegisterUser, Status, Event
from ..users.models import User
from rest_framework_jwt.views import obtain_jwt_token, refresh_jwt_token, verify_jwt_token
urlpatterns = [
url(r'^jwt/login/', obtain_jwt_token... |
import os
import logging
import numpy as np
from argparse import ArgumentParser
from time import clock
from gensim import corpora, models
MODELS_DIR = "../../Data/models/lda_standard"
default_num_topics = 6
default_num_iterations = 1000
default_num_passes = 2
rand_state = 2
logging.basicConfig(format='%(asctime)s : %(l... |
import os
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
def readme():
try:
with open(os.path.join(os.path.dirname(__file__), 'README.md')) as f:
return f.read()
except Exception:
return ''
setup(
name='jjaljup',
version='0.0.7'... |
"""
class VelocityField
"""
import sys
import numpy as np
import netCDF4
class VelocityField:
"""
Data file
Loads the input file with the NetCFD (.nc)
format or a Tecplot format (.dat);
initialize the variables.
:param file_path: file path
:type file_path: str
:param time_step: current ... |
import email.utils
from email.message import Message
message = """Hello,
This is a test message from Chapter 12. I hope you enjoy it!
-- Anonymous"""
msg = Message()
msg['To'] = 'recipient@example.com'
msg['From'] = 'Test Sender <sender@example.com>'
msg['Subject'] = 'Test Message, Chapter 12'
msg['Date'] = email.util... |
from sklearn import datasets
iris = datasets.load_iris()
from sklearn.naive_bayes import GaussianNB
gnb = GaussianNB()
y_pred = gnb.fit(iris.data, iris.target).predict(iris.data)
print("Number of mislabeled points out of a total %d points : %d" % (iris.data.shape[0],(iris.target != y_pred).sum())) |
import os
import sys
import json
import shutil
import hashlib
import resource
import datetime
import getpass
from .config import load_config, save_config, __config
from .objects import init_database, open_database
from .error import RelFsError
_version_numbers= (0,1,0)
def _mkdir_p(os_path):
try: os.makedirs(os_pat... |
import unicodecsv
import datetime
import shutil
import os
import FileDetails
def write_databases(unsucky_events):
create_backups()
channel_data = get_channel_data(unsucky_events)
write_USEvents(unsucky_events)
write_Channels(channel_data)
def create_backups():
backup_path = FileDetails.DATA_DIR + '/' + F... |
from run_clang import test_input
import sys
SANITY_CHECKS = True
def remove_elem_iter(data, pred):
'''Remove one element from the data, which may be a list or a string.
If pred is still true for the reduced data, accept it. Repeat
until minimal. Yield progressively minimized results.'''
if SANITY_CHECKS... |
from shared import *
from radio_observations import *
from accelerometer_observations import *
from accelerometer_events import *
from interaction_periods import *
from interaction_totals import *
from sensor_mappings import *
from areas import *
from materials import *
from classrooms import *
from camera_data import ... |
"""Utilities for use by assessment package implementations"""
import importlib
from dlkit.abstract_osid.osid.errors import NotFound, NullArgument, IllegalState
from dlkit.abstract_osid.assessment.objects import Assessment as abc_assessment
from ..utilities import get_provider_manager, JSONClientValidated
from dlkit.pri... |
import itertools
import js2c
import multiprocessing
import optparse
import os
import random
import re
import shutil
import signal
import string
import subprocess
import sys
import time
FILENAME = "src/runtime.cc"
HEADERFILENAME = "src/runtime.h"
FUNCTION = re.compile("^RUNTIME_FUNCTION\(Runtime_(\w+)")
ARGSLENGTH = re.... |
print( "Let's Practice Everything." )
print( "You'd need to know \'bout escapes with \\ that do \n newlines and \t tabs." )
poem = """
\tThe lovely world
with logic so firmly planted
cannot discern \n the needs of love
nor comprehend passion from intuition
and requires an explanation
\n\t\twhere there is none.
"""
pr... |
"""
Cursor tool
A cursor tool lets you drag vertical and horizontal lines whose intersection
defines one point on the plot.
Left-button drag to move the cursors round.
Right-drag to pan the plots. 'z'-key to Zoom
"""
import numpy
from chaco.api import create_line_plot, OverlayPlotContainer, \
HPlotContaine... |
import requests as req
import traceback
from flask import request
class Mail(object):
API_URL = 'https://api.mailgun.net/v3/{domain}/messages'
def ___init__(self, app):
"""Initialization of app
:param app: {Flask}
"""
if app:
self.init_app(app)
def init_app(self, ... |
__author__ = 'qiudebo'
import matplotlib.pyplot as plt
if __name__ == '__main__':
# 在坐标系 画一长方形状
left, width = .25, .5
bottom, height = .25, .5
right = left + width
top = bottom + height
# polar 极坐标
ax = plt.gca()
# rotation 旋转角度
p = plt.Rectangle((left, bottom), width, height, Fill=F... |
import unittest
import unittest.mock
import etl.commands
class TestCommands(unittest.TestCase):
def test_execute_or_bail_ok(self):
"""Make sure context runner exits cleanly."""
with self.assertLogs(level="INFO") as cm:
with etl.commands.execute_or_bail("unittest"):
pass
... |
"""s3bot command line tool abstraction."""
import s3bot.freeze
from s3bot.s3_interface import S3Wrapper
freeze = s3bot.freeze.freeze
def ls(**kwargs):
"""List the contents of the default bucket, with prefixes in the
args."""
s3 = S3Wrapper()
contents = dict((arg, '') for arg in kwargs["prefix"])
if ... |
"""
Django settings for example project.
Generated by Cookiecutter Django Package
For more information on this file, see
https://docs.djangoproject.com/en/1.9/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.9/ref/settings/
"""
import os
BASE_DIR = os.path.dirname... |
import pygame
import pymunk
from .base_shape import BaseShape
from .util import to_pygame
class Ball(BaseShape):
def __init__(self, space, x, y, radius, mass, static, cosmetic=False):
if not cosmetic:
moment = pymunk.moment_for_circle(mass, 0, radius)
if static:
self.... |
from pyparsing import *
import os.path as pth
from collections import namedtuple
import collections
Entry = namedtuple("Entry", "description path section")
def loadguard(function):
def wrapper(*args, **kwargs):
if not args[0].loaded:
args[0].load()
return function(*args, **kwargs)
return wrapper
class Bundle(c... |
from read_data import readData
from tools import *
from math import log
from collections import defaultdict
import wordSimilarity
import pandas as pd
import re
import pickle
from random import randrange
import requests
from ast import literal_eval
import random
import codecs
import csv
def runMeta(book, sentences, wsen... |
import tempfile
from fabric.api import put, sudo
from shuttle.services.service import Service
from shuttle.hooks import hook
from shuttle.shared import apt_get_install, pip_install, chown
class Memcached(Service):
name = 'memcached'
script = 'memcached'
DEFAULT_SETTINGS = {
'-d': None,
'logf... |
__author__ = 'Cedric'
from .BuyingPolicy import BuyingPolicy
from .ChancePolicy import ChancePolicy
from .AuctionPolicy import AuctionPolicy
from .HousingPolicy import HousingPolicy
from .SellingPolicy import SellingPolicy
from .UnmortgagePolicy import UnmortgagePolicy
from .JailPolicy import JailPolicy
from .DealPolic... |
t = (0, 1, 2)
print(t)
print(type(t))
print(t[0])
print(t[:2])
t_add = t + (3, 4, 5)
print(t_add)
print(t)
print(t + tuple([3, 4, 5]))
print(t + (3,))
l = list(t)
print(l)
print(type(l))
l.insert(2, 100)
print(l)
t_insert = tuple(l)
print(t_insert)
print(type(t_insert))
l = list(t)
l[1] = 100
t_change = tuple(l)
print(... |
import _plotly_utils.basevalidators
class SideValidator(_plotly_utils.basevalidators.EnumeratedValidator):
def __init__(
self,
plotly_name="side",
parent_name="scatterternary.marker.colorbar.title",
**kwargs
):
super(SideValidator, self).__init__(
plotly_name=... |
import scrapy
import hashlib
import json
import re
import random
from locations.items import GeojsonPointItem
day_formats = {
"MON": "Mo",
"TUES": "Tu",
"WED": "We",
"THURS": "Th",
"FRI": "Fr",
"SAT": "Sa",
"SUN": "Su"
}
class BathAndBodyWorksSpider(scrapy.Spider):
name = "bathandbodywor... |
r"""Control flow plumbing.
Every component is directional, with some set of inputs and outputs.
To push some input into a component, call 'send'.
To iterate over possible inputs, call 'next'.
"""
def nada(*args, **kwargs):
pass
class Component(object):
r"""Base component."""
def pass_in(self, input):
... |
total = 0
for i in range(21):
if i%2 == 0:
total += i
else:
if i%5 == 0:
print "Checkpoint: %s" % i
else:
print i
print "%s - Total" % total |
from xlink import XLink
import numpy
import bisect
import copy
import itertools
class Match:
def __init__(self, spec, xlink, mass, param):
self.spec = copy.deepcopy(spec)
self.xlink = xlink
self.param = param
self.mol_weight = self.xlink.mol_weight + self.spec.ch * mass['Hatom']
len1 = self.xlink.pep[0].leng... |
from human_readable_error import HumanReadableError |
from django.db import models
class Account(models.Model):
class Meta:
managed = False
guid = models.CharField(primary_key=True, max_length=32)
name = models.CharField(max_length=2048)
code = models.CharField(max_length=2048, null=True)
description = models.CharField(max_length=2048, null=Tru... |
from stock_analysis.utils import parse_start_end_date, moving_average, find_trend, get_stats_intervals, get_symbol_yahoo_stats, get_symbol_exchange
from stock_analysis.utils import lookup_cik_from_sec, extract_earnings_from_xbrl
from stock_analysis.utils import Command
from stock_analysis.symbol import Symbol
from stoc... |
import sys
import os
from wpbiff import cli
package_folder = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0, package_folder)
if __name__ == '__main__':
sys.exit(cli.main()) |
from datetime import datetime, timedelta
import logging
import traceback
from django.contrib.gis.utils import HAS_GEOIP
if HAS_GEOIP:
from django.contrib.gis.utils import GeoIP, GeoIPException
from django.conf import settings
from django.contrib.auth.models import User
from django.db import models
from django.utils... |
""" File that holds helper functions. """
import numpy as np
def wrap_radian(radian):
""" Wraps an angle measurement in radians to be from -pi to pi. """
while (radian > np.pi):
radian -= 2 * np.pi
while (radian < -np.pi):
radian += 2 * np.pi
return radian
if __name__ == "__main__":
... |
import os
import sys
import hook_utils as hut
def main(commit=-1, *args, **kwargs):
if commit == 'HEAD':
commit = 0
else:
commit = int(commit)
changed_exercises = hut.get_changed_exercises(commit)
changed_tracks = set(track for track, _ in changed_exercises)
for track in changed_trac... |
from datetime import datetime
import os
from django.db import models
from django.db.models import Q
from django.conf import settings
from django.core.cache import cache
from django.core.urlresolvers import reverse
from django.contrib.auth.decorators import login_required
from django.contrib.auth.views import redirect_t... |
"""
Run Regression Test Suite
This module calls down into individual test cases via subprocess. It will
forward all unrecognized arguments onto the individual test scripts, other
than:
- `-extended`: run the "extended" test suite in addition to the basic one.
- `-win`: signal that this is running in a Windows e... |
import sys
import subprocess
from gevent.pywsgi import WSGIServer
def http_response(status_code, content, start_response):
start_response(status_code, [('Content-Type', 'text/html; charset=utf-8')])
return [str(content).encode('utf-8')] if content else []
class App(object):
def __init__(self):
self.... |
"""
deserializers
~~~~~~~~~~~~~
All deserializers supported by our API
"""
from ..deserializers.base import Deserializer as BaseDeserializer
from ..deserializers.comma_sep import Deserializer as CsvDeserializer
from ..deserializers.form_data import Deserializer as FormDataDeserializer
from ..deserializers.f... |
import os
from pathlib import Path
from getenv import env
path = Path(__file__)
import pdb; pdb.set_trace()
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
SECRET_KEY = env('SECRET_KEY')
DEBUG = False
TEMPLATE_DEBUG = DEBUG
ALLOWED_HOSTS = []
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth... |
"""
Exercicio 2 - Lista de exercicios 3 do Curso Python para Zumbis
Faça um programa que leia um nome de usuário e a sua senha e não aceite a senha igual ao
nome do usuário, mostrando uma mensagem de erro e voltando a pedir as informações.
"""
nome = raw_input('Digite o nome de usuário ? ')
senha = nome
whi... |
import sublime, sublime_plugin
import xml.etree.ElementTree as ElementTree
import os
import datetime
import threading
import urllib
from . import requests, context, util
from .progress import ThreadProgress
from .salesforce.lib.panel import Printer
class ReloadSalesforceDocumentCommand(sublime_plugin.WindowCommand):
... |
from mpi4py import MPI
import numpy as np
import sys
def initial_conditions(DTDX, X, Y, comm_col, comm_row):
'''Construct the grid points and set the initial conditions.
X[i,j] and Y[i,j] are the 2D coordinates of u[i,j]'''
assert X.shape == Y.shape
um = np.zeros(X.shape) # u^{n-1} "u minus"
u = np.zero... |
"""
Support for creating GUI apps and starting event loops.
IPython's GUI integration allows interative plotting and GUI usage in IPython
session. IPython has two different types of GUI integration:
1. The terminal based IPython supports GUI event loops through Python's
PyOS_InputHook. PyOS_InputHook is a hook that ... |
from datetime import datetime, timedelta
from flask.json import JSONEncoder as BaseJSONEncoder
def get_current_time():
return datetime.utcnow
def get_current_time_plus(days=0, hours=0, minutes=0, seconds=0):
return get_current_time() + timedelta(days=days, hours=hours, minutes=minutes, seconds=seconds)
class JS... |
from keras.engine.topology import Layer
import keras.backend as K
class SpatialPyramidPooling(Layer):
'''Spatial pyramid pooling layer for 2D inputs.
See Spatial Pyramid Pooling in Deep Convolutional Networks for Visual Recognition,
K. He, X. Zhang, S. Ren, J. Sun
# Arguments
pool_list: list of ... |
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^testresults/$', views.index, name='results_home'),
url(r'^testresults_patient/', views.view_for_patient, name='view test results for patient'),
url(r'^testresults/create/$', views.createResult, name='results_create'),
url(r'^tes... |
import sys
from unittest import TestCase
from unittest import mock
sys.modules["znc"] = mock.MagicMock()
from relay_in import _contains_required_args, _parse_args, _is_valid_module_args
class Test_relay_in(TestCase):
_TEST_ARGS = "--test0=zero --test1=one --test2=two"
_TEST_REQUIRED_ARGS = ["--test0", "--test1"... |
import abc
from . import loading
class BaseFileLoader(abc.ABC):
@abc.abstractmethod
def make_file_id(self, base_path, local_base_path, filename):
pass
@abc.abstractmethod
def load_file(
self,
base_path,
local_base_path,
filename,
file_id,
functions... |
from __future__ import absolute_import
from zope.interface.declarations import provider, implementer
import serialization
from serialization import adapter, base
from .interface import IRestorator, ISerializable
try:
from twisted.python.failure import Failure
except ImportError:
Failure = None
class AdaptedMark... |
import math
from modules.utils import provision_to_tube, printdatetime, det_new_group, thermocycle_ramp
from autoprotocol.pipette_tools import aspirate_source, depth
def assemble(protocol, params):
def provision_reagents(reagents, dest, num_rxts, mm_mult=1.3, num_rxts_plus=3.0):
for reagent in reagents.valu... |
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
import warnings
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model 'PeopleInPovertyState'
db.create_table('data_peopleinpovertystate', (
('id', self.gf('django... |
from BaseHTTPServer import BaseHTTPRequestHandler,HTTPServer
from nap.url import Url
import logging
import os, sys
import requests.packages.urllib3
import threading
import time
import operator
from string import maketrans
requests.packages.urllib3.disable_warnings()
PORT_NUMBER = int(os.environ.get('PORT', 9243))
REFRE... |
from . import forms
def bpm_playlist_form_context(request):
return {'form': forms.BPMPlaylistForm()} |
import time
import math
import sys
import os
from typing import List
from PyQt5.QtMultimedia import QCameraInfo, QCamera, QCameraViewfinderSettings
from PyQt5.QtWidgets import QDialog, QVBoxLayout, QHBoxLayout, QCheckBox, QPushButton, QLabel
from PyQt5.QtGui import QImage, QPixmap
from PyQt5.QtCore import QSize, QRect,... |
def areAnagrams(word1, word2):
"""Return true, if words are anagrams."""
#2. Sort the words.
word1_sorted = sorted(word1) # sorted returns a sorted list
word2_sorted = sorted(word2)
#3. Check that the sorted words are identical.
return word1_sorted == word2_sorted
print "Anagram Test"
twoWord... |
"""
Defines views.
"""
import calendar
import locale
import logging
from operator import itemgetter
from flask import abort, redirect
from flask_mako import render_template
from jinja2 import TemplateNotFound
from mako.exceptions import TopLevelLookupException
from presence_analyzer.main import app
from presence_analyz... |
"""Add brief clarification questions
Revision ID: 580
Revises: 570
Create Date: 2016-02-23 16:53:28.171878
"""
revision = '580'
down_revision = '570'
from alembic import op
import sqlalchemy as sa
def upgrade():
op.create_table('brief_clarification_questions',
sa.Column('id', sa.Integer(), nullable=False),
... |
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.protobuf import symbol_database as _symbol_database
from google.pr... |
import Bank
import Connect_db
class Account(Bank.Bank):
def __init__(self):
Bank.__init__("Graphic Era Bank")
self.acc_type = 's'
self.acc_number = -1
self.balance = 0
self.transactions = 0
def create_account(self, password, account_type, first_name, last_name, contact_nu... |
"""copie de fichiers sur une clé USB, interface fenêtrée"""
import Tkinter as Tk # pour la fenêtre
import selection_file # pour rechercher un répertoire
import copie_usb # version sans fenêtre
import re # pour les expressions régulières
class copie_usb_window (copie_usb.copie_usb):
"""reco... |
import logging
from django.http import HttpRequest
from djblets.db.query import get_object_or_none
from djblets.siteconfig.models import SiteConfiguration
from djblets.webapi.decorators import (webapi_decorator,
webapi_login_required,
webapi_... |
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('oai', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='sources',
name='jnl_active',
field=models.IntegerField(default=1, verbose_name='Acti... |
import os
from r2.lib.translation import I18N_PATH
from r2.lib.plugin import PluginLoader
from r2.lib import js
print 'POTFILE := ' + os.path.join(I18N_PATH, 'r2.pot')
plugins = PluginLoader()
print 'PLUGINS := ' + ' '.join(plugin.name for plugin in plugins
if plugin.needs_static_build)
p... |
from cryptos.electrumx_client import rpc_send_and_wait, rpc_send
host = "electrum.akinbo.org"
port = 50001
method = "blockchain.address.listunspent"
params = ["1AoZAu5Kif5MTkaNWbHiXGdcNEgFGVqDgB"]
rpc_send(host, port, method, params)
print('yes')
import time
time.sleep(2) |
print "234".replace("\r\n", "\n") |
from __future__ import print_function, absolute_import, division, unicode_literals
from strictyaml.ruamel.error import MarkedYAMLError
from strictyaml.ruamel.tokens import * # NOQA
from strictyaml.ruamel.compat import (
utf8,
unichr,
PY3,
check_anchorname_char,
nprint,
) # NOQA
if False: # MYPY
... |
from __future__ import unicode_literals, division, absolute_import, print_function
from datetime import datetime, timedelta
import inspect
import re
import sys
import textwrap
from asn1crypto import x509, keys, crl, pem
from asn1crypto.util import timezone
from oscrypto import asymmetric
from .version import __version_... |
import datetime
import decimal
import uuid
from dateutil.relativedelta import relativedelta
from django.db import transaction
from django.db.models import Sum
from django.http import HttpResponse
from django.utils.translation import ugettext_lazy as _
from django_filters.rest_framework import DjangoFilterBackend
from r... |
import numpy as np
import scipy
import scipy.optimize
def sound_speed(gamma, pressure, density, dustFrac=0.):
"""
Calculate sound speed, scaled by the dust fraction according to:
.. math::
\widetilde{c}_s = c_s \sqrt{1 - \epsilon}
Where :math:`\epsilon` is the dustFrac
"""
scale ... |
"""
本模块中主要包含:
1. 从通联数据下载历史行情的引擎
2. 用来把MultiCharts导出的历史数据载入到MongoDB中用的函数
3. 增加从通达信导出的历史数据载入到MongoDB中的函数
History
<id> <author> <description>
2017050301 hetajen DB[CtaTemplate增加日线bar数据获取接口][Mongo不保存Tick数据][新增数据来源Sina]
2017052500 hetajen DB[增加:5分钟Bar数据的记录、存储和获取]
"""
'''2017052500... |
from msrest.serialization import Model
class ConnectionMonitor(Model):
"""Parameters that define the operation to create a connection monitor.
All required parameters must be populated in order to send to Azure.
:param location: Connection monitor location.
:type location: str
:param tags: Connectio... |
import cv2
import numpy as np
import pickle
from helpers import Helpers
from cells import Cells
class Extractor(object):
'''
Stores and manipulates the input image to extract the Sudoku puzzle
all the way to the cells
'''
def __init__(self, color_img):
self.helpers = Helpers() # Ima... |
import DeepFried2 as df
class RepeatInput(df.Container):
def symb_forward(self, symb_input):
return tuple(module(symb_input) for module in self.modules) |
f = open('helloworld.txt','r')
message = f.read()
print message
f.close() |
def some_function():
print('this is my function')
# return 43 |
"""
Spectrum utilities.
"""
import os
import glob
__all__ = [os.path.basename(m).replace('.py', '')
for m in glob.glob("snspin/spectrum/*.py")
if '__init__' not in m]
if True:
for pkg in __all__:
__import__(__name__ + '.' + pkg) |
import subprocess
import os
import shutil
import re
import urllib
import requests
from db import session
from models import User, Flag
from settings import SA_COOKIE
flag_url = 'http://fi.somethingawful.com/flags/'
image_folder = './images/'
audio_working_folder = './audio/'
def flag_query(where=True):
return sessi... |
from django.contrib.gis import forms, admin
from django.contrib.gis.geos import GEOSGeometry
from django.contrib import messages
from django.core.management import settings
from django.core.exceptions import ObjectDoesNotExist
from django.forms import CharField
from django.forms import ModelForm
from django.forms impor... |
import cabinet.receivers |
__author__ = 'bcaimar' |
import cv2
import urllib2 as u
import numpy as np
import os, sys
from datetime import datetime
from datetime import timedelta
import time
import psutil
import pythonled
import Pipeline
import TargetObservation
import UDPServer
import subprocess
import pyMjpgStreamer
import httplib
import socket
socket.setdefaulttimeout... |
import fidget
import cairoEng
if __name__ == "__main__":
cairoEng.run(fidget.Fidget(), "fidget-sprites.png", fidget.getFrameRect, (171, 151), (-28, -2)) |
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('carts', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='cartitem',
name='line_item_total',
field=m... |
import pandas as pd
import numpy as np
from numpy import fft
import tensorflow as tf
import matplotlib.pyplot as plt
data = pd.read_csv('StockDataWithVolume.csv', index_col='Date', parse_dates=True)
features = ['DJIA', 'S&P', 'Russell 2000', 'NASDAQ', 'VIX', 'Gold']
def fourierEx(x, n_predict, harmonics):
n = len(x... |
import copy
import datetime
import json
import PyQt5
from PyQt5.QtGui import *
from PyQt5.QtCore import *
import PyQt5.QtCore as QtCore
from electroncash import transaction
from electroncash.bitcoin import base_encode
from electroncash.i18n import _
from electroncash.plugins import run_hook
from util import *
dialogs =... |
from basic import *
from amino_acids import amino_acids
from tcr_distances_blosum import blosum
from paths import path_to_db
import translation
cdrs_sep = ';'
gap_character = '.'
all_genes = {}
class TCR_Gene:
def __init__( self, l ):
self.id = l['id']
self.organism = l['organism']
self.chai... |
"""async10gather.py: Use gather
Usage:
async10gather.py
"""
import asyncio
async def factorial(name, number):
f = 1
for i in range(2, number + 1):
print(f"Task {name}: Compute factorial({i})...")
await asyncio.sleep(1)
f *= i
print(f"Task {name}: factorial({i}) = {f}")
def main():
... |
import math
import time
import threading
import Adafruit_CharLCD as LCD
class Line(object):
"""Handles line representation for LCD character display of display_length."""
def __init__(self, s="", display_length=16, delimiter=" *** "):
self.display_length = display_length
self.length = 0
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.