code stringlengths 1 199k |
|---|
"""KDE of Temps."""
import calendar
from datetime import date, datetime
import pandas as pd
from pyiem.plot.util import fitbox
from pyiem.plot import figure
from pyiem.util import get_autoplot_context, get_sqlalchemy_conn
from pyiem.exceptions import NoDataFound
from matplotlib.ticker import MaxNLocator
from scipy.stat... |
from django.contrib import admin
from pieces.models import (
PieceTag,
Piece, Venue, Study, Keyword,
PieceToStudyAssociation)
class KeywordInline(admin.TabularInline):
model = Keyword
extra = 10
class StudyAdmin(admin.ModelAdmin):
list_display = ("id", "name", "start_date")
date_... |
import os
import logging
import datetime
import re
import dateutil.parser
from lib.cuckoo.common.abstracts import BehaviorHandler
log = logging.getLogger(__name__)
class FilteredProcessLog(list):
def __init__(self, eventstream, **kwfilters):
self.eventstream = eventstream
self.kwfilters = kwfilters
... |
"""
An API used by the UI and RESTful API.
"""
from bson import ObjectId
__author__ = 'tmetsch'
import collections
import json
import pika
import pika.exceptions as pikaex
import uuid
from suricate.data import object_store
from suricate.data import streaming
TEMPLATE = '''
% if len(error.strip()) > 0:
<div class="e... |
import vim
import itertools as it
from orgmode._vim import echom, ORGMODE, apply_count, repeat, realign_tags
from orgmode import settings
from orgmode.liborgmode.base import Direction
from orgmode.menu import Submenu, ActionEntry
from orgmode.keybinding import Keybinding, Plug
from orgmode.exceptions import PluginError... |
import yaml
import os
from ..boids import Boids
from nose.tools import assert_equal
import random
import numpy as np
from unittest.mock import patch
import unittest.mock as mock
def test_Boids():
flock = Boids(boid_number=10,move_to_middle_strength=0.1,alert_distance=100,formation_flying_distance=900,formation_flyi... |
from django.conf.urls import url, include
from django.contrib import admin
from django.conf import settings
from django.conf.urls.static import static
from api.views import router
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^', include(router.urls)),
url(r'^ui/', include('ui.urls', namespace='bu... |
import unittest, os, sys, StringIO
from textui.prompt import *
from nose.tools import istest, nottest
from nose.plugins.attrib import attr
_explained = False
def _text_repeats(txt, fragment):
i = txt.find(fragment)
if i > -1:
i = txt[i + len(fragment):].find(fragment)
return i > -1
return Fa... |
import sys; import os
sys.path.insert(0, os.path.abspath('..'))
sys.path.insert(0, os.path.abspath('.'))
from flask import Flask, render_template, request, redirect
import subprocess
from Utils import subprocess_helpers
from Utils.DataSource import *
app = Flask(__name__)
dataSource = DataSource()
def launch_preproces... |
import pygame
from pygame.locals import *
import constants as c
class Enemy:
def __init__(self, x, y, health, movement_pattern, direction, img):
self.x = x
self.y = y
self.health = health
self.movement_pattern = movement_pattern
self.direction = direction
self.img = i... |
import os
from angular_flask import app
from flask.ext.restless import APIManager
from flask.ext.mongoengine import MongoEngine
app.config["MONGODB_SETTINGS"] = {'DB':os.environ.get('MONGODB_DB'),"host":os.environ.get('MONGODB_URI')}
mongo_db = MongoEngine(app)
api_manager = APIManager(app) |
import asyncio
try:
from unittest.mock import Mock, create_autospec
except ImportError:
from mock import Mock, create_autospec
from uuid import uuid4
from functools import wraps
from copy import copy
from unittest import TestCase as unittestTestCase
from zeroservices.exceptions import ServiceUnavailable
from ze... |
"""
The classes `Token` and `Nonterm` can be subclassed and enriched
with docstrings indicating the intended grammar, and will then be
used in the parsing as part of the abstract syntax tree that is
constructed in the process.
"""
from __future__ import annotations
class Symbol:
pass
class Nonterm(Symbol):
"""
... |
from distutils.dir_util import copy_tree, remove_tree
import os
import shutil
def _copy_function(source, destination):
print('Bootstrapping project at %s' % destination)
copy_tree(source, destination)
def create_app():
cwd = os.getcwd()
game_logic_path = os.path.join(cwd, 'game_logic')
game_app_inte... |
from tc_python.arule import ARule
from t_core.messages import Packet
from HA import HA
from HAb import HAb
from HTopClass2TableLHS import HTopClass2TableLHS
from HTopClass2TableRHS import HTopClass2TableRHS
r1 = ARule(HTopClass2TableLHS(), HTopClass2TableRHS())
p = Packet()
p.graph = HA()
p1 = r1.packet_in(p)
print p1
... |
r"""
This code was generated by
\ / _ _ _| _ _
| (_)\/(_)(_|\/| |(/_ v1.0.0
/ /
"""
from twilio.base import deserialize
from twilio.base import values
from twilio.base.instance_context import InstanceContext
from twilio.base.instance_resource import InstanceResource
from twilio.base.list_resource i... |
"""Main package initializer"""
__author__ = "Cody Precord <cprecord@editra.org>"
__svnid__ = "$Id: __init__.py 49807 2007-11-10 07:08:33Z CJP $"
__revision__ = "$Revision: 49807 $" |
"""Interface to rpy2.glm
Copyright 2012 Allen B. Downey
License: GNU GPLv3 http://www.gnu.org/licenses/gpl.html
"""
import rpy2.robjects as robjects
r = robjects.r
def linear_model(model, print_flag=True):
"""Submits model to r.lm and returns the result."""
model = r(model)
res = r.lm(model)
if print_fl... |
"""
General functions for HTML manipulation, backported from Py3.
Note that this uses Python 2.7 code with the corresponding Python 3
module names and locations.
"""
from __future__ import unicode_literals
_escape_map = {ord('&'): '&', ord('<'): '<', ord('>'): '>'}
_escape_map_full = {ord('&'): '&', ord('... |
from OpenGL.GL import *
from OpenGL.GLU import *
from OpenGL.GLUT import *
import psi
from psi.calc import clip
from psi.euclid import Vector2
__all__ = ['Camera']
class Camera(object):
def __init__(self, pos=Vector2(0, 0)):
self.pos = pos
self.half_size = Vector2(300, 300)
self.zoom = 1.0
... |
import mcpi.minecraft as minecraft
import mcpi.block as block
import time
mc = minecraft.Minecraft.create()
x, y, z = mc.player.getPos()
mc.setBlocks(x - 20, y, z - 20, x + 20, y + 20, z + 20, block.AIR)
mc.setBlocks(z - 20, y - 1, z - 20, y, z + 20, block.GRASS.id)
for colour in range(0, 15):
# draw upwards
mc... |
import artistools.makemodel.botyanski2017 |
from .Confusion_MI import*
from .Cov_Mat import *
from .SaveLoadModel import * |
"""
This is part of the MSS Python's module.
Source: https://github.com/BoboTiG/python-mss
"""
import platform
from typing import TYPE_CHECKING
from .exception import ScreenShotError
if TYPE_CHECKING:
from typing import Any # noqa
from .base import MSSBase # noqa
def mss(**kwargs):
# type: (Any) -> MSSBas... |
try:
from functools import reduce # noqa
except Exception:
pass
try:
from .tornado_handler import TornadoHandler # noqa
except ImportError:
pass
from .environmentdump import EnvironmentDump # noqa
from .healthcheck import HealthCheck # noqa |
import threading
def worker():
print('new worker')
for i in range(8):
threading.Thread(target = worker).start() |
class Solution:
def decodeString(self, s: str) -> str:
St = []
num = 0
curr = ''
for c in s:
if c.isdigit():
num = num*10 + int(c)
elif c == '[':
St.append([num, curr])
num = 0
curr = ''
... |
import os
import datetime
import logging
from py_modelica.exception_classes import ModelicaInstantiationError
from abc import ABCMeta, abstractmethod
class ToolBase:
__metaclass__ = ABCMeta
tool_name = ''
tool_version = ''
tool_version_nbr = ''
model_config = None
date_time = ''
## instance ... |
"""
formlayout
==========
Module creating Qt form dialogs/layouts to edit various type of parameters
formlayout License Agreement (MIT License)
------------------------------------------
Copyright (c) 2009 Pierre Raybaut
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and a... |
"""A parser for axfs file system images"""
from stat import *
import zlib
from . import *
from ..io import *
from ..util import *
AxfsHeader = Struct('AxfsHeader', [
('magic', Struct.STR % 4),
('signature', Struct.STR % 16),
('digest', Struct.STR % 40),
('blockSize', Struct.INT32),
('files', Struct.INT64),
('size... |
from rest_framework import status
from rest_framework.reverse import reverse
from rest_framework.test import APITestCase
from restapi.models.web_radio import WebRadio
class TestGetDetails(APITestCase):
def setUp(self):
super(TestGetDetails, self).setUp()
self.webradio = WebRadio.objects.create(name=... |
import queue
class Edge:
def __init__(self, u, v, capacity):
self.u = u
self.v = v
self.capacity = capacity
self.flow = 0
class FlowGraph:
def __init__(self, n):
# List of all - forward and backward - edges
self.edges = []
# These adjacency lists store onl... |
'''
David Rodriguez
Goal: Continuously looping while to perform valve actions at specified times,
introduce substance at a specific ratio based on flow data, recording
and saving flow data, and actuating a flush at a specified time.
Inputs: A schedule of events based on entered times.
Outputs: Sequence of events to a s... |
from .company import Company
from .contact import Contact
from .deal import Deal
from .note import Note
from .requester import Requester
class AgileCRM:
def __init__(self, domain, email, api_key):
requester = Requester(domain, email, api_key)
self.contact = Contact(requester=requester)
self.... |
import re
import datetime
import logging
log = logging.getLogger(__name__)
class Marker(object):
__slots__ = ['line_start', 'line_end', 'expires']
def __init__(self, lineno):
self.line_start = lineno
self.line_end = lineno
self.expires = None
def __str__(self):
if self.line_s... |
"""Qurawl Main"""
from __future__ import absolute_import
from __future__ import unicode_literals
import itertools as it
import random as rand
import difflib as diff
import common.debugit as debugit
import qurawl.regparse as rp
from qurawl.level import *
from qurawl.items import *
import qurawl.zoo as zoo
__all__ = ['Qu... |
import _plotly_utils.basevalidators
class NticksValidator(_plotly_utils.basevalidators.IntegerValidator):
def __init__(
self, plotly_name="nticks", parent_name="funnel.marker.colorbar", **kwargs
):
super(NticksValidator, self).__init__(
plotly_name=plotly_name,
parent_nam... |
import msvcrt
titulo="Empresa Rubben Rc Corporation\n".capitalize()
print titulo.center(50," ")
print("Telefono: 6948209")
class modelo_presupuesto:
titulo="presupuesto"
inicio_nombre="Empresa Rubben Rc Corporation"
inicio_web= "www.rubbenrc.com"
inicio_email= "rubbenrc@hotmail.com"
cuota_iva= 7
... |
import sys
import os
import shlex
DIR = os.path.dirname(os.path.abspath(__file__))
def read(fpath):
with open(fpath, 'rt') as f:
return f.read().strip()
extensions = []
templates_path = ['_templates']
source_suffix = '.rst'
master_doc = 'index'
project = u'fmap'
copyright = u'2016, Matt Bodenhamer'
author =... |
"""
niascape.usecase.postcount
投稿件数ユースケース
"""
import niascape
from niascape.repository import postcount
from niascape.utility.database import get_db
def day(option: dict) -> list:
with get_db(niascape.ini['database']) as db: # type: ignore # XXX セクションぶっこむとmypyさんにおこられ 辞書化すべきか
return postcount.day(db, **option)
def ... |
command = '/home/lucas/www/reddit.lucasou.com/reddit-env/bin/gunicorn'
pythonpath = '/home/lucas/www/reddit.lucasou.com/reddit-env/flask_reddit'
bind = '127.0.0.1:8040'
workers = 1
user = 'lucas'
accesslog = '/home/lucas/logs/reddit.lucasou.com/gunicorn-access.log'
errorlog = '/home/lucas/logs/reddit.lucasou.com/gunico... |
import sys, getopt
import errno
import os.path
import epub
import lxml
from bs4 import BeautifulSoup
class EPubToTxtParser:
# Epub parsing specific code
def get_linear_items_data( self, in_file_name ):
book_items = []
book = epub.open_epub( in_file_name )
for item_id, linear in book.opf.... |
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import numpy as np
from src import jeffery_model as jm
DoubleletStrength = np.array((1, 0, 0))
alpha = 1
B = np.array((0, 1, 0))
lbd = (alpha ** 2 - 1) / (alpha ** 2 + 1)
x, y = np.meshgrid(np.linspace(-1, 1, 100), np.linspace(-1, 1, 100))
problem... |
"""
Design a data structure that supports the following two operations:
void addWord(word)
bool search(word)
search(word) can search a literal word or a regular expression string containing
only letters a-z or .. A . means it can represent any one letter.
For example:
addWord("bad")
addWord("dad")
a... |
import sys
import os
import sphinx_rtd_theme
sys.path.insert(0, os.path.abspath('../..'))
extensions = [
'sphinx.ext.autodoc',
]
templates_path = ['_templates']
source_suffix = '.rst'
master_doc = 'index'
project = 'Qcloud COS SDK for Python 3'
copyright = '2016, Dan Su'
author = 'Dan Su'
version = '0.1.0'
release ... |
import feedparser
import logging
from rss import sources
from util import date, dict_tool, tags
log = logging.getLogger('app')
def parse_feed_by_name(name):
feed_params = sources.get_source(name)
if not feed_params:
raise ValueError('There is no feed with name %s' % name)
source_name = feed_params['... |
from setuptools import setup
setup(name='pyyaxml',
version='0.6.7',
description='Python API to Yandex.XML',
url='https://github.com/dbf256/py-ya-xml',
author='Alexey Moskvin',
author_email='dbf256@gmail.com',
license='MIT',
packages=['pyyaxml'],
install_requires=[
... |
"""
Broadcast a message, with or without a price.
Multiple messages per block are allowed. Bets are be made on the 'timestamp'
field, and not the block index.
An address is a feed of broadcasts. Feeds may be locked with a broadcast whose
text field is identical to ‘lock’ (case insensitive). Bets on a feed reference
the... |
from __future__ import unicode_literals
from django.test import TestCase, RequestFactory
from django.contrib.auth import get_user_model, authenticate
from django.contrib.auth.models import AnonymousUser
import json
import status
from tiny_rest.views import APIView
from tiny_rest.authorization import (
IsAuthenticat... |
import uuid
from msrest.pipeline import ClientRawResponse
from msrestazure.azure_exceptions import CloudError
from .. import models
class AvailabilitySetsOperations(object):
"""AvailabilitySetsOperations operations.
:param client: Client for service requests.
:param config: Configuration of service client.
... |
import os
from twilio.rest import Client
account = os.environ['TWILIO_ACCOUNT_SID']
token = os.environ['TWILIO_AUTH_TOKEN']
client = Client(account, token)
credential = client.notify \
.credentials("CRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \
.update(friendly_name="MyCredential",
... |
print 'abc' + '123'
print 'Hi' * 5 |
import numpy as np
import tensorflow as tf
import os
def get_inputs(split, config):
split_dir = config['split_dir']
data_dir = config['data_dir']
dataset = config['dataset']
split_file = os.path.join(split_dir, dataset, split + '.lst')
filename_queue = get_filename_queue(split_file, os.path.join(dat... |
import subprocess
import datetime
from pymongo import MongoClient
filename = '/path/to/php/logs.log'
client = MongoClient('mongo.server.address', 27017)
db = client.logs
php_logs = db.php_logs
f = subprocess.Popen(['tail','-f',filename],\
stdout=subprocess.PIPE,stderr=subprocess.PIPE)
while True:
# read line by line
... |
import os
import pickle
import numpy as np
from tqdm import tqdm
class SumTree:
def __init__(self, capacity):
self.capacity = capacity
self.tree = np.zeros(2 * capacity - 1, dtype=np.float32)
self.data = np.empty(capacity, dtype=object)
self.head = 0
@property
def total_prior... |
import sys
import os
import csv
from datetime import datetime, timedelta
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
from matplotlib.dates import drange
from matplotlib.patches import Rectangle
import scenario_factory
PRIMA = (148/256, 164/256, 182/256)
PRIMB = (101/256, 1... |
"""
The MIT License (MIT)
Copyright (c) 2017 LeanIX GmbH
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, pu... |
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('mainapp', '0022_auto_20190404_1605'),
]
operations = [
migrations.AlterField(
model_name='historicalpaper',
name='reference_number',
field=models.CharField(b... |
import sklearn.cross_validation as cv
import sklearn.dummy as dummy
from sklearn.mixture import GMM
from sklearn.hmm import GMMHMM
from sklearn import linear_model, naive_bayes
import collections
import itertools
import pandas as pd
from testResults import TestResults
from counters import *
import utils as utils
class ... |
from f6a_tw_crawler.constants import *
import unittest
import logging
def setup():
pass
def teardown():
pass |
"""
Plugins related to folders and paths
"""
from hyde.plugin import Plugin
from hyde.fs import Folder
class FlattenerPlugin(Plugin):
"""
The plugin class for flattening nested folders.
"""
def __init__(self, site):
super(FlattenerPlugin, self).__init__(site)
def begin_site(self):
""... |
from django.db import models
from django.contrib.auth.models import User
class Post(models.Model):
title = models.CharField(max_length=255)
body = models.TextField()
user = models.ForeignKey(User) |
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('builds', '0010_merge'),
]
operations = [
migrations.AlterField(
model_name='project',
name='approved',
field=models.B... |
from kazoo.exceptions import NoNodeError
from sys import maxsize
from .mutex import Mutex
from .internals import LockDriver
from .utils import lazyproperty
READ_LOCK_NAME = "__READ__"
WRITE_LOCK_NAME = "__WRIT__"
class _LockDriver(LockDriver):
def sort_key(self, string, _lock_name):
string = super(_LockDriv... |
"""
You are given an array of desired filenames in the order of their creation. Since two files cannot have equal names, the one which comes later will have an addition to its name in a form of (k), where k is the smallest positive integer such that the obtained name is not used yet.
Return an array of names that will ... |
from distutils.core import setup
setup(
name = "nip",
version = "0.1a1",
py_modules = [
"nip",
],
scripts = [
"bin/nip",
],
author = "Brian Rosner",
author_email = "brosner@gmail.com",
description = "nip is environment isolation and installation for Node.js",
long... |
import unittest
from allergies import Allergies
if not hasattr(unittest.TestCase, 'assertCountEqual'):
unittest.TestCase.assertCountEqual = unittest.TestCase.assertItemsEqual
class AllergiesTests(unittest.TestCase):
def test_no_allergies_means_not_allergic(self):
allergies = Allergies(0)
self.as... |
import numpy
import argparse
import time
import mido
import colorsys
import gitgrid.gridcontroller
import gitgrid.utils.utils
args = gitgrid.utils.utils.controller_args()
tmp = gitgrid.gridcontroller.create(args.controller, args.input, args.output)
def toggle(x, y, Message):
curr = tmp.lights[x, y, :] / 255.
hs... |
import RPi.GPIO as gpio
from datetime import datetime
import time
import controller
gpio.setmode(gpio.BOARD)
switch = 10
gpio.setup(switch, gpio.OUT, initial=False)
def switch_on():
gpio.output(switch, True)
print "Oven switched ON at " + str(datetime.now())
def switch_off():
gpio.output(switch, False)
print "O... |
from __future__ import (unicode_literals, absolute_import,
division, print_function)
import logging
from django.http import Http404
from django.shortcuts import render
from django.contrib.auth.decorators import login_required
from snisi_core.permissions import provider_allowed_or_denied
from sni... |
import os
import codecs, re, time, string, logging, math
from operator import itemgetter
from nltk import FreqDist
from nltk.corpus import stopwords
import textmining
from scipy import spatial
from . import filehandler
def most_frequent_terms(*args):
tdm = textmining.TermDocumentMatrix(simple_tokenize_remove_our_st... |
import sys
import textwrap
from setuptools import setup
from setuptools.command.install import install
class CheckCairoXcb(install):
def cairo_xcb_check(self):
try:
from cairocffi import cairo
cairo.cairo_xcb_surface_create
return True
except AttributeError:
... |
from __future__ import unicode_literals
from django.db import models, migrations
from django.conf import settings
class Migration(migrations.Migration):
dependencies = [
('user', '0002_auto_20150703_0836'),
]
operations = [
migrations.AlterField(
model_name='user',
na... |
from django.db import models
from django.contrib.postgres.fields.jsonb import JSONField
class Supplier(models.Model):
name = models.CharField(max_length=50)
tax_id = models.CharField(max_length=10)
def __str__(self):
return self.name
class Bargain(models.Model):
sku = models.CharField(max_length... |
"""
"""
import nagini
import requests
import json
import os, sys
import base64
import time
from requests.packages.urllib3.exceptions import InsecureRequestWarning
def get_script_path():
return os.path.dirname(os.path.realpath(sys.argv[0]))
def get_metric_data(resourceknd,adapter,key,sampleno ):
outdata = [] # I... |
from mapwidgets.widgets import GooglePointFieldWidget
from miot.models import PointOfInterest, Page, Profile
from django import forms
class PointOfInterestForm(forms.ModelForm):
'''The form for a point of interest.'''
class Meta:
model = PointOfInterest
fields = ("name", "featured_image", "posit... |
from __future__ import absolute_import
from werkzeug.exceptions import ServiceUnavailable, NotFound
from r5d4.flask_redis import get_conf_db
def publish_transaction(channel, tr_type, payload):
conf_db = get_conf_db()
if tr_type not in ["insert", "delete"]:
raise ValueError("Unknown transaction type", tr... |
import _plotly_utils.basevalidators
class TicksuffixValidator(_plotly_utils.basevalidators.StringValidator):
def __init__(
self, plotly_name="ticksuffix", parent_name="densitymapbox.colorbar", **kwargs
):
super(TicksuffixValidator, self).__init__(
plotly_name=plotly_name,
... |
"""
Utilities for dealing with text encodings
"""
import sys
import locale
import warnings
def get_stream_enc(stream, default=None):
"""Return the given stream's encoding or a default.
There are cases where ``sys.std*`` might not actually be a stream, so
check for the encoding attribute prior to returning i... |
import numpy as np
import scipy.interpolate as interp
import warnings
from astropy.io import fits
def concentration(radii, phot, eta_radius=0.2, eta_radius_factor=1.5, interp_kind='linear', add_zero=False):
"""
Calculates the concentration parameter
C = 5 * log10(r_80 / r2_0)
Inputs:
radii -- 1d arr... |
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding field 'Project.url'
db.add_column(u'core_project', 'url',
self.gf('django.db.models.fields.TextField')(n... |
from django.contrib import admin
from courses.models import Course, Instructor, Page, Enrollment
class CourseAdmin(admin.ModelAdmin):
list_display = ['title', 'instructor', 'language', 'popularity', 'is_public', 'deleted']
prepopulated_fields = {
'slug': ('title', )
}
def queryset(self, request)... |
"""JSON implementations of relationship searches."""
from . import objects
from . import queries
from .. import utilities
from ..osid import searches as osid_searches
from ..primitives import Id
from ..utilities import get_registry
from dlkit.abstract_osid.osid import errors
from dlkit.abstract_osid.relationship import... |
from staffjoy.resource import Resource
class ChompTask(Resource):
PATH = "internal/tasking/chomp/{schedule_id}"
ENVELOPE = None
ID_NAME = "schedule_id" |
from ctypes import Structure, c_int16, c_uint16
class Filter(Structure):
""" Represents a Fixture filter """
_fields_ = [("categoryBits", c_uint16),
("maskBits", c_uint16),
("groupIndex", c_int16)]
def __init__(self, categoryBits=0x1, maskBits=0xFFFF, groupIndex=0):
"... |
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
]
operations = [
migrations.CreateModel(
name='Category',
fields=[
('id', models.AutoField(primary_key=True, verbose_name='... |
__author__ = 'ray'
__date__ = '2/27/15'
from flask import jsonify, abort
from flask.views import MethodView
from ..models import ThemeModel
class ThemeView(MethodView):
""" Theme View
Retrieve description of a list of available themes.
:param theme_model: A theme model that manages themes.
:type theme_m... |
"""
WSGI config for api project.
This module contains the WSGI application used by Django's development server
and any production WSGI deployments. It should expose a module-level variable
named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover
this application via the ``WSGI_APPLICATION`` setti... |
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [("hordak", "0007_auto_20161209_0111")]
operations = [
migrations.RenameField("Account", "has_statements", "is_bank_account")
] |
def fixture(fixture_manager, factory_manager):
acc_seq = "CREATE SEQUENCE IF NOT EXISTS accession_naming_seq START WITH 1 INCREMENT BY 1 NO MINVALUE NO MAXVALUE CACHE 1;"
bat_seq = "CREATE SEQUENCE IF NOT EXISTS batch_naming_seq START WITH 1 INCREMENT BY 1 NO MINVALUE NO MAXVALUE CACHE 1;"
from django.db im... |
"""
Django settings for lark 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/
"""
from .base import *
SECRET_KEY = ')i4@2vfr##+zd3cn8ckw#!lebya1mk2sg@yq9boog+=ofi... |
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('fastapp', '0010_auto_20150910_2010'),
]
operations = [
migrations.AddField(
model_name='thread',
name='updated',
fiel... |
class ClopureSyntaxError(Exception):
def __init__(self, *args, pos=0, **kwargs):
super().__init__(*args, **kwargs)
self.pos = pos
class ClopureRuntimeError(Exception):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs) |
from datetime import datetime, timedelta
import json
from django.contrib.contenttypes.models import ContentType
from django.test import TestCase
from django_dynamic_fixture import G, N
from freezegun import freeze_time
from mock import patch
from issue.models import (
Assertion, ExtendedEnum, Issue, IssueAction, Is... |
class TooManyMissingFrames(Exception):
pass
class InvalidDuration(Exception):
pass
class InvalidTag(Exception):
pass
class InvalidID3TagVersion(Exception):
pass
class CouldntDecodeError(Exception):
pass |
import os
import sys
import shutil
import logging
import argparse
import tempfile
sys.path.append(os.path.join(os.path.dirname(__file__), '..'))
from webloader.phantomjs_loader import PhantomJSLoader
from webloader.curl_loader import CurlLoader
from webloader.pythonrequests_loader import PythonRequestsLoader
from weblo... |
"""
Serializers for the topic and voting models.
"""
from topics.models import Topic, Vote
from rest_framework import serializers
class InRange(object):
"""
Validator that specifies a value must be in a particular range
"""
def __init__(self, low, high):
self.low = low
self.high = high
... |
import random
import numpy as np
class ReplayBuffer(object):
def __init__(self, max_size):
self.max_size = max_size
self.cur_size = 0
self.buffer = {}
self.init_length = 0
def __len__(self):
return self.cur_size
def seed_buffer(self, episodes):
self.init_lengt... |
subreddit = 'jacksepticeye'
t_channel = '@r_jacksepticeye'
def send_post(submission, r2t):
return r2t.send_simple(submission) |
import re
import sys
INTERACTIVE = False
POSTPROC = True
if POSTPROC:
print 'WARNING: Performing dataset-specific postprocessing.'
utterance_re = re.compile('^utterance\(')
phrase_re = re.compile('^phrase\(')
mappings_re = re.compile('^mappings\(')
candidates_re = re.compile('^candidates\(')
EOU_re = re.compile('^\... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.