code stringlengths 1 199k |
|---|
"""tidy_up_latent
Tidy up a latent migration not previously picked up by alembic or ignored.
Revision ID: 1280
Revises: 1270
Create Date: 2019-06-10 15:51:48.661665
"""
from alembic import op
import sqlalchemy as sa
revision = '1280'
down_revision = '1270'
def upgrade():
# this field not has a "unique index" instea... |
import base64
from dataclasses import dataclass
from typing import Any, List, Tuple, Union
import flask
import sqlalchemy as sa
from marshmallow import ValidationError, fields
from flask_resty.sorting import FieldOrderings, FieldSortingBase
from flask_resty.view import ModelView
from . import meta
from .exceptions impo... |
>>> # 4 ways to make a string
>>> str1 = 'This is a string. We built it with single quotes.'
>>> str2 = "This is also a string, but built with double quotes."
>>> str3 = '''This is built using triple quotes,
... so it can span multiple lines.'''
>>> str4 = """This too
... is a multiline one
... built with triple double... |
__all__ = ["user_controller", "plant_controller"] |
import os
import subprocess
import pandas as pd
os.chdir('../')
start_dt = '2019-05-01'
end_dt = '2019-06-20'
commits = subprocess.check_output(
"git log --after={start_dt} --before={end_dt} --format='%s%cr'".
format(start_dt=start_dt, end_dt=end_dt),
shell=True)
commits = commits.decode('utf-8')
print(... |
import collections
class Solution:
def arrangeWords(self, text: str) -> str:
words = text.split()
table = collections.defaultdict(list)
for word in words:
table[len(word)].append(word)
result = []
for key in sorted(table):
result.extend(table[key])
... |
import doctest
import logging
import os
import pytest
import robustus
from robustus.detail import check_module_available
from robustus.detail.utility import run_shell, check_run_shell
import shutil
import subprocess
import tempfile
def test_doc_tests():
doctest.testmod(robustus, raise_on_error=True)
doctest.tes... |
from __future__ import print_function
import RPi.GPIO as GPIO
import time
import Queue # https://pymotw.com/2/Queue/
Taster1 = 24
Taster2 = 27
GPIO.setmode(GPIO.BCM)
PULL = GPIO.PUD_UP #GPIO -> 3V3
GPIO.setup(Taster1, GPIO.IN, pull_up_down=PULL)
GPIO.setup(Taster2, GPIO.IN, pull_up_down=PULL)
dictionary = {}
dic... |
import numpy as np
import matplotlib.pyplot as plt
import re
rootPath = "/Users/jeff/work/debug/20181216_hard_fe2k_15fps/"
finalLogFile = "rosout.log.2"
def appendTimestamps(arr, start, stop, flag):
#flag = True
d = stop - start
if flag or (d > -10 and d < 2000):
arr.append(d)
return True
... |
import numpy as np
from skimage import io
def read_image(fn, normalize=True):
"""Read a CCD/CMOS image in .da format (Redshirt). [1_]
Parameters
----------
fn : string
The input filename.
Returns
-------
images : array, shape (nrow, ncol, nframes)
The images (normalized by th... |
from os.path import dirname
import os
import sys
if __name__ == "__main__":
sample_dir = dirname(os.path.abspath(__file__))
root = dirname(dirname(sample_dir))
sys.path.append(root)
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "sampleproj.settings")
try:
from django.core.management import... |
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('dashboard', '0041_auto_20160707_1856'),
]
operations = [
migrations.AddField(
model_name='studytableevent',
name='notes',
... |
import os
from distutils.core import setup
ROOT = os.path.dirname(os.path.realpath(__file__))
setup(
name='wmsigner',
version='0.1.1',
url='https://github.com/egorsmkv/wmsigner',
description='WebMoney Signer',
long_description=open(os.path.join(ROOT, 'README.rst')).read(),
author='Egor Smolyakov... |
import test_core
import sys
import demjson
test_core.title("搜索用户")
f = open("testconfig.json", 'r')
lines = f.read()
f.close()
jsonfiledata = demjson.decode(lines)
if jsonfiledata["url"] == "":
test_core.terr("错误: 'testconfig.json' 配置不完全。")
exit()
uurl = jsonfiledata["url"]+"search.php"
udataarr = {
'type':... |
"""Models for the ``feedback_form`` app."""
from django.contrib.contenttypes.fields import GenericForeignKey
from django.contrib.contenttypes.models import ContentType
from django.db import models
from django.conf import settings
from django.utils.encoding import python_2_unicode_compatible
from django.utils.translatio... |
"""
This tests that all the PLE games launch, except for doom; we
explicitly check that it isn't defined.
"""
import nose
import numpy as np
import unittest
NUM_STEPS=150
class NaiveAgent():
def __init__(self, actions):
self.actions = actions
def pickAction(self, reward, obs):
return self.action... |
import socket
import random
from PIL import Image
import json
import sys, getopt
import math
import pika
offset_x = 80
offset_y = 24
screen_width = 240
screen_height = 240
queueAddress = ''
fileName = ''
workers = 36
Matrix = []
def main(argv):
global fileName, workers
inputFile = ''
try:
opts, args... |
import re
from astropy import units as u
from astropy.coordinates import SkyCoord
from astropy.time import Time
from panoptes.mount.mount import AbstractMount
from ..utils.logger import has_logger
from ..utils.config import load_config
from ..utils import error as error
@has_logger
class Mount(AbstractMount):
"""
... |
"""
WSGI config for sms_relay 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``... |
import matplotlib.pyplot as plt
import numpy as np
import sys
import time
import scipy.interpolate as ip
infile = sys.argv[1]
indata = np.load(infile)
spec = indata[0]
samp_rate = indata[1]
fftsize = indata[2]
center_freq = 1419.4 # MHz
halffft = int(0.5*fftsize)
freqs = 0.5*samp_rate*np.array(range(-halffft,halffft))/... |
"""
To understand why this file is here, please read:
http://cookiecutter-django.readthedocs.io/en/latest/faq.html#why-is-there-a-django-contrib-sites-directory-in-cookiecutter-django
"""
from django.conf import settings
from django.db import migrations
def update_site_forward(apps, schema_editor):
"""Set site doma... |
import os
import re
from subprocess import Popen, PIPE
from kivy.uix.popup import Popup
def run_syscall(cmd):
"""
run_syscall; handle sys calls this function used as shortcut.
::cmd: String, shell command is expected.
"""
p = Popen(cmd, shell=True, stdout=PIPE, stderr=PIPE)
out, err = p.communic... |
"""
@author: Daniel Butum, Group 911
"""
from domain.number import Number, NumberException
from utils.number import convert_to_int
class Console:
def __init__(self):
pass
def run(self):
"""
Run the console gui
"""
# print initial help menu
print(self._get_help_men... |
"""
Coverers of the filtrated space
"""
from __future__ import print_function
from sklearn.base import BaseEstimator, TransformerMixin
import numpy as np
class HyperRectangleCoverer(BaseEstimator, TransformerMixin):
""" Covers the space using overlapping hyperectangles
Parameters
----------
intervals: i... |
from command import Command, is_command
from event import Event
class Say(Command):
shortname = 'say'
name = 'Say something to someone, or in the public chat'
@is_command
def say(self, player, *args):
if args[0] in self.world.players:
prefix = "(private) <%s> " % player.name
... |
from abc import ABCMeta
from up.utils.up_logger import UpLogger
class BaseModule(metaclass=ABCMeta):
LOAD_ORDER = 0
def __init__(self, silent=False):
self.__silent = silent
self.__logger = UpLogger.get_logger()
self.__up = None
def initialize(self, up):
self.__up = up
... |
import urllib2
import base64
import json
from link import *;
from GitFetcher import GitHubFetcher;
username = "debuggerman"
password = "megadeth"
orgUrl = "https://api.github.com/orgs"
orgName = "coeus-solutions"
gitFetcher = GitHubFetcher(username = username, password = password, orgUrl = orgUrl, orgName = orgName)
gi... |
def print_banner(s):
print('##------------------------------------------------------------------------------')
print(f'## {s}')
print('##------------------------------------------------------------------------------')
print_banner('First implementation')
class Base:
def foo(self):
raise NotImple... |
import functools
import operator
class Env(dict):
"""
Computational environment for some expression.
Implemented with recursive composition -
each environment has the outer environment.
Every lookup for a name N in the environment E
with outer environment O goes like this:
1) E.lookup(N)
... |
import cv2
from collections import namedtuple
import logging
import re
import os
RecorderConfig = namedtuple('RecorderConfig',
['file_limit',
'time_limit',
'directory',
'file_base'],
... |
from ..models.checksum import Checksum
from ..models.address import Address
from ..models.shopping_cart_item import ShoppingCartItem
from ..models.shopping_cart import ShoppingCart
from .paymill_service import PaymillService
import json
__author__ = 'yalnazov'
class ChecksumService(PaymillService):
def endpoint_pat... |
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
... |
"""
This file is part of the web2py Web Framework
Copyrighted by Massimo Di Pierro <mdipierro@cs.depaul.edu>
License: LGPLv3 (http://www.gnu.org/licenses/lgpl.html)
Provides:
- List; like list but returns None instead of IndexOutOfBounds
- Storage; like dictionary allowing also for `obj.foo` for `obj['foo']`
"""
import... |
import pandas as pd
import numpy as np
import sqlite3
from bokeh.plotting import Figure
from bokeh.models import (
CategoricalColorMapper,
HoverTool,
ColumnDataSource,
Panel,
FuncTickFormatter,
SingleIntervalTicker,
LinearAxis,
)
from bokeh.models import Legend
from bokeh.models.widgets impo... |
import sys, subprocess, time
"""
This script is made as a wrapper for sc2 bots to set a timeout to the bots (in case they cant find the last enemy structure or the game is ending in a draw)
Usage:
cd into python-sc2/ directory
docker build -t test_image -f test/Dockerfile .
docker run test_image -c "python test/travis_... |
""" S3 Query Construction
@copyright: 2009-2015 (c) Sahana Software Foundation
@license: MIT
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 w... |
"""
Main __init__.py for the vsgen package
"""
import pkg_resources
try:
pkg = pkg_resources.get_distribution("vsgen")
__version__ = pkg.version
except pkg_resources.DistributionNotFound:
__version__ = "0.0.0.0"
from vsgen.solution import VSGSolution
from vsgen.project import VSGProject
from vsgen.register ... |
import os
workingdir = os.path.dirname(os.path.realpath(__file__))
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
import cgi
import imp
modulesdir = workingdir+"/../modules"
common = imp.load_source("common", modulesdir+"/common.py")
colors = imp.load_source("colors", modulesdir+"/colors.py")
try:
if common.au... |
from __future__ import print_function
import optparse
import os
import re
import sys
__VERSION__ = '0.0.2'
__URL__ = "https://github.com/blankenberg/Kraken-Taxonomy-Report"
NO_RANK_NAME = "no rank"
RANK_NAMES = [ NO_RANK_NAME,
"root",
"superkingdom",
"kingdom",
... |
from django.contrib.auth.models import User
from django.test import TestCase, Client
from django.urls import reverse
username = 'admin'
password = 'Test1234$'
"""
Method to replicate
~~~~~~~~~~~~~~~~~~~
1. Bring up a new instance of NearBeach (grab from fixtures)
2. Try and log in as the admin user
Expected Results
~~~... |
def solution(a):
l = len(a)
if l < 3: return reduce(lambda x, y: x * y, a)
products = []
for i in xrange(0, l):
for j in xrange(i+1, l):
for k in xrange (j+1, l):
products.append(a[i] * a[j] * a[k])
return max(products)
if __name__ == '__main__':
array = [ -3 , 1 , 2 , -2 , 5 , 6]
prin... |
"""
asm.py - (dis)assembly features.
(c) 2014 Samuel Groß
"""
from willie import web
from willie.module import commands, nickname_commands, example
from random import choice
from binascii import hexlify, unhexlify
import string
import re
import os
from subprocess import Popen, PIPE
@commands('disas', 'disas64', 'disass... |
from setuptools import setup
setup(
name="sgf",
version="0.5",
description="Python library for reading and writing Smart Game Format",
license="MIT",
url="http://github.com/jtauber/sgf",
author="James Tauber",
author_email="jtauber@jtauber.com",
py_modules=["sgf"],
classifiers=[
... |
from math import *
def i321():
n = 0L
mn = 0L
tn = 0L
sn = 0L
n3 = 0L
n9 = 0L
n = 372889431
mn = 139046528497282623
tn = 1L + 8L * mn
print "M(%i) = %i\n" % (n, mn)
print "sqrt(%d) = %i\n" % (n, sqrt(n))
print "sqrt(%d) = %i\n" % (tn, sqrt(tn))
print "sqrt(%i) mod 1 = %i\n" % (tn, sqrt(tn) % 1... |
""" """
from rowgenerators.appurl.file.file import FileUrl
from rowgenerators.exceptions import AppUrlError
class ZipUrlError(AppUrlError):
pass
class ZipUrl(FileUrl):
"""Zip URLS represent a zip file, as a local resource. """
match_priority = FileUrl.match_priority - 10
def __init__(self, url=None, dow... |
from Scraping4blog import Scraping4blog
import sys,os
sys.path.append(os.path.dirname(os.path.abspath(__file__)) + '/../util')
from settings import SettingManager
def main():
conf = SettingManager()
instance = Scraping4blog(conf)
instance.run()
if __name__ == "__main__":
main() |
class Solution(object):
def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
low=1<<31
profit=0
for p in prices:
if p<low:
low=p
if p-low>profit:
profit=p-low
return profit |
import collections
import functools
import dpath
import six
import pprint
import stringcase
from pyutrack.logger import get_logger
def print_friendly(value, sep=', '):
if isinstance(value, six.string_types):
return value
if isinstance(value, collections.Iterable):
return sep.join(str(k) for k in... |
import os
import glob
import math
import subprocess
import re
import sys
import string
from decimal import Decimal
from astropy.io import fits
from astropy.wcs import WCS
import matplotlib.pyplot as plt
import numpy as np
import numpy.ma as ma
from scipy.ndimage import median_filter
import argparse
import pandas as pd
... |
import _plotly_utils.basevalidators
class FamilysrcValidator(_plotly_utils.basevalidators.SrcValidator):
def __init__(
self,
plotly_name="familysrc",
parent_name="funnelarea.hoverlabel.font",
**kwargs
):
super(FamilysrcValidator, self).__init__(
plotly_name=pl... |
import datetime
import warnings
import re
from math import ceil
from collections import namedtuple
from contextlib import contextmanager
from distutils.version import LooseVersion
import numpy as np
from pandas.util.decorators import cache_readonly, deprecate_kwarg
import pandas.core.common as com
from pandas.core.comm... |
from __future__ import absolute_import
import logging
from uuid import uuid1
import dockets.queue
import dockets.error_queue
from .base import Queue
class DocketsQueue(Queue):
def __init__(self, redis_client, queue_name, wait_time, timeout):
self.queue = dockets.queue.Queue(redis_client,
... |
import six
import warnings
from .. import errors
from ..utils.utils import (
convert_port_bindings, convert_tmpfs_mounts, convert_volume_binds,
format_environment, normalize_links, parse_bytes, parse_devices,
split_command, version_gte, version_lt,
)
from .base import DictType
from .healthcheck import Healt... |
from ast import literal_eval
from json import dumps, loads
from urllib2 import Request, urlopen
from requests import post, get
from p3lzstring import LZString
def user_input(data):
i = 0
while i < len(data):
if 'xp' in data[i]['dragondata']['sidekick_name'][9:][5:]:
data[i]['dragondata']['va... |
__author__ = 'Steven Brien'
__email__ = 'sbrien@hlkagency.com'
__version__ = '0.1.0' |
from __future__ import division
import myhdl
from myhdl import instance, delay
ClockList = []
class Clock(myhdl.SignalType):
def __init__(self, val, frequency=1, timescale='1ns'):
self._frequency = frequency
self._period = 1/frequency
self._timescale = timescale
self._hticks = 0
... |
import io
from pathlib import Path
from typing import Mapping
import fontTools.designspaceLib
import fontTools.ttLib
import fontTools.ttLib.tables._n_a_m_e
import fontTools.varLib
import ufo2ft
import ufoLib2
import statmake.classes
import statmake.lib
def dump_axes(font, axes_array):
dump_list = []
for axis in... |
import os
import sys
import pprint
sys.path.append(os.path.join(os.path.dirname(__file__), '..'))
from m2x.client import M2XClient
KEY = os.environ['KEY']
DEVICE_ID = os.environ['DEVICE']
client = M2XClient(key=KEY)
device = client.device(DEVICE_ID)
pprint.pprint(device.data) |
"""
Setup script for the Gimbal package
"""
from setuptools import setup
from setuptools import find_packages
def readme():
"""Returns the contents of the README without the header image."""
header = '======\nGimbal\n======\n'
with open('README.rst', 'r') as f:
f.readline()
return header + f... |
import hashlib
import shutil
import os
from datetime import datetime
list_of_paths_and_strings = [
["assignment1.cpp", "main()"]
]
def main():
if acceptance_test():
make_txt_file()
zip_dir()
def get_md5_hash(file):
# opening file
file_to_hash = open(file)
read_file = file_to_hash.read()
# get hash of file
md5... |
from django.db import models
from django.db.models import Count
from belt.managers import SearchQuerySetMixin
class PostQuerySet(SearchQuerySetMixin, models.QuerySet):
pass
class CategoryQuerySet(SearchQuerySetMixin, models.QuerySet):
pass
class BlogQuerySet(SearchQuerySetMixin, models.QuerySet):
def annota... |
import logging
from .generic import *
from criacao.forms import *
from criacao.models import *
from gerenciamento.models import *
logger = logging.getLogger(__name__)
class LinkView(GenericView):
def criar(self, request):
if request.method == 'POST':
try:
name = request.POST['name']
url = request.POST['ur... |
import argparse
import nltk
import os
import re
default_regex = "^(?!http|\d)\w{2,}"
def filter_corpus_data(string_data, stopwords=[], use_nltk_default=True):
# Tokenize and get the words
tokenizer = nltk.tokenize.TweetTokenizer(preserve_case=False, strip_handles=True)
tokens = tokenizer.tokenize(string_dat... |
import sys
import wx
import wx.dataview as dv
class MyCustomRenderer(dv.DataViewCustomRenderer):
def __init__(self, log, *args, **kw):
dv.DataViewCustomRenderer.__init__(self, *args, **kw)
self.log = log
self.value = None
def SetValue(self, value):
#self.log.write('MyCustomRender... |
from findSentence import sentenceGrab
from phoneticWords import findPhonetics
from phoneticIndex import findPhoneticIndex
from random import randint
from math import floor
import sys
def main():
library = sys.argv[1]
subject = sys.argv[2]
dictionary = "/usr/share/dict/words"
phonetics = findPhonetics(su... |
import numpy as np
import util
from datetime import datetime
from scipy.stats import norm
import better_exceptions
from scipy.stats import multivariate_normal as mvn
class NaiveBayers(object):
def __init__(self):
# Gaussian deviation
self.gaussians = dict()
# Class priors
self.priors... |
import collections
import functools
from typing import List
from test_framework import generic_test
from test_framework.test_utils import enable_executor_hook
Rect = collections.namedtuple('Rect', ('left', 'right', 'height'))
def compute_skyline(buildings: List[Rect]) -> List[Rect]:
# TODO - you fill in here.
r... |
import sys
import os
import traceback
from django import db
sys.path.append('/root/wisely/wisely_project/')
os.environ['DJANGO_SETTINGS_MODULE'] = 'wisely_project.settings.production'
from django.db.models import F, Q
from django.utils import timezone
from users.tasks import get_coursera_courses, get_edx_courses, get_u... |
import importlib
import json
import os
from datetime import datetime
from hackathon.log import log
try:
from config import Config
except ImportError:
from config_sample import Config
__all__ = [
"get_config",
"safe_get_config",
"get_class",
"load_template",
"call",
"get_now",
"Utilit... |
import unittest
import slowboy.gpu
import slowboy.interrupts
from tests.mock_interrupt_controller import MockInterruptController
STAT_IE_ALL_MASK = (slowboy.gpu.STAT_LYC_IE_MASK |
slowboy.gpu.STAT_OAM_IE_MASK |
slowboy.gpu.STAT_HBLANK_IE_MASK |
slowboy.gpu.STA... |
import random
def roll(qty, sides):
return sum(random.randrange(1, sides + 1) for _ in range(qty))
def chances(qty, out_of):
"""'1 chance in 5' is chances(1, 5)"""
# Chance succeeds if roll is lower than max.
return roll(1, out_of) <= qty |
from datetime import datetime
from app.model import db
class FeedRecord(db.Model):
__tablename__ = 'feeds'
id = db.Column(db.Integer, primary_key=True)
time = db.Column(db.DateTime, default=datetime.now())
quant = db.Column(db.Integer)
def __repr__(self):
return 'At %s eat %d ml' % (str(self.time), self.quant) |
'''
Setup.py script.
'''
__author__ = 'riko'
from Cython.Build import cythonize
import numpy
from setuptools import setup, Extension, find_packages
try:
use_cython = True
from Cython.Distutils import build_ext
except ImportError:
use_cython = False
ext = '.pyx' if use_cython else '.c'
ext_modules = [Extensi... |
import pytest
TEST_HASHES = {
"test": "Jnh+8wNnELksNFVbxkya8RDrxJNL13dUWTXhp5DCx/quTM2/cYn7azzl2Uk3I2zc",
"test2": "sh33L5uQeLr//jJULb7mAnbVADkkWZrgcXx97DCacueGtEU5G2HtqUv73UTS0EI0",
"testing100" * 10: "5rznDSIcDPd/9rjom6P/qkJGtJSV47y/u5+KlkILROaqQ6axhEyVIQTahuBYerLG",
}
@pytest.mark.parametrize(('password'... |
from __future__ import absolute_import
import csv
from django.contrib import admin
from django.http import HttpResponse
from .models import Donor, Donation
class DonationInline(admin.TabularInline):
model = Donation
extra = 0
@admin.register(Donor)
class DonorAdmin(admin.ModelAdmin):
inlines = [
Don... |
import copy
def execute(moves):
players = [
{'name': 'Xena', 'score': 0},
{'name': 'Ophelia', 'score': 0},
]
idx = 0
first_player = 0
draw_count = 0
move_count = 0
init_map = [[False]*3, [False]*3, [False]*3]
map = copy.deepcopy(init_map)
for move in moves:
mo... |
import thoonk
from thoonk.feeds import SortedFeed
import unittest
from ConfigParser import ConfigParser
class TestLeaf(unittest.TestCase):
def setUp(self):
conf = ConfigParser()
conf.read('test.cfg')
if conf.sections() == ['Test']:
self.ps = thoonk.Thoonk(host=conf.get('Test', 'h... |
from mininet.net import Mininet
from ..util import findPyroObjectOrNone
def monkeypatch(cls):
def decorator(func):
setattr(cls, func.__name__, func)
return func
return decorator
def getOneNodeByName(net, name):
if name in net.nameToNode:
return net.nameToNode[name]
else:
return findPyroObjectOrN... |
'''
Geometry Transform
''' |
import numpy as np
import scipy.cluster.hierarchy as hr
import scipy.spatial as spa
import clustering
import matplotlib.pyplot as plt
from sklearn.cluster import AgglomerativeClustering
import filter
class textMiningEac:
def __init__(self,k,N,low,high=0):
self.k = k
# Leer datos desde archivo [Tempo... |
import os
import re
import subprocess
import time
import sys
import random
import string
from Queue import Queue, Empty
from threading import Thread
from datetime import date
from sonLib.bioio import logger
from sonLib.bioio import system
from jobTree.batchSystems.abstractBatchSystem import AbstractBatchSystem
from job... |
from django.conf.urls import re_path
from . import views
app_name = 'topic'
urlpatterns = [
re_path(r'^$', views.deleted, name='index'),
re_path(r'^deleted/$', views.deleted, name='deleted'),
re_path(r'^closed/$', views.closed, name='closed'),
re_path(r'^pinned/$', views.pinned, name='pinned'),
] |
class NoResultScraped(Exception):
pass
class NotCompleteParse(Exception):
pass
class CouldNotAuthorize(Exception):
pass |
"""
WSGI config for c2asm project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.10/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTINGS_MO... |
from datetime import datetime
from xml.etree import ElementTree
import pkgutil
from json import loads as base_loads
from random import choice
import logging
import re
import urlparse
from sleekxmpp import ClientXMPP
from redis import Redis, ConnectionPool
import requests
from humanize import intcomma, naturaltime, intw... |
import os, sys
import mercadopago
def index(req, **kwargs):
mp = mercadopago.MP("CLIENT_ID", "CLIENT_SECRET")
topic = kwargs["topic"]
merchant_order_info = None
if topic == "payment"
payment_info = mp.get("/collections/notifications/"+kwargs["id"])
merchant_order_info = mp.get("/merchant... |
from pprint import pformat
from sqlalchemy import Column, ForeignKey, orm
from sqlalchemy.types import String, Integer, Boolean, Text
from sqlalchemy.schema import UniqueConstraint
from intranet3 import memcache
from intranet3.models import Base, User
from intranet3.log import WARN_LOG, INFO_LOG, DEBUG_LOG
LOG = INFO_L... |
import math
def add_vectors(vector1, vector2):
#Note the vectors are tuple (angle, magnitude)
x = math.sin(vector1[0]) * vector1[1] + math.sin(vector2[0]) * vector2[1]
y = math.cos(vector1[0]) * vector1[1] + math.cos(vector2[0]) * vector2[1]
mag = math.hypot(x, y)
angle = (math.pi/2) - math.atan2(y, x)
return (an... |
import numpy as np
from numpy import ma
from matplotlib import pyplot as plt
from mpl_toolkits.basemap import Basemap as bm
from mpl_toolkits.basemap import addcyclic
import palettable
class vector_plot:
def __init__(self, ucompos, vcompos):
self.ucompos = ucompos
self.vcompos = vcompos
self... |
from django.test import TestCase
from ...models import Office
class PublishedMixinTest(TestCase):
def test_only_published_manager_and_queryset_default_datetime(self):
data = [
dict(published=False, address='office', office='not_published'),
dict(office='published', address='some adre... |
SITENAME = "Marc Sleegers"
DOMAIN = "marcsleegers.com"
BIO_TEXT = "Infrequent ramblings."
FOOTER_TEXT = '© 2022 Marc Sleegers. Licensed <a href="https://creativecommons.org/licenses/by/4.0/">CC BY 4.0</a>.'
SITE_AUTHOR = "Marc Sleegers"
TWITTER_USERNAME = "@marcardioid"
GOOGLE_PLUS_URL = ""
INDEX_DESCRIPTION = "Le... |
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits import mplot3d
def direction(d,t):
# if type == uniform
if(t == 'u'):
return np.random.uniform(-1/np.sqrt(2), 1/np.sqrt(2), d)
elif(t == 'n'):
return np.random.normal(0, 1/np.sqrt(d), d)
elif(t == 's'):
# a poin... |
from __future__ import (unicode_literals, absolute_import,
division, print_function)
from snisi_reprohealth.models.PFActivities import (PFActivitiesR, AggPFActivitiesR) |
from __future__ import print_function
import collections
import logging
import os
import platform
import re
import subprocess
import types
import util
import json
from ebstall.versions import Version
from ebstall.util import normalize_string
logger = logging.getLogger(__name__)
CLI_DEFAULTS_DEFAULT = dict(
packager... |
import boto
from boto.s3.connection import OrdinaryCallingFormat
from fabric.api import prompt
def confirm(message):
"""
Verify a users intentions.
"""
answer = prompt(message, default="Not at all")
if answer.lower() not in ('y', 'yes', 'buzz off', 'screw you'):
exit()
def replace_in_file(fi... |
"""Utilities for the instance-groups managed update-instances commands."""
import re
from googlecloudsdk.calliope import exceptions
STANDBY_NAME = 'standby'
TARGET_SIZE_NAME = 'target-size'
TEMPLATE_NAME = 'template'
def _ParseFixed(fixed_or_percent_str):
"""Retrieves int value from string."""
if re.match(r'^\d+$',... |
from reads.conf.development import * # NOQA |
eveapi = local_import('eveapi')
def is_igb():
return 'http_eve_charid' in request.env
def auto_vivify(charid):
if db(db.char.charid==charid).count():
return # character id already exists in db
api = eveapi.EVEAPIConnection()
try:
el = api.eve.CharacterName(ids=str(charid))
charn... |
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from qrtextedit import ScanQRTextEdit
import re
from decimal import Decimal
from electrum import bitcoin
import util
RE_ADDRESS = '[1-9A-HJ-NP-Za-km-z]{26,}'
RE_ALIAS = '(.*?)\s*\<([1-9A-HJ-NP-Za-km-z]{26,})\>'
frozen_style = "QWidget { background-color:none; border:... |
import Parser, Lexer
from DSL import _lexerParser, _lexerLexer
from DSL import _parserLexer, _parserParser
from DSL import makeParser, makeLexer
lexerLexerConfig = r"""#dsl
%keys ::= '%ignore' '%keys' '::='
comment ::= /#[^\n]*\n/
identifier ::= /[_a-zA-Z][_a-zA-Z0-9]*/
sqString ::= /'[^']*'/
dqStri... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.