code stringlengths 1 199k |
|---|
__author__ = 'magus0219'
import logging
import hashlib
from tornado.web import authenticated
from .common_handler import CommonHandler
from utils.mongo_handler import mongodb_client
from models.account import Account
import time
from config import INSTANCE_NAME as _INSTANCE_NAME
logger_server = logging.getLogger("Deplo... |
from django.shortcuts import render, HttpResponseRedirect, get_object_or_404
from django.views.generic import (
ListView,
CreateView,
UpdateView,
DeleteView,
View
)
from django.core.urlresolvers import reverse_lazy
from django.core import serializers
from django.http import HttpResponse
from apps.te... |
'''
Load data in parallel with train.py
'''
import time
import math
import numpy as np
import zmq
import pycuda.driver as drv
import pycuda.gpuarray as gpuarray
import hickle as hkl
def get_params_crop_and_mirror(param_rand, data_shape, cropsize):
center_margin = (data_shape[2] - cropsize) / 2
crop_xs = int(rou... |
surnames = ['Rivest', 'Shamir', 'Adleman']
for position in range(len(surnames)):
print(position, surnames[position])
# print(surnames[position][0], end='') # try swapping prints |
from __future__ import print_function, division
import argparse
import multiprocessing
import re
import sys
import xml.etree.ElementTree as ET
from HTMLParser import HTMLParser
class Writer(multiprocessing.Process):
"""writes stuff"""
def __init__(self, oq, filename):
multiprocessing.Process.__init__(se... |
import time
import logging
from selenium import webdriver
from pyvirtualdisplay import Display
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support.ui import WebDriverWait
from seleniu... |
import PyFBA
import argparse
import os
import sys
parser=argparse.ArgumentParser(description='Convert a RAST spreadsheet file to a list of roles')
parser.add_argument('-a', help='RAST spreadsheet (tab-separated text) file')
parser.add_argument('-v', help='verbose', action='store_true')
args = parser.parse_args()
if arg... |
"""Provides a method for fetching Service Configuration from Google Service
Management API."""
from __future__ import absolute_import
import logging
import json
import os
import urllib3
from apitools.base.py import encoding
from ..gen import servicemanagement_v1_messages as messages
from oauth2client import client
from... |
import os
import numpy as np
import matplotlib.pyplot as plt
import sys
print(" # ========== make & load ProbeParticle C++ library ")
LWD = '/home/prokop/git/ProbeParticleModel/code'
sys.path = [ LWD ]
import basUtils
import elements
import GridUtils as GU
import ProbeParticle as PP
print(" ============= RUN ")
print... |
"""Custom TF 'ops' as meant in the TensorFlow definition of ops."""
import numpy as np
import tensorflow as tf
from utils import io_utils
from tensorflow.python.util import nest
def dynamic_sampled_softmax_loss(labels, logits, output_projection, vocab_size,
from_scratch=False, num_sampl... |
from unittest import TestCase
from src.main.fpgavisio import FPGAVisual
__author__ = 'pawel'
class TestFPGAVisual(TestCase):
def test_make_simulation_movie(self):
visualisation = FPGAVisual('../data/final.csv')
visualisation.make_simulation_movie('../data/content.gif')
def test_make_simulation_m... |
"""Calculates Javascript dependencies without requiring Google3.
It iterates over a number of search paths and builds a dependency tree. With
the inputs provided, it walks the dependency tree and outputs all the files
required for compilation.\n
"""
import distutils.version
import json
import logging
import optparse
i... |
import RPi.GPIO as GPIO
import time
def GPIO_On_Off(pinNumber):
# Setup
GPIO.setmode(GPIO.BOARD)
GPIO.setup(pinNumber, GPIO.OUT)
# Turn On
GPIO.output(pinNumber, True)
# Leave on for 5 seconds
time.sleep(0.1)
# Turn off
GPIO.output(pinNumber, False)
# Will Reset the GPIO
GPIO.cleanup()
while True:
GPIO_On_O... |
from .naive import *
from .naive_reverse import *
from .simple_random import *
from .ema import EMAPriceCrossover |
print 'why do you think python is cool?';
answer = raw_input();
print 'your answer is: ', answer, ' is so cool~'; |
import logging
import os
from .version import __version__
LOG = logging.getLogger("pulse")
LOG.level = logging.DEBUG
BUILTIN_ACTIONS_LOADED = False
def loadActionsFromDirectory(startDir):
"""
Search for and load BuildActions from the given directory,
then register them for use.
Args:
startDir: A... |
import collections
from supriya import CalculationRate
from supriya.ugens.UGen import UGen
class IRand(UGen):
"""
An integer uniform random distribution.
::
>>> supriya.ugens.IRand.ir()
IRand.ir()
"""
### CLASS VARIABLES ###
__documentation_section__ = "Noise UGens"
_ordered_... |
from wtforms.widgets import TextArea
class BigTextArea(TextArea):
def __init__(self, *args, **kwargs):
super(BigTextArea, self).__init__()
self.rows = kwargs.get('rows')
self.cols = kwargs.get('cols')
self.css_cls = kwargs.get('css_cls')
self.style_ = kwargs.get('style_')
... |
OAUTH2_PROVIDER = {
'SCOPES': {
'read': 'Read scope',
'write': 'Write scope',
'groups': 'Access to your groups'},
} |
from __future__ import unicode_literals
import platform
def get_os():
system_name = platform.system()
if system_name == 'Linux':
return '{} {} {}'.format(system_name, platform.linux_distribution()[0], platform.linux_distribution()[1])
else:
return '{} {}'.format(system_name, platform.release... |
import datetime
from django.http import Http404, HttpResponseRedirect, HttpResponseForbidden
from django.shortcuts import render, get_object_or_404
from django.contrib.auth import authenticate, login
from django.contrib.auth.decorators import login_required
from django.contrib.admin.views.decorators import staff_member... |
from __future__ import annotations
from .typecheck import *
from .import core
from .import ui
from . import dap
import asyncio
class Watch:
class Expression:
def __init__(self, value: str):
self.value = value
self.message = ""
self.evaluate_response: Optional[dap.Variable] = None
self.on_updated: core.Ev... |
__author__ = 'Călin Sălăgean'
import unittest
class TestPersonController(unittest.TestCase):
def test_index(self):
pass |
import _env
import json
import re
import time
from lib._db import get_collection
from tornado.escape import xhtml_unescape
from judge_upload import exist_or_insert
from config.config import CONFIG
DB = CONFIG.MONGO.DATABASE
PAT = re.compile('[-#\w]+')
def find_first_tag(s):
m = PAT.search(s)
return m.group() if... |
import numpy as np
import os
import six.moves.urllib as urllib
import sys
import tarfile
import tensorflow as tf
import zipfile
import cv2
from distutils.version import StrictVersion
from collections import defaultdict
from io import StringIO
from matplotlib import pyplot as plt
from PIL import Image
from object_detect... |
from __future__ import unicode_literals
import platform
from datetime import datetime
from kgb import SpyAgency
from rbpkg.repository.package_bundle import PackageBundle
from rbpkg.repository.package_channel import PackageChannel
from rbpkg.repository.package_release import PackageRelease
from rbpkg.repository.package_... |
RNA_CODON_TABLE = {
'UUU': 'F', 'CUU': 'L', 'AUU': 'I', 'GUU': 'V',
'UUC': 'F', 'CUC': 'L', 'AUC': 'I', 'GUC': 'V',
'UUA': 'L', 'CUA': 'L', 'AUA': 'I', 'GUA': 'V',
'UUG': 'L', 'CUG': 'L', 'AUG': 'M', 'GUG': 'V',
'UCU': 'S', 'CCU': 'P', 'ACU': '... |
from typing import TYPE_CHECKING
import warnings
from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import HttpRequest, HttpResponse
from azure.mgmt.core... |
from nose.plugins import Plugin
import warnings
import sys
import logging
log = logging.getLogger()
def import_item(name):
"""Import and return ``bar`` given the string ``foo.bar``.
Calling ``bar = import_item("foo.bar")`` is the functional equivalent of
executing the code ``from foo import bar``.
Param... |
"""
Python variables relevant to the Cas9 mutants described by Klienstiver et al. (2015), Nature, doi:10.1038/nature14592
Contains the variables:
PI_domain: string, WT PI domain (AA 1099-1368) from UniProt (http://www.uniprot.org/uniprot/Q99ZW2) + AAs 1097, 1098
PI_sec_structure: dict with format 'type_#' : (st... |
import sys
fn1, fn2 = sys.argv[1:]
def get_diff_lines(fn):
with open(fn) as fh:
return set([line for line in fh
if line.startswith('diffing')])
for fn in get_diff_lines(fn1) - get_diff_lines(fn2):
print(fn.strip()) |
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('productdb', '0034_auto_20200526_1555'),
]
operations = [
migrations.AlterField(
model_name='productlist',
name='string_product_list',
field=models.TextField(... |
import random
import pygame
from pygame.locals import *
class Simulator(object):
def __init__(self, width, height):
pygame.init()
self.screen = pygame.display.set_mode((width,height))
pygame.display.set_caption('Leviosa')
self.objects = {}
# up and down keys
self.k_u ... |
import os
import sys
import numpy as np
import scipy
from scipy import io, misc, sparse
from scipy.linalg import solve_banded
from scipy.ndimage.filters import uniform_filter
from scipy.sparse.linalg import spsolve
from sklearn.preprocessing import normalize
import cartesian
import color_conv
def neighborhood(X, r):
... |
def fortune(binary):
count=0
cur=''
for n in binary:
if cur==n:
count+=1
else:
cur=n
count=1
if count==6:
return "Sorry, sorry!"
else:
return "Good luck!"
if __name__ == "__main__":
print fortune(raw_input()) |
import urllib2, code
import xml.etree.cElementTree as ET
import MySQLdb
import datetime, threading, time
from datetime import datetime
def getOne():
return 1
def getTwo():
return 2
def getThree():
return 3
def timerLoop():
global next_call
print(datetime.datetime.now())
next_call = next_call + 1... |
import _plotly_utils.basevalidators
class TextValidator(_plotly_utils.basevalidators.StringValidator):
def __init__(
self, plotly_name="text", parent_name="scattermapbox.legendgrouptitle", **kwargs
):
super(TextValidator, self).__init__(
plotly_name=plotly_name,
parent_na... |
"""
Wrangles data into the ELMR database
"""
import os
import glob
import json
import elmr
from datetime import datetime
from operator import itemgetter
from elmr.models import SeriesRecord, Series
DATE_FMT = "%B %Y"
JSON_DTE = "%Y-%m-%d"
JSON_FMT = "%Y-%m-%dT%H:%M:%S.%f"
def extract(path):
"""
Extracts timeser... |
from django.http import HttpResponseRedirect
from django.shortcuts import redirect
from django.contrib.auth.decorators import login_required
from .tasks import write_config, kick_services, get_server_status, stop_services, perform_upgrade
from time import sleep
from session.models import Entry, Preset, ServerSetting
fr... |
import sys
import re
from htmlGetter import HtmlGetter
from pattern.web import plaintext
class Html2Article:
def __init__(self):
pass
def html_2_Plaintext(self,html):
#text = re.sub(r"(?is)<.*?>","",html)
text = plaintext(html,keep=[],replace='',linebreaks=1, indentation=False)
#... |
import pyfits
import numpy
import SPARTATools
datapath = '/home/deen/Data/GRAVITY/SPARTA_Data/'
delta = pyfits.getdata(datapath+'delta_junk.fits')
fullNoll = pyfits.getdata(datapath+'ZernikeCovar_Noll.fits')
HOIM = pyfits.getdata(datapath+'HOIM.fits')
TTIM = pyfits.getdata(datapath+'TTIM.fits')
nfilt = 50
nHOAct = 60
n... |
import os
import numpy as np
import pandas as pd
from ogusa import utils
CUR_PATH = os.path.split(os.path.abspath(__file__))[0]
def get_wealth_data(scf_yrs_list=[2019, 2016, 2013, 2010, 2007], web=True,
directory=None):
'''
Reads wealth data from the 2007, 2010, 2013, 2016, and 2019 Survey o... |
from django.db import models
from django.contrib.auth.models import (
BaseUserManager, AbstractBaseUser, PermissionsMixin
)
from django.core.mail import send_mail
from django.utils.translation import ugettext_lazy as _
from django.utils import timezone
from django.core.exceptions import ImproperlyConfigured
from dj... |
from datetime import datetime
def base_time():
return datetime(1970, 1, 1) |
from datetime import datetime
from django.db import models
from members.models import Person
from django.core.mail import send_mail
class Booking(models.Model):
date = models.DateField()
time = models.TimeField()
court = models.PositiveSmallIntegerField()
person = models.ForeignKey(Person, on_delete=mod... |
import os
import copy
import re
from dnslib import RR, QTYPE, RCODE
from dnslib.server import DNSServer, DNSHandler, BaseResolver, DNSLogger
import config
class MysqlLogger():
def log_data(self, dnsobj):
pass
def log_error(self, handler, e):
pass
def log_pass(self, *args):
pass
d... |
from numpy import array, dot, eye, copy
from numpy import dot, zeros
from scipy.linalg import inv
import rospy
C = array([[1, 0]])
B = eye(2)
def kinematicLuembergerObserver(vhat_x, vhat_y, w_z, a_x, a_y, v_x_enc, aph, dt):
"""
inputs:
* current longitudinal velocity estimate vhat_x [m/s]
* curr... |
import numpy as np
from distutils.spawn import find_executable
from string import Template
import tempfile
import subprocess
import collections
from .. import util
from .. import visual
from .. import grouping
from .. import resources
from ..geometry import triangulate_quads
from ..constants import log
dtypes = {
'... |
from __future__ import unicode_literals
from django.db import models, migrations
from django.conf import settings
import django.utils.timezone
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.Create... |
import unittest
import random
import numpy as np
from mep.genetics.population import Population
from mep.genetics.chromosome import Chromosome
class TestPopulation(unittest.TestCase):
"""
Test the Population class.
"""
def test_random_tournament_selection(self):
"""
Test the random_tourn... |
import ShtikerPage
from direct.gui.DirectGui import *
from pandac.PandaModules import *
from toontown.toonbase import ToontownGlobals
from toontown.toonbase import TTLocalizer
from toontown.suit import SuitDNA
from toontown.battle import SuitBattleGlobals
from toontown.minigame import MinigamePowerMeter
from toontown.c... |
"""
560. Subarray Sum Equals K
https://leetcode.com/problems/subarray-sum-equals-k/
"""
from collections import defaultdict
from typing import List
class Solution:
def subarraySum(self, nums: List[int], k: int) -> int:
res = 0
summ = 0
h = defaultdict(int)
h[0] = 1
for num in... |
import sys
from common import conn, cur, command, aggregate, get_aggregate
def process_user(uid, follower_of=None, top_level_followee=None, nest_level=0, no_followers=False):
cur.execute("insert into metadata (uid, follower_of, top_level_followee, nest_level) values (%s, %s, %s, %s) on conflict (uid) do update set ... |
"Publications: A publications reference database with web interface."
import os.path
import re
import sys
__version__ = "7.0.4"
class Constants:
def __setattr__(self, key, value):
raise ValueError("cannot set constant")
VERSION = __version__
URL = "https://github.com/pekrau/Publications"
ROOT = ... |
"""
Split RADSeq FASTQ file to a pair of FASTQ files.
RADSeq FASTQ files contain both forward and reverse reads which names
have suffixes '_1' and '_2', respectively. The script produces two FASTQ
files that contain forward and reverse reads and removes the suffixes
from the read names.
The script has two command-line ... |
from django.conf.urls.defaults import *
urlpatterns = patterns('',
(r'^post/$', 'recaptcha_comments.views.validate_and_submit'),
(r'^', include('django.contrib.comments.urls')),
) |
from . import log
from http.client import HTTPResponse
from http.server import BaseHTTPRequestHandler, HTTPServer
from socketserver import ThreadingMixIn
from threading import Thread
import random, socket, struct, sys, time
def sogou_proxy_server(
host=("0.0.0.0", 0),
network_env='CERNET',
ostream=sys.stder... |
from .swin_transformer import SwinTransformer
from .swin_mlp import SwinMLP
def build_model(config):
model_type = config.MODEL.TYPE
if model_type == 'swin':
model = SwinTransformer(img_size=config.DATA.IMG_SIZE,
patch_size=config.MODEL.SWIN.PATCH_SIZE,
... |
import sys
import imp
try:
import dlm
except ImportError:
print "[ERROR] dlm module not found. Add CoreLM root directory to your PYTHONPATH"
sys.exit()
import dlm.utils as U
import dlm.io.logging as L
import argparse
from dlm.io.nbestReader import NBestList
import dlm.reranker.bleu as B
import codecs
from multiproce... |
from OpenGLCffi.GLES2 import params
@params(api='gles2', prms=['n', 'bufs'])
def glDrawBuffersEXT(n, bufs):
pass |
"""Utilities for sending e-mail messages."""
import logging
from django.contrib.auth.models import User
from django.db.models import Q
from djblets.mail.utils import (build_email_address,
build_email_address_for_user)
from reviewboard.accounts.models import ReviewRequestVisit
from review... |
from django.conf.urls import patterns, url
from wikicitations import views
urlpatterns = patterns('',
url(r'^$', views.CitationsView.as_view(), name='citations_index'),
) |
def run_model( fn, command ):
import os, subprocess
head = '#!/bin/sh\n' + \
'#SBATCH --ntasks=32\n' + \
'#SBATCH --nodes=1\n' + \
'#SBATCH --ntasks-per-node=32\n' + \
'#SBATCH --account=snap\n' + \
'#SBATCH --mail-type=FAIL\n' + \
'#SBATCH --mail-user=malindgren@alaska.edu\n' + \
'#SBATCH -p mai... |
from .hlda import hLDA, HLDA_plot
from .corp import sim_corpus, read_corpus |
"""
This script requires Python 3.5 to run.
"""
import asyncio
import aiohttp
import itertools
import sys
import os
import io
import collections
import string
UNICODEDATA_URL = 'http://www.unicode.org/Public/8.0.0/ucd/UnicodeData.txt'
async def spin(msg):
"""Display spinning sequence of ``/-\|``."""
write, flus... |
from twisted.python.filepath import FilePath
from twisted.trial.unittest import TestCase
from renamer import config, plugin
class TestCommand(plugin.Command):
name = 'test'
optParameters = [
('aardvark', 'a', None, 'desc'),
('bobcat', 'b', 5, 'desc', int),
('chocolate', 'c', None,... |
def getitem(M, k):
"Returns the value of entry k in M. The value of k should be a pair."
assert k[0] in M.D[0] and k[1] in M.D[1]
pass
def setitem(M, k, val):
"Sets the element of v with label k to be val. The value of k should be a pair"
assert k[0] in M.D[0] and k[1] in M.D[1]
pass
def add(A... |
""" Constants used by Home Assistant components. """
__version__ = "0.9.0.dev0"
MATCH_ALL = '*'
DEVICE_DEFAULT_NAME = "Unnamed Device"
CONF_LATITUDE = "latitude"
CONF_LONGITUDE = "longitude"
CONF_TEMPERATURE_UNIT = "temperature_unit"
CONF_NAME = "name"
CONF_TIME_ZONE = "time_zone"
CONF_CUSTOMIZE = "customize"
CONF_PLAT... |
from sqlalchemy import Column, Integer, Unicode, ForeignKey, DateTime
from sqlalchemy.orm import relationship
from .base import Base
from .query import Query # noqa
class QueryRevision(Base):
__tablename__ = 'query_revision'
id = Column(Integer, primary_key=True)
text = Column(Unicode(4096))
query_data... |
import hurricane
import collections
import jinja2
import json
import psutil
from tornado.gen import sleep, coroutine
from tornado.websocket import WebSocketHandler
psutil.cpu_percent() # Initialize percent calculator
def _getnums():
numbers = []
numbers.append({
'label': 'CPU Usage',
'label_saf... |
import six
from pyoptix.context import current_context
from pyoptix.mixins.destroyable import DestroyableObject
from pyoptix.mixins.graphnode import GraphNodeMixin
from pyoptix.mixins.hascontext import HasContextMixin
class Acceleration(GraphNodeMixin, HasContextMixin, DestroyableObject):
def __init__(self, builder... |
import time
from task import Task
class SleepTask(Task):
def __init__(self, arguments):
self._seconds = int(arguments[ "seconds" ])
self._current_seconds = 0
def progress(self):
return (self._current_seconds * 100)/self._seconds, "Working..."
def answer(self):
if self._current_seconds == self._seconds:
re... |
import pytest
from nex.dampf.utils import (get_bytes_needed,
is_signed_nr_expressible_in_n_bits)
max_bits_we_can_use = 4 * 8
test_ints = list(range(2 ** 8))
test_ints += [2 ** i for i in range(max_bits_we_can_use + 2)]
test_ints += [n + 1 for n in test_ints] + [n - 1 for n in test_ints]
tes... |
import unittest
import six
from abelfunctions.puiseux import (
almost_monicize,
newton_data,
newton_iteration,
newton_polygon,
newton_polygon_exceptional,
puiseux,
puiseux_rational,
transform_newton_polynomial,
)
from abelfunctions.puiseux_series_ring import PuiseuxSeriesRing
from abelfu... |
import torch.nn as nn
import deep_architect.core as co
from deep_architect.hyperparameters import D
class PyTorchModule(co.Module):
"""Class for taking Pytorch code and wrapping it in a DeepArchitect module.
This class subclasses :class:`deep_architect.core.Module` as therefore inherits all
the information ... |
from __future__ import absolute_import
import numpy as np
np.random.seed( 1337 )
import data_utils
from qe_binid_sent import Bilingual_neural_information_density_sentence
import sys
if __name__ == '__main__':
if len( sys.argv ) != 14:
print( "\nUsage: ", sys.argv[ 0 ], "<src sentence> <src sentence embedding size> <... |
from feature_requests import data
import feature_requests.data.feature_request
def get(id=None):
if id is not None:
return data.feature_request.get(id)
return data.feature_request.get_all()
def add(f):
return data.feature_request.add(f)
def update(id, f):
return data.feature_request.update(id, f... |
import mimetypes
import sys
import tablib
import tablib.core
import csv
import os
from tablib.formats import ods
from tablib.formats._ods import opendocument
from tablib.formats._xls import xlrd
from util.SBtab import misc
def sheets(self): # Added to excess sheets of Databook
return self._datasets
try:
tablib... |
from typing import TYPE_CHECKING
import warnings
from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error
from azure.core.paging import ItemPaged
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import HttpRe... |
import pytest
import supriya.assets.synthdefs
import supriya.nonrealtime
import supriya.patterns
pattern = supriya.patterns.Pbus(
supriya.patterns.Pgpar(
[
supriya.patterns.Pmono(
amplitude=1.0,
duration=1.0,
frequency=supriya.patterns.Pseq([440, 6... |
print("Welcome to System Security Inc.")
print("-- where security is our middle name!\n")
password = input("Enter your password:\n")
if password == "secret":
print("\nAccess Granted")
print("Welcome! You must be someone very important.")
else:
print("\nACCESS DENIED!!!")
input("\n\nPress the enter key to ex... |
def parse_type_list(alist):
result = []
for typeName in alist:
entry = Type(typeName, "object")
result.append(entry)
return result
'''
some predicate's arguments: (on ?obj1 ?obj2), etc
'''
def parse_typed_object_list(alist, variable_names=False, makeDict=False):
result = []
while ali... |
def bsuccessors(state):
"""Return a dict of {state:action} pairs. A state is a (here, there, t) tuple,
where here and there are frozensets of people (indicated by their times) and/or
the light, and t is a number indicating the elapsed time."""
here, there, t = state
if 'light' in here:
return dict(((he... |
import sys
from util import uid
class Skeleton(object):
"""skeleton data"""
def __init__(self):
self.__id = uid.generateUID()
self.__bones = []
self.__boneTop = None
@property
def id(self):
return self.__id
@property
def top(self):
return self.__boneTop
... |
from unipath import Path
import sys
import os
PROJECT_DIR = Path(os.path.abspath(__file__)).parent.parent.parent
sys.path.append(PROJECT_DIR)
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'seaserpent.settings')
import django
django.setup()
import threading
from crawler import SubmarinoSerpent, AmericanasSerpent, Shop... |
from numpy import array, zeros, argmin, inf
from numpy.linalg import norm
def dtw(x, y, dist=lambda x, y: norm(x - y, ord=1)):
""" Computes the DTW of two sequences.
:param array x: N1*M array
:param array y: N2*M array
:param func dist: distance used as cost measure (default L1 norm)
Returns the mi... |
"""
Django settings for AssetManager project.
For more information on this file, see
https://docs.djangoproject.com/en/dev/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/dev/ref/settings/
"""
import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
SECRET_K... |
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('wagtailimages', '0019_delete_filter'),
('animals', '0006_auto_20171117_1119'),
]
operations = [
migrations.AddFi... |
from core.himesis import Himesis, HimesisPreConditionPatternLHS
import uuid
class HUnitR04c_ConnectedLHS(HimesisPreConditionPatternLHS):
def __init__(self):
"""
Creates the himesis graph representing the AToM3 model HUnitR04c_ConnectedLHS
"""
# Flag this instance as compiled now
self.is_compiled = True
sup... |
import os
from datetime import datetime
import numpy as np
from numpy.linalg import norm
from matplotlib import rc
import matplotlib.pyplot as plt
from astropy import units as u
from poliastro.bodies import Earth
from poliastro.twobody import Orbit
from poliastro.twobody.propagation import cowell
from poliastro.twobody... |
import tensorflow as tf
import numpy as np
import argparse
import model_config
import data_loader
from ByteNet import model
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--learning_rate', type=float, default=0.001,
help='Learning Rate')
parser.add_argument('--batch_size', type=int, defa... |
import warnings
import sys
from os.path import join
import tarfile
import numpy
import rasterio
import glob
from rasterio.warp import reproject, RESAMPLING, transform
from skimage import img_as_ubyte, exposure
from skimage import transform as sktransform
import settings
from mixins import VerbosityMixin
from utils impo... |
from __future__ import unicode_literals, print_function
import frappe
import imaplib
import re
import json
import socket
from frappe import _
from frappe.model.document import Document
from frappe.utils import validate_email_address, cstr, cint, get_datetime, DATE_FORMAT, strip, comma_or, sanitize_html, add_days
from f... |
from datetime import datetime, timedelta
from django.conf import settings
from django.core.exceptions import FieldError
from nopassword.models import LoginCode
from nopassword.utils import get_user_model
class NoPasswordBackend(object):
def authenticate(self, code=None, **credentials):
try:
user... |
from .fp import FrontPanel, PLL22150, PLL22393 |
import cult
def addMember():
entry = cult.getEntries()
if cult.validateEmail(entry[1].get()):
cult.writeData("shirts.txt")
else:
cult.displayError("Invalid Email")
cult.deleteEntries()
cult.createMaster("Shirt Order Form")
fields = ["Name", "Email", "Shirt Size"]
cult.createLabels(fields... |
import os
import unittest
import random
import logging
import math
import cmath
import testfixtures
from pyvivado import project, signal
from pyvivado import config as pyvivado_config
from rfgnocchi.xilinx import dds_compiler
from rfgnocchi import config
logger = logging.getLogger(__name__)
class TestXilinxDDSCompiler(... |
import heapq
def largest_max_heap(h, k):
"""
Returns the k largest items from h, which has the heap property.
"""
aux = [(-h[0], 0)]
largest = []
for _ in xrange(k):
x, i = heapq.heappop(aux)
largest.append(-x)
for j in range(2*i+1, 2*i+3):
if j < len(h):
... |
CELERY_ACCEPT_CONTENT = ['pickle', 'json']
BROKER_URL = 'redis://localhost:6379/0' |
import numpy
def sliding_window(data, size, stepsize=1, padded=False, axis=-1, copy=True):
"""
Calculate a sliding window over a signal
Parameters
----------
data : numpy array
The array to be slided over.
size : int
The sliding window size
stepsize : int
The sliding ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.