code stringlengths 1 199k |
|---|
class Sourcefile(Dashboard.Module):
"""Show the program source code, if available."""
def __init__(self):
self.file_name = None
def label(self):
return 'Sourcefile'
def lines(self, term_width, style_changed):
if self.output_path is None:
return []
# skip if th... |
""" SYNC Synchronisation, Controllers
@author: Amer Tahir
@author: nursix
@version: 0.1.0
"""
prefix = "sync" # common table prefix
module_name = T("Synchronization")
response.menu_options = admin_menu_options # uses the admin menu in 01_menu.py
def index():
""" Module's Home Page """
response.title... |
import doctest
import os.path
import re
import sys
import tempfile
from functools import wraps
from os.path import dirname, expanduser, isdir, isfile, join
import fabric.api
import fabric.contrib.files
import fabric.operations
import utlz
from fabric.context_managers import quiet
from fabric.state import env
from fabri... |
def combo_string(a, b):
if len(a) > len(b):
return b + a + b
else:
return a + b + a |
import sys
import yaml
from urllib.parse import urlparse
with open("sites.yaml", 'r') as stream:
sites = yaml.safe_load(stream)
try:
name = sys.argv[1]
feedurl = input("URL: ")
parsed = urlparse(feedurl)
if not (parsed.scheme and parsed.netloc and parsed.path):
print("invalid URL")
e... |
import os
import sys
import shutil
current_dir = 'C:/HYSPLIT_argh/WHI_1h_10-day_endpoints/'
os.chdir(current_dir)
for filename in os.listdir('.'):
file_hour = int(filename[-2:])
if file_hour%2 != 0:
print file_hour
shutil.move('C:/HYSPLIT_argh/WHI_1h_10-day_endpoints/'+filename, 'C:/HYSPLIT_argh/WHI_1h_10-day_arc... |
import logging
import sys
import aiohttp_jinja2
logging.basicConfig(stream=sys.stdout, level=logging.DEBUG)
logger = logging.getLogger(__name__)
class Handlers(object):
@aiohttp_jinja2.template('index.html')
async def root(self):
context = {'name': 'Andrew', 'surname': 'Svetlov'}
response = aioh... |
import cv2
import cv
import numpy as np
from scipy import signal as sig
import Evaluation
import time
def segmentation_plan(adresseVid):
print "debut"
print time.localtime()
#Avec les parametres pour lintersection
cont = Contours(1.6, 7, adresseVid)
print "contours cree"
print time.localtime()
hist = Histogramme... |
import rospy, tf, math
from heapq import *
from lab5Helpers import *
from geometry_msgs.msg import PoseWithCovarianceStamped #format for reading the start and goal points
from geometry_msgs.msg import PoseStamped
from geometry_msgs.msg import Point
from geometry_msgs.msg import Point
from nav_msgs.msg import OccupancyG... |
"""
chemdataextractor.parse.base
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from abc import abstractproperty, abstractmethod
import logging
log = logging.getLogger(__name__)
class B... |
from collections import OrderedDict
from os import path as osp
import numpy as np
import torch
from torch import optim
from torch.distributions import Normal
from torch.utils.data import DataLoader
from torchvision.utils import save_image
from multiworld.core.image_env import normalize_image
from rlkit.core import logg... |
import csv
import json
header = ['Semester', 'Class Number', 'Subject', 'Catalog Number',
'Section', 'Course Component', 'Course Title',
'Units', 'Facility', 'Meeting Days',
'Start Time', 'End Time', 'Instructor Name']
reader_f = open('data/grad_schedule.csv', 'r')
reader = csv.reader(read... |
from Root import application
import unittest
class test210(unittest.TestCase):
def test_one(self):
self.assertEqual(3,1)
if __name__ == '__main__':
unittest.main() |
from app import Handler
from entities.like import Like
from entities.post import Post
from handlers.auth import Auth
from webapp2_extras import json
class LikeHandler(Handler):
def post(self):
if not Auth.is_logged_in(self.request):
self.response.content_type = 'application/json'
res... |
from unittest import TestCase
from raven.utils.serializer import transform
class DemoTestCase(TestCase):
def test_handles_gettext_lazy(self):
import pickle
from django.utils.functional import lazy
def fake_gettext(to_translate):
return u'Igpay Atinlay'
fake_gettext_lazy =... |
from setuptools import setup, find_packages
setup(
name="etlcookbook",
version="0.0.1",
packages=find_packages()
) |
import cgi
import cgitb
import lib.univie as univie
import lib.gcalexport as gcalexport
import layout
import datetime
PROJECT_ROOT = '/univie2gcal_root'
def get_list_semesters():
prefix = ["S", "W"]
long_prefix = ["S", "W"]
curmonth = int(datetime.datetime.now().strftime("%m"))
if curmonth >= 2 and curmonth < 7:
... |
import game
from game import *
import unittest
class GameTest(unittest.TestCase):
# def test_acceptance_test(self):
# val monteCarlo = new MonteCarlo()
#val winProba = monteCarlo.winProbability()
#winProba should be <= 1.0
#winProba should be >= 0.7
def test_game_lost_after_nine_crows(self):
... |
"""This module defines TemplateExporter, a highly configurable converter
that uses Jinja2 to export notebook files into different formats.
"""
from __future__ import print_function, absolute_import
import os
from IPython.utils.traitlets import MetaHasTraits, Unicode, List, Dict, Any
from IPython.utils.importstring impo... |
import base64
import binascii
import hashlib
import hmac
import random
import struct
import sys
from . import ql2_pb2
from .errors import *
try:
xrange
except NameError:
xrange = range
class HandshakeV0_4(object):
VERSION = ql2_pb2.VersionDummy.Version.V0_4
PROTOCOL = ql2_pb2.VersionDummy.Protocol.JSON
... |
from sys import argv
from os.path import exists
import xml.etree.ElementTree as etree
import getopt
import json
print("This is a small program to analyse your Taskcoach file")
try:
script, taskfile = argv
except getopt.GetoptError:
print("Usage: %s <toachcoach_file.tsk>" % script)
exit(2)
if exists(taskfile):
tk_fi... |
from bottle import jinja2_template as template, request
from models.cmsmodels import Email
import admin.session as withsession
@withsession.app.app.route('/contact', method=['GET', 'POST'])
@withsession.issessionactive()
def contact():
try:
if request.method == 'GET':
email = Email.objects.get()... |
import _plotly_utils.basevalidators
class MaxpointsValidator(_plotly_utils.basevalidators.NumberValidator):
def __init__(self, plotly_name="maxpoints", parent_name="bar.stream", **kwargs):
super(MaxpointsValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
... |
from wtforms import Form, TextField, PasswordField, RadioField, validators
from wtforms.fields import html5
class LoginForm(Form):
email = html5.EmailField('Email', [validators.Required(message="Enter a valid email"), validators.Email(message="Enter a valid email")])
password = PasswordField('Password', [valida... |
import gencommon
import jagbasecfg
import introspect
import sig
import heapq
from string import Template
from pygccxml import declarations
cpp_class_body="""
class ${cpp_name}
{
${c_handle} m_obj;
public:
${body}
public: // operators + destructor
static void unspecified_bool(${cpp_name}***)
{
}
type... |
from typing import Any
from niltype import Nil, Nilable
from .._props import Props
from .._schema_visitor import SchemaVisitor
from .._schema_visitor import SchemaVisitorReturnType as ReturnType
from ..errors import make_already_declared_error
from ._schema import Schema
__all__ = ("ConstSchema", "ConstProps",)
class C... |
import numpy
def min_and_idxs(np_arr):
upper_tri = np.triu(np_arr)
m_a = np.ma.masked_equal(upper_tri, 0.0, copy=False)
idxs_min_T = np.where(m_a == m_a.min())
idxs_min = np.asarray(idxs_min_T).T
idxs_min_tuples = [tuple(idx_pair) for idx_pair in idxs_min]
# print(idxs_min_tuples)
# return {... |
from qstat import *
from util import *
results = qstat_process(qstat(user="tmaxson")+qstat(user="zeng46"))
zeng = subset(results, lambda x: "zeng46" in x["Owner"])
for id in zeng:
if zeng[id]["State"] == "R":
continue
print id, zeng[id]["Name"] |
import json
from pyramid.renderers import render, Response
from src.sgd.frontend import config
from pyramid.view import notfound_view_config
from src.sgd.frontend.yeastgenome import send_message
from src.sgd.tools.blast import do_blast
from src.sgd.tools.patmatch import do_patmatch
from src.sgd.tools.seqtools import do... |
from django.shortcuts import render, redirect, HttpResponse
from models import Article, ArticleType, User, Reply
from forms import ArticleForm, UserForm, UserProfileForm
from django.contrib.auth import authenticate, login, logout
from django.http import HttpResponseRedirect
from django.contrib.auth.decorators import lo... |
import os
import sys
import json
from datetime import datetime
__areas__ = json.loads(open(os.path.join(os.path.dirname(__file__),
'areas.json')).read())
__verification_code_map__ = {
0: '1',
1: '0',
2: 'X',
3: '9',
4: '8',
5: '7',
6: '6',
7: '5',
8: '4',
... |
import readline
import logging
import time
LOG_FILENAME = '/tmp/completer.log'
logging.basicConfig(filename=LOG_FILENAME,
level=logging.DEBUG,
)
class BufferAwareCompleter(object):
def __init__(self, options):
self.options = options
self.current_candidates = [... |
""" Sahana Eden Fire Models
@copyright: 2009-2016 (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... |
import unittest
from abc import ABCMeta
from testhelpers import TypeUsedInTest, get_classes_to_test, create_tests
from useintest.modules.irods.setup_irods import setup_irods
from useintest.modules.irods.helpers import IrodsSetupHelper
from useintest.modules.irods.services import irods_service_controllers, IrodsServiceC... |
from __future__ import division
from __future__ import print_function
from __future__ import absolute_import
from __future__ import unicode_literals
import pytest
from tableschema_bigquery.mapper import Mapper
def test_mapper_convert_bucket():
mapper = Mapper('prefix_')
assert mapper.convert_bucket('bucket') ==... |
from random import randint, random
from unittest import TestCase, skip
from math import cos, sin
from utils import parse
def rand_int():
return randint(-100, 100)
def rand_float():
return random() * rand_int()
rand = rand_float
class TestUtils(TestCase):
xs = [(rand(), abs(rand()), rand()) for i in range(10... |
from django.template import RequestContext
from django.shortcuts import render_to_response, get_object_or_404
def view_parties(request):
from parties.models import Party
return render_to_response('parties/index.html',
{
'parties': Party.objects.all().... |
import random
def construit_suite(n):
"""construit une liste de n nombres entiers compris entre 0 et 99"""
l = []
for i in range(0,n):
l.append (random.randint(0,100))
return l
def recherche_dichotomique (l,x):
"""cherche l'élément x dans la liste l, la liste l est
supposée être triée pa... |
from pyramid.view import view_config
@view_config(route_name='tutorial4', renderer='projectconway:templates/tutorial-4.mako')
def tutorial4_view(request):
'''
Executes the logic for the fourth tutorial web page, allowing the user to access the
fourth page of the tutorial process.
'''
return {'title'... |
"""
WSGI config for web_dev_final_project 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
from whitenoise.django im... |
""" Deprecated Google Trends API """
from __future__ import print_function, unicode_literals, division, absolute_import
from builtins import (bytes, dict, int, list, object, range, str, # noqa
ascii, chr, hex, input, next, oct, open, pow, round, super, filter, map, zip)
from future import standard_library
standard... |
'''
Experiment to create a simple lookup cache
Author: Dave Cuthbert
Copyright: 2016
License: MIT
'''
def func_fact(x):
"""
>>> func_fact(0)
0
>>> func_fact(1)
1
>>> func_fact(4)
24
>>> func_fact(10)
3628800
>>> func_fact(20)
2432902008176640000L
"""
if x == 0:
... |
import salt.exceptions
def build_site(name, output="/srv/www"):
# /srv/salt/_states/pelican.py
# Generates static site with pelican -o $output $name
# Sorry.
# -- Jadon Bennett, 2015
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
current_state = __salt__['pelican.current_sta... |
"""
Folium Tests
-------
"""
import pytest
import os
import json
try:
from unittest import mock
except ImportError:
import mock
import pandas as pd
import jinja2
from jinja2 import Environment, PackageLoader
import vincent
import folium
import base64
from folium.six import PY3
from folium.element import Html
fr... |
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
with open('gridData.txt', 'r') as f:
for line in f:
strLine = line.split()
if strLine[0] == 'domain':
x_0, x_L, y_0, y_L = float(strLine[1]), float(strLine[2]), float(strL... |
import sys
from genStubs import *
stub = Stubs( "gpsBsp", sys.argv[1], sys.argv[2] )
stub.include("gps/gpsBsp.h")
stub.include("bsp_spi.h")
stub.newline()
stub.stubFunction( ("bool","true"), "BSP_OSInit" )
stub.stubFunction( ("BSP_BctErr_t","BCT_ERR_NONE"), "BSP_Init" )
stub.stubFunction( ("SpiDrvErr_t","SPI_DRV_ERR_NO... |
from database_handler import DatabaseHandler |
tw = 32
th = 32
tileSize = 32
class Sprite(object):
def __init__(self, posX, posY):
self.x = posX
self.y = posY
self.dir = 1
self.dx = 0
self.dy = 0
def checkCollision(self, otherSprite):
if (self.x < otherSprite.x + tw and otherSprite.x < self.x + tw
... |
import regex
def separate_string(string):
"""
>>> separate_string("test <2>")
(['test ', ''], ['2'])
"""
string_list = regex.split(r'<(?![!=])', regex.sub(r'>', '<', string))
return string_list[::2], string_list[1::2] # Returns even and odd elements
def overlapping(start1, end1, start2, end2):
... |
from .geohex import * |
import sys
from contextlib import contextmanager
import lldb
import debugger
indent = 0
@contextmanager
def indent_by(n):
global indent
indent += n
try:
yield None
finally:
indent -= n
def iprint(*args, **kwargs):
sys.stdout.write(' ' * indent)
print(*args, **kwargs)
def eval(exp... |
import os
import os.path
import readline
import subprocess
import sys
import threading
import time
sys.path.insert(0, 'module/')
sys.path.insert(0, 'lib/')
from Sniffer import *
from Connect2DB import *
from Queries import *
import Discover_Hidden_SSID
from Discover_Hidden_SSID import *
import Suspicious_AP
from Suspic... |
"""
.. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com>
"""
import pytest
from simplesqlite import SimpleSQLite
TEST_TABLE_NAME = "test_table"
@pytest.fixture
def con(tmpdir):
p = tmpdir.join("tmp.db")
con = SimpleSQLite(str(p), "w")
con.create_table_from_data_matrix(TEST_TABLE_NAME, ["attr_a", ... |
from flask import Flask
from flask_bouncer import Bouncer, ensure, requires
from bouncer.constants import *
from nose.tools import *
from .models import Article, TopSecretFile, User
from .helpers import user_set
def test_non_standard_names():
app = Flask("advanced")
app.debug = True
bouncer = Bouncer(app)
... |
import sys
import unittest
import os
import tempfile
from netCDF4 import Dataset, CompoundType
import numpy as np
from numpy.testing import assert_array_equal, assert_array_almost_equal
FILE_NAME = tempfile.NamedTemporaryFile(suffix='.nc', delete=False).name
DIM_NAME = 'phony_dim'
GROUP_NAME = 'phony_group'
VAR_NAME = ... |
from http.server import BaseHTTPRequestHandler, HTTPServer
from http import cookies
from socketserver import ThreadingMixIn
import dataManagement
import time
import math
dataStor = None
_timeP = 0
def start(port, data):
global dataStor
dataStor = data
serverAddress = ('', port)
httpd = HTTPServerThread(... |
from django.conf.urls import url
from chat import views
urlpatterns = [
url(r'^(?P<chatroom_slug>[\w]+)/$', views.chatroom),
url(r'^create/$', views.chatroom),
] |
from plotly.basedatatypes import BaseTraceHierarchyType as _BaseTraceHierarchyType
import copy as _copy
class Font(_BaseTraceHierarchyType):
# class properties
# --------------------
_parent_path_str = "box.legendgrouptitle"
_path_str = "box.legendgrouptitle.font"
_valid_props = {"color", "family", ... |
import xml.etree.ElementTree as etree
import sys
import re
exclude_interface = ["wl_registry", "wl_resource"]
header_preamble = """// Generated by create_interface.py
"""
header_body = """
namespace karuta {{
namespace protocol {{
{interface_define}
}}
}}
"""
source_preamble = """// Generated by create_interface.py
"""... |
from __future__ import division, print_function, absolute_import
from setuptools import setup
import sys
if sys.version_info[0] < 3:
import __builtin__ as builtins
else:
import builtins
builtins.__EVEREST_SETUP__ = True
import everest
long_description = \
"""
EPIC Variability Extraction and Removal for Exop... |
import sys
import math
import json
import optparse
from pymongo import MongoClient
import MySQLdb as mdb
parser = optparse.OptionParser()
parser.add_option('-t', '--tables', action="store", dest="tables", help="List of exported tables by comma ", default="")
parser.add_option('--host', action="store", dest="host", help... |
from endpoint_configuration import EndpointConfiguration
from ingenico.connect.sdk.defaultimpl.authorization_type import \
AuthorizationType
class CommunicatorConfiguration(EndpointConfiguration):
"""
Configuration for the communicator.
:param properties: a ConfigParser.ConfigParser object containing co... |
from django.db import models
from django.contrib.auth.models import User
class Feed(models.Model):
titulo = models.CharField(max_length=250)
feed_url = models.URLField(unique=True, max_length=250,verify_exists=False)
public_url = models.URLField(max_length=250,verify_exists=False)
muerto = models.Boolea... |
some_number: int # variable without initial value
some_list: List[int] = [] # variable with initial value
some_number : source.python
: : punctuation.separator.colon.python, source.python
: source.python
int : source.python, support.type.python
: source.pyt... |
from setuptools import setup
setup(
name = 'redis_luamodules',
py_modules = ['redis_luamodules'],
version = '0.0.1',
description = 'Higher-level Redis Lua scripting',
author = 'Leif K-Brooks',
author_email = 'eurleif@gmail.com',
url = 'https://github.com/leifkb/redis_scripts',
keywords = ['redis', 'lua'... |
"""
tube.utils.options
~~~~~~~~~~~~~~~~~~
This module defines just the `get` function. This function retrieves
Tube options.
"""
from tube.utils import v
prefix = 'g:tube_'
def get(name, fmt=None):
"""To get the value of a Tube setting."""
if not v.eval(u"exists('{0}')".format(prefix + name), fmt=bool):
... |
import responses
from conftest import Mock
class TestHost:
@responses.activate
def test_get_hosts(self, manager):
data = Mock.mock_get('host')
hosts = manager.get_hosts()
for host in hosts:
assert type(host).__name__ == 'Host'
@responses.activate
def test_get_host(sel... |
from __future__ import unicode_literals
import django.contrib.postgres.fields.jsonb
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Batch',
... |
import itertools
computed = []
def pentagonal(n):
p = int(n*(3*n-1)/2)
if p not in computed:
computed.append(p)
return p
def is_pentagonal(p):
if p in computed:
return True
# n = something
if p>1000:
return True
n = 0.1
return n==int(n)
for j in itertools.count(st... |
import math
EARTH_RADIUS = 6378137.0
TILE_SIZE = 256
ORIGIN_SHIFT = 2.0 * math.pi * EARTH_RADIUS / 2.0
INITIAL_RESOLUTION = 2.0 * math.pi * EARTH_RADIUS / float(TILE_SIZE)
def resolution(zoom):
return INITIAL_RESOLUTION / (2 ** zoom) |
""" Data model module for appengine_multiblog
Contains data model definitions
used by Google Cloud Datastore. These are imported
by main.py
"""
from google.appengine.ext import ndb
import bleach
import jinja2
import os
TEMPLATE_DIR = os.path.join(os.path.dirname(__file__), 'templates')
JINJA_ENV = jinja2.En... |
"""
.. module:: Post
:synopsis: A generic post database model.
.. moduleauthor:: Dan Schlosser <dan@danrs.ch>
"""
from app import db
from app.models import User
from app.lib.regex import SLUG_REGEX
from datetime import datetime
import markdown
now = datetime.now
class Post(db.Document):
"""A generic post object... |
from flask import request # , make_response
__all__ = ["controller1"]
def valueFromRequest(key=None, request=None, default=None, lower=False, list=False, boolean=False):
''' Convenience function to retrieve values from HTTP requests (GET or POST).
@param key Key to extract from HTTP request.
@param... |
import sys
import random
import pygame
from pygame.locals import *
FPS = 30 #30 FPS
WINDOWWIDTH = 640
WINDOWHEIGHT = 480
REVEALSPEED = 8
BOXSIZE = 40
GAPSIZE = 10
BOARDWIDTH = 10
BOARDHEIGHT = 7
assert (BOARDWIDTH * BOARDHEIGHT) % 2 == 0, 'Board needs to have an even number of boxes for pairs of matches'
XMARGIN = int(... |
"""
flask_genshi
~~~~~~~~~~~~
An extension to Flask for easy Genshi templating.
:copyright: (c) 2010 by Dag Odenhall <dag.odenhall@gmail.com>.
:license: BSD, see LICENSE for more details.
"""
from __future__ import absolute_import
from collections import defaultdict
import os.path
from warnings impo... |
import functools
import json
import pprint as _pprint
import sublime
from contextlib import contextmanager
_log = []
enabled = False
ENCODING_NOT_UTF8 = "{} was sent as binaries and we dont know the encoding, not utf-8"
def start_logging():
global _log
global enabled
_log = []
enabled = True
def stop_lo... |
from django.contrib.auth import get_user_model
from django.db import models
class Sprint(models.Model):
"""
A Spring
"""
start_date = models.DateField()
end_date = models.DateField()
name = models.CharField(max_length=256)
def __unicode__(self):
return self.name
class Point(models.Mo... |
class NoArgumentError(Exception):
pass
class GetRequestError(Exception):
pass
class UnknownError(Exception):
pass
class NoCategoryError(Exception):
pass |
"""
WSGI config for tracking 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.7/howto/deployment/wsgi/
"""
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "tracking.settings")
from django.core.wsg... |
from collections import defaultdict as ddict
from copy import copy
class View(object):
"""
A View is made up of two components:
- A configuration: How the buttons and dials on the input device should behave
- A Map: Connects the input device's controls (by their ID) to Targets like
Paramete... |
"""
This module provides useful some useful types
Some of these types are a bit different to what a Python programmer is used to thinking
of as a type, such as dependent types and existential types
@author: Matt Pryor <mkjpryor@gmail.com>
"""
class TypeMeta(type):
"""
Base class for typing metaclasses providing... |
from hhub.plugins import LightsPlugin
import logging
from huepy import hue
from flask import Blueprint, render_template
admin = Blueprint('huepy', __name__, template_folder="templates",
static_folder='static')
@admin.route('/')
def index():
return render_template('huepy/index.html')
class HuepyPlugin(LightsPlug... |
"""
A row of five black square tiles is to have a number of its tiles replaced with
coloured oblong tiles chosen from red (length two), green (length three), or
blue (length four).
If red tiles are chosen there are exactly seven ways this can be done. If
green tiles are chosen there are three ways. And if blue tiles ar... |
import logging
from typing import NamedTuple, Optional, Mapping, Awaitable, Callable, TypeVar, Any
from solo.types import IO
from solo.vendor.old_session.old_session import SessionStore
from solo.configurator.registry import Registry
from solo.server.app import App
from solo.server.handler.http_handler import handle_re... |
from django.test.testcases import TestCase
from django_js_choices.core import generate_js
class ChoicesJSTestCase(TestCase):
"""
Test choices_js view.
"""
def test_view(self):
response = self.client.get("/choices.js")
self.assertEqual(response.status_code, 200)
self.assertContain... |
import sys
sys.path.insert(0, "..")
from haishoku.haishoku import Haishoku
def main():
path = "/Users/wujianming/Desktop/WechatIMG18547.jpeg"
# path = "http://wx2.sinaimg.cn/large/89243dfbly1ffoekfainzj20dw05k0u7.jpg"
# getPalette api
palette = Haishoku.getPalette(path)
# getDominant api
dominan... |
from bson import json_util
import copy
import json
import os
import re
import sys
try:
import requests
except ImportError as e:
print("Error! requests module could not be imported. Perhaps install it with\n\n pip install requests")
exit()
try:
import requests_toolbelt
except ImportError as e:
print("Error! requ... |
import unittest
from datetime import datetime
from sqlalchemy.exc import IntegrityError
from scrutiny import Scrutiny
from scrutiny import IPAddr, BannedIPs, BreakinAttempts, Base, SubnetDetails
class TestCase(unittest.TestCase):
def setUp(self):
self.scrutiny_instance = Scrutiny()
self.scrutiny_ins... |
import requests
def convert(apiKey, fromCode, toCode):
"""Gives the currency conversion from <fromCode> to <toCode>.
Get the API key from https://www.exchangerate-api.com/.
Currency codes must be from ISO 4217 Three Letter Currency Codes.
Keyword arguments:
apiKey -- <str>; the API key
f... |
"""
Salt Edge Account Information API
API Reference for services # noqa: E501
OpenAPI spec version: 5.0.0
Contact: support@saltedge.com
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
import pprint
import re # noqa: F401
import six
class HolderInfoAddresses(object):
"""NOT... |
from example.classes import Data
from example.utils import tempdir
import csv
import json
import six
class Csv(Data):
"""
CSV type.
"""
aliases = ['csv']
### "csv-settings"
_settings = {
'write-header' : ("Whether to write a header row first.", True),
'csv-settings' : (
... |
import inspect
import json
import os
import re
import sys
from functools import wraps
__version__ = '1.0.0'
DATA_ATTR = '%values' # store the data the test must run with
FILE_ATTR = '%file_path' # store the path to JSON file
UNPACK_ATTR = '%unpack' # remember that we have to unpack values
def unpack(func):
... |
try:
from osgeo import gdal
from osgeo.gdalnumeric import *
except ImportError:
import gdal
from gdalnumeric import *
from optparse import OptionParser
import sys
import os
AlphaList=["A","B","C","D","E","F","G","H","I","J","K","L","M",
"N","O","P","Q","R","S","T","U","V","W","X","Y","Z"]
Def... |
import argparse
import itertools
import json
import xml.etree.ElementTree
import requests
APPCAST_URL = 'https://download.docker.com/mac/{channel}/appcast.xml'
DOWNLOAD_URL = 'https://download.docker.com/mac/{channel}/{build}/Docker.dmg'
def get_latest_build_number(channel):
"""
Parse the appcast XML to find th... |
import _plotly_utils.basevalidators
class TextValidator(_plotly_utils.basevalidators.DataArrayValidator):
def __init__(self, plotly_name="text", parent_name="pie", **kwargs):
super(TextValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
edit_type=... |
class Solution(object):
def computeArea(self, A, B, C, D, E, F, G, H):
"""
:type A: int
:type B: int
:type C: int
:type D: int
:type E: int
:type F: int
:type G: int
:type H: int
:rtype: int
"""
return abs((D-B)*(C-A))+abs((G-E)*(F-H))-max(0, (min(C, G) - max(A, E))) * max(0, (min(D, H) - max(B... |
"""Syscoin P2P network half-a-node.
This python code was modified from ArtForz' public domain half-a-node, as
found in the mini-node branch of http://github.com/jgarzik/pynode.
P2PConnection: A low-level connection object to a node's P2P interface
P2PInterface: A high-level interface object for communicating to a node ... |
import argparse
import sys
import requests
from buildinfo import BuildInfo
from releases import Releases, ReleaseInfo
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--arch', default='x86_64',
help='Architecture; defaults to x86_64')
subparsers = parser.add_subpar... |
import sys, os
extensions = ['sphinx.ext.autodoc', 'sphinx.ext.doctest']
templates_path = ['_templates']
source_suffix = '.rst'
master_doc = 'index'
project = u'Elixir'
copyright = u'2010, Gaetan de Menten'
version = '0.8'
release = '0.8.0'
exclude_patterns = ['_build']
pygments_style = 'sphinx'
html_theme = 'default'
... |
"""
Chain core classes - allows cascading selection and editing of
models linked by foreign keys.
"""
import re
from django.db.models import Model, ForeignKey
from django.db.models.query import QuerySet
from django.db.models.fields.related import ManyToManyField
from django.db.models.signals import post_save, pre_delet... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.