content string |
|---|
from django.contrib import admin
from django.contrib import messages
from django.contrib.auth.models import User
from portfolios.models import Artwork
from tenant.admin import NonPublicSchemaOnlyAdminAccessMixin
from .models import Profile, create_profile
def create_missing_profiles(modeladmin, request, queryset):
... |
from tasks.hierarchy import (DenormalizedHierarchy, Hierarchy, HierarchyChildParentsUnion, HierarchyInfoUnion,
HierarchyChildParent, GetParentsFunction, LevelHierarchy, LevelInfo)
from tasks.au.geo import (GEO_STE, GEO_SA4, GEO_SA3, GEO_SA2, GEO_SA1, GEO_MB, GEO_POA,
... |
import subprocess
import logging
from .builder import Builder
from os.path import relpath
class MakefileGccArmBuilder(Builder):
# http://www.gnu.org/software/make/manual/html_node/Running.html
ERRORLEVEL = {
0: 'success (0 warnings, 0 errors)',
1: 'targets not already up to date',
2: '... |
from tempest.lib.services.volume.v3 import backups_client
from tempest.tests.lib import fake_auth_provider
from tempest.tests.lib.services import base
class TestBackupsClient(base.BaseServiceTest):
FAKE_BACKUP_LIST = {
"backups": [
{
"id": "2ef47aee-8844-490c-804d-2a8efe561c65... |
""".. module:: directory
This Python module manages the directory into which logs are saved.
"""
# enable some python3 compatibility options:
from __future__ import absolute_import, print_function
import os
class LoggingDirectory(object):
"""Logging directory object.
:param directory: Directory path in whi... |
#!/usr/bin/python3
'Make features.fea file'
# TODO: add conditional compilation, compare to fea, compile to ttf
__url__ = 'http://github.com/silnrsi/pysilfont'
__copyright__ = 'Copyright (c) 2017 SIL International (http://www.sil.org)'
__license__ = 'Released under the MIT License (http://opensource.org/licenses/MIT)'... |
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.mlab import griddata
class field:
"""This class allows "allocate and plot" a 2D FARGO3D scalar field."""
def __init__(self, input_file):
"""input_file = String, FARGO3D output field
option = XY, XZ, YZ
"""
sel... |
from __future__ import division
import numpy as np
def to_float(_input):
if _input.dtype == np.float64:
return _input, _input.dtype
elif _input.dtype == np.float32:
return _input.astype(np.float64), _input.dtype
elif _input.dtype == np.uint8:
return (_input - 128) / 128., _input.dty... |
import os
import unittest
from vsg.rules import architecture
from vsg import vhdlFile
from vsg.tests import utils
sTestDir = os.path.dirname(__file__)
lFile, eError =vhdlFile.utils.read_vhdlfile(os.path.join(sTestDir,'rule_032_test_input.vhd'))
lExpected = []
lExpected.append('')
utils.read_file(os.path.join(sTestD... |
"""Module holds classes common to test modules"""
from django.contrib.auth.models import User
from rest_framework.test import APITestCase, APIClient
from rest_framework_jwt.settings import api_settings
class ApiHeaderAuthorization(APITestCase):
"""Base class used to attach header to all request on setup."""
... |
import requests
import json
import argparse
from hashlib import md5
import networkx as nx
import pygraphviz as pgv
import matplotlib.pyplot as plt
API_ROOT = "http://ws.audioscrobbler.com/2.0/"
class ConfigException(Exception):
pass
class APIException(Exception):
pass
def parse_config(config_path):
with... |
"""Collection of helper methods.
All containing methods are legacy helpers that should not be used by new
components. Instead call the service directly.
"""
from homeassistant.components.lock import DOMAIN
from homeassistant.const import (
ATTR_CODE,
ATTR_ENTITY_ID,
ENTITY_MATCH_ALL,
SERVICE_LOCK,
... |
'''pyinfo
Functions for gathering and presenting information about the running
python program.
'''
import sys
def rawstack(depth = 1):
data = []
while depth is not None:
try:
f = sys._getframe(depth)
except ValueError:
depth = None
else:
data.a... |
"""abydos.tests.phonetic.test_phonetic_soundex_br.
This module contains unit tests for abydos.phonetic.SoundexBR
"""
import unittest
from abydos.phonetic import SoundexBR
class SoundexBRTestCases(unittest.TestCase):
"""Test SoundexBR functions.
test cases for abydos.phonetic.SoundexBR
"""
pa = So... |
import os
import fileinput
import re
import heapq
from collections import defaultdict, deque
from core.virtual_machine import VirtualMachine
class EventType:
UNKNOWN = 0
SUBMIT = 1
UPDATE = 2
FINISH = 3
NOTIFY = 4
UPDATES_FINISHED = 5
VERIFY_VMS_POOL = 6
TIME_TO_PREDICT = 7
@stati... |
"""Regression test for rosterd
Make sure you are running this against a database that can be destroyed.
DO NOT EVER RUN THIS TEST AGAINST A PRODUCTION DATABASE.
"""
__copyright__ = 'Copyright (C) 2009, Purdue University'
__license__ = 'BSD'
__version__ = '#TRUNK#'
import os
import shutil
import sys
import socket
i... |
#!/usr/bin/python
import string
import datetime
import re
import sys
import os
import subprocess
import cgi
from xml.dom.minidom import parseString
from xml.parsers.expat import ExpatError
from xml.etree.ElementTree import ElementTree, Element, SubElement, tostring
import xml.etree.ElementTree as ET
today = datetime.... |
import gudev
from common import common_logging_elasticsearch_httpx
# https://stackoverflow.com/questions/2861098/how-do-i-use-udev-to-find-info-about-inserted-video-media-e-g-dvds
def com_hard_cddvdbrrom():
client = gudev.Client(['block'])
drives = []
for device in client.query_by_subsystem("block"):
... |
"""Class for describing ion mobility data. This is used for both
small sections of the full set of mobility data (DataSlice) and whole
datasets (its the superclass of Im()).
"""
__author__ = "Ganesh N. Sivalingam <<EMAIL>>"
from imClasses import Atd
from msClasses import MassSpectrum
import numpy as np
import matplot... |
from __future__ import print_function
import random
import unittest
import test_lib as test
import sys, os.path
from sickbeard.postProcessor import PostProcessor
import sickbeard
from sickbeard.tv import TVEpisode, TVShow
from sickbeard.name_cache import addNameToCache
class PPInitTests(unittest.TestCase):
de... |
from pyrocumulus.conf import settings
from pyrocumulus.web.template import ContextProcessor
from tornado import locale
from toxicbuild import VERSION
from toxicbuild.ui.utils import get_defaulte_locale_morsel
class ToxicWebMainContextProcessor(ContextProcessor):
def get_context(self):
master_location = ... |
"""Copyright 2020 Google LLC
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
dis... |
import hassapi as hass
import datetime
#
# App to send email report for devices running low on battery
#
# Args:
#
# threshold = value below which battery levels are reported and email is sent
# always_send = set to 1 to override threshold and force send
#
# None
#
# Release Notes
#
# Version 1.0:
# Initial Version
... |
#!/usr/bin/env python
#someone always prefers setuptools over distutils.core
import os, json
#from distutils.core import setup #must import find_package, /usr/lib/python2.7/distutils/dist.py:267: UserWarning: Unknown distribution option: 'install_requires'
from distutils.core import setup
import setuptools
from os.... |
# -*- coding: utf-8 -*-
from time import time
from module.common.json_layer import json_loads
from module.plugins.Account import Account
class MyfastfileCom(Account):
__name__ = "MyfastfileCom"
__type__ = "account"
__version__ = "0.04"
__description__ = """Myfastfile.com account plugin"""
... |
import soldipubblici
import json
from collections import defaultdict
from time import sleep
import sys
from matplotlib import pyplot as plt
import matplotlib.pyplot as plt
import textwrap
class crawler():
def __init__(self):
self.comuni = self.load_data()
self.session = soldipubblici.soldi_pubblic... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
import sys
import pyexiv2
try:
from pyexiv2 import ImageMetadata
except ImportError:
print 'Error loading required module "ImageMetadata" from pyexiv2.'
sys.exit(1)
copy_tags = {
'GPSInfo': (
'GPSVersionID',
'GPSLatitudeRef',
'GPSLati... |
"""
Multipurpose RCON library in Python
by Anthony Nguyen
MIT Licensed, see LICENSE
"""
import thread
import socket
import time
class RconError(Exception):
"""Raised whenever a RCON command cannot be evaluated"""
pass
class RConnection(object):
"""
Base class for an RCON "connection", even though R... |
import re
from ecl.util.util import monkey_the_camel
from ecl.grid import EclGrid
from .fault import Fault
comment_regexp = re.compile("--.*")
def dequote(s):
if s[0] in ["'", '"']:
if s[0] == s[-1]:
return s[1:-1]
else:
raise ValueError("Quote fuckup")
else:
r... |
from __future__ import annotations # isort:skip
import pytest ; pytest
#-----------------------------------------------------------------------------
# Imports
#-----------------------------------------------------------------------------
# Module under test
import bokeh.embed.wrappers as bew # isort:skip
#-------... |
import logging
import sys
import numpy
import rasterio
logging.basicConfig(stream=sys.stderr, level=logging.DEBUG)
def test_read_boundless_natural_extent():
with rasterio.open('tests/data/RGB.byte.tif') as src:
data = src.read(boundless=True)
assert data.shape == (3, src.height, src.width)
... |
import mock
import netaddr
from rally.plugins.openstack.context.network import networks as network_context
from tests.unit import test
NET = "rally.plugins.openstack.wrappers.network."
class NetworkTestCase(test.TestCase):
def get_context(self, **kwargs):
return {"task": {"uuid": "foo_task"},
... |
import ctypes
from os_win.utils.winapi import constants as w_const
from os_win.utils.winapi import wintypes
lib_handle = None
ISCSI_SECURITY_FLAGS = ctypes.c_uint64
ISCSI_LOGIN_FLAGS = ctypes.c_uint32
ISCSI_LOGIN_OPTIONS_INFO_SPECIFIED = ctypes.c_uint32
ISCSI_AUTH_TYPES = wintypes.UINT
ISCSI_DIGEST_TYPES = wintypes.... |
import operator
import json
from django.shortcuts import render
from django.http import HttpRequest, HttpResponseRedirect, Http404
from django.contrib.auth.models import User
from django.contrib import messages
from django.forms.models import model_to_dict
from django.db.models import Count, Avg
from LL1_Academy.mode... |
from .imports import *
from .layer_optimizer import *
from enum import IntEnum
def scale_min(im, targ):
""" Scales the image so that the smallest axis is of size targ.
Arguments:
im (array): image
targ (int): target size
"""
r,c,*_ = im.shape
ratio = targ/min(r,c)
sz = (scale_t... |
from PIL import Image
import requests
from StringIO import StringIO
from flask import session
from model import *
def RGB_to_HSV(r, g, b):
""" Converts RGB value to HSV value """
r, g, b = r/255.0, g/255.0, b/255.0
mx = max(r, g, b)
mn = min(r, g, b)
df = mx-mn
if mx == mn:
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import re
import sys
from setuptools import setup
from setuptools.command.test import test as TestCommand
# This command has been borrowed from
# https://github.com/getsentry/sentry/blob/master/setup.py
class PyTest(TestCommand):
def finalize_options(self):... |
import errno
import os
import yaml
from urllib import quote_plus as urlquote
__all__ = ['config', 'engine_uri', 'db_uri']
class ConfigError(Exception):
def __init__(self, error=None, help=None):
self.error = error or ''
self.help = help or \
'Run `sudo cp etc/config-dev.json /etc/inb... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
r"""
Program to batch create categories.
The program expects a generator of page titles to be used as
suffix for creating new categories with a different base.
The following command line parameters are supported:
-always Don't ask, just do the edit.
-overwrite ... |
#!/usr/bin/python
"""
================================================
ABElectronics ADC Pi V2 8-Channel ADC
Version 1.0 Created 09/05/2014
Version 1.1 16/11/2014 updated code and functions to PEP8 format
Requires python smbus to be installed
================================================
"""
class ADCPi:
# i... |
from transitions.extensions import GraphMachine
name = []
class TocMachine(GraphMachine):
def __init__(self, **machine_configs):
self.machine = GraphMachine(
model = self,
**machine_configs
)
def is_going_to_state1(self, update):
text = update.message.text
... |
import time
def is_prime(n):
'''check if integer n is a prime'''
# make sure n is a positive integer
n = abs(int(n))
# 0 and 1 are not primes
if n < 2:
return False
# 2 is the only even prime number
if n == 2:
return True
# all other even numbers are not primes
... |
# -*- coding: utf-8 -*-
import re
import json
import zlib
from pkg_resources import resource_string
from lxml import etree
from pybikes.base import BikeShareSystem, BikeShareStation
from pybikes.utils import PyBikesScraper, filter_bounds
from pybikes.contrib import TSTCache
_kml_ns = {
'kml': 'http://earth.goog... |
"""
argParser.py:
Parses arguments from a command line for pyUHBD.
Uses class modeClass to define how arguments should be parsed. An instance of
modeClass is created for each possible mode defined in pyUHBD.py. See modeClass
doc string for more information.
Version notes:
0.1: 060113
0.1.1: 060310
Changed hybrid d... |
# -*- coding: utf-8 -*-
"""
rnn_params = {
"fold": 5,
"lr": 0.0627,
"win": 5, # number of words in context window if use context-window
"em_dimension":100 # the dimension of word embeding
}
"""
MIN_SENTENCE_LENGTH = 3
RNN_PARAMS = {
"dh": 10,
"nc": 3,
"ne": 14326,
"de": 100,
"sw": ... |
import os
from setuptools import find_packages
from setuptools import setup
project = 'kotti_blogtool'
version = '1.0.0'
here = os.path.abspath(os.path.dirname(__file__))
README = open(os.path.join(here, 'README.rst')).read()
CHANGES = open(os.path.join(here, 'CHANGES.rst')).read()
setup(
name=project,
vers... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Project Euler solution
Problem 35: Circular primes
The number, 197, is called a circular prime because all rotations of the
digits: 197, 971, and 719, are themselves prime.
There are thirteen such primes below 100: 2, 3, 5, 7, 11, 13, 17, 31, ... |
# -*- coding: utf-8 -*-
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 'Flipbook.video_download'
db.add_column(u'flipbook_flipbook', 'video_download',
... |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
import os
from mr_database import Inquisitor as IQ
from mr_database import MrDatabase
from mr_database import DatabaseConnection
from mr_database import ConType
from mr_database import Table
from mr_database import Column
from mr_database import DataTypes
DB_PATH = 'test_dat... |
"""Python datastore class User to be used as a datastore data type.
Classes defined here:
User: object representing a user. A user could be a Google Accounts user
or a federated user.
Error: base exception type
UserNotFoundError: UserService exception
RedirectTooLongError: UserService exception
NotAl... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
import codecs
import copy
import os
from twisted.internet import defer
from mock import Mock
from testtools import TestCase, run_test_with
from testtools.twistedsupport import Asynch... |
# coding: spec
from harpoon.option_spec.harpoon_specs import Harpoon, HarpoonSpec
from harpoon.option_spec import image_objs, command_objs
from harpoon.collector import Collector
from tests.helpers import HarpoonCase
from input_algorithms import spec_base as sb
from input_algorithms.dictobj import dictobj
from delfi... |
# -*- coding: utf-8 -*-
""" Transports data from various sources and over diverse protocols fresh to your application.
For more, read the manual at http://jhermann.github.io/daqueduct/.
Copyright © 2013 Jürgen Hermann
Licensed under the Apache License, Version 2.0
"""
# Copyright © 2013 Jürgen Hermann
#
... |
# -*- coding: utf-8 -*-
from selenium import webdriver
from .session import SessionHelper
from .group import GroupHelper
from .contact import ContactHelper
class Application:
def __init__(self, browser, base_url):
if browser == "firefox":
self.wd = webdriver.Firefox()
elif browser ==... |
#!./env/bin/python
""" Windows Registry Network Query
Lists the network name and MAC addresses of the networks that
this computer has connected to. If the location command is given
print the coordinates of the network if they are in the wigile
datebase
Don't be a moron, please don't use this for ... |
import logging, re
from autotest.client.shared import error, utils
from virttest import env_process, utils_misc, utils_test
@error.context_aware
def run_enforce_quit(test, params, env):
"""
enforce quit test:
steps:
1). boot guest with enforce params
2). guest will quit if flags is not supported in... |
"""Run tests with GDB goodies enabled."""
from . import plugin
from .. import exceptions
from ..settings import settings
from ...utils import gdb
from ...utils import process
from ...utils import path as utils_path
class GDB(plugin.Plugin):
"""
Run tests with GDB goodies enabled
"""
name = 'gdb'
... |
from ._baseclass import ArtBaseClass
from collections import OrderedDict
from math import sin, cos
from opc.colormap import Colormap
from opc.colors import rgb
from opc.matrix import OPCMatrix
from .utils.diamondsquare import DiamondSquareAlgorithm
SCALE = 8
CENTERZONE = 16
class Art(ArtBaseClass):
descript... |
'''
This file is part of evopy.
Copyright 2012, Jendrik Poloczek
evopy is free software: you can redistribute it
and/or modify it under the terms of the GNU General Public License as published
by the Free Software Foundation, either version 3 of the License, or (at your
option) any later version.
evopy is distribut... |
#!/usr/bin/env python3
"""
Test to ensure that pegasus-kickstart sends SIGTERM and then SIGKILL to a job
executable when checkpoint.time and maxwalltime pegasus profiles are given.
Additionally, tests that checkpoint files are handled correctly for nonsharedfs.
"""
import logging
from pathlib import Path
from Pegas... |
from __future__ import division, print_function, absolute_import
import numpy as np
from numpy.testing import assert_equal
from scipy.sparse import diags, csc_matrix, csr_matrix, coo_matrix
from scipy.sparse.csgraph import reverse_cuthill_mckee, \
maximum_bipartite_matching, structural_rank
def test_graph_revers... |
#!/usr/bin/env python
import numpy as np
class State:
def __init__(self, init=True, board=None):
if init:
values = range(1,10)
# self.nodes = [[set(values) for x in range(0,9)] for y in range(0,9)]
self.nodes = { (x,y): set(values) for x in range (1,10) for y in range(1,1... |
from tests import *
import mock
import inyourface
import requests
import hashlib, pickle, mock, os, json, pprint, re, pkgutil, inspect
from inyourface.effect import *
from inyourface import Animator
from google.cloud import vision
from google.cloud.vision import types
from google.protobuf import message as _message
fro... |
import os
import sys
import radical.pilot as rp
# READ: The RADICAL-Pilot documentation:
# http://radicalpilot.readthedocs.org/en/latest
#
# Try running this example with RADICAL_PILOT_VERBOSE=debug set if
# you want to see what happens behind the scenes!
#--------------------------------------------------------... |
"""
Utils for SPDK driver.
"""
import glob
import os
import re
from oslo_config import cfg
from oslo_log import log as logging
from cyborg.accelerator import configuration
from cyborg.accelerator.common import exception
from cyborg.accelerator.drivers.spdk.util.pyspdk.py_spdk import PySPDK
from cyborg.common.i18n im... |
#!/usr/bin/env python2.7
# -*- coding: UTF-8 -*-
"""
Author: Michael Rong
<<EMAIL>>
www.electronic.works
Creation Date: 2016-03-09
Copyright: (c) 2016 Linux statt Windows
https://linux-statt-windows.org
"""
# * * * * * * * * * *... |
# coding=utf-8
class Solution(object):
def search(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
lo, hi = 0, len(nums) - 1
while lo <= hi:
mid = (lo + hi) / 2
if target == nums[mid]:
ret... |
import gssapi
import sys
import six
from ipalib import api
from ipalib import errors
from ipaplatform.paths import paths
from ipapython import admintool
from ipapython.dn import DN
from ipapython.ipautil import realm_to_suffix, posixify
from ipaserver.install import replication, installutils
if six.PY3:
unicode ... |
from fabric.operations import prompt
from loader import get_wrapper
from pios import run_local
import difflib, color
def print_diff(str1, str2):
diff = difflib.ndiff(str1.splitlines(1),
str2.splitlines(1))
for line in list(diff):
if line.startswith('+'):
with color.green():
... |
import hypothesis.strategies as st
import numpy as np
import pytest
from astropy import time, units as u
from astropy.coordinates import CartesianRepresentation
from astropy.tests.helper import assert_quantity_allclose
from hypothesis import given, settings
from numpy.testing import assert_allclose
from pytest import a... |
# Headers
from threading import Thread
import urllib
import json
import redis
from os import path
from PIL import Image
import numpy as np
import matplotlib.pyplot as plt
import re
import pandas as pd
from wordcloud import WordCloud, STOPWORDS, ImageColorGenerator
from TwitterAPI import TwitterAPI, TwitterRestPager, T... |
#! /usr/bin/env python
# encoding: utf-8
"""
Windows-specific optimizations
This module can help reducing the overhead of listing files on windows (more than 10000 files).
"""
import os
try: import cPickle
except: import pickle as cPickle
from waflib import Utils, Build, Context, Node, Logs
try:
TP = '%s\\*'.decod... |
import numpy as np
# ネットワーク構造の定義
# [filter size, stride, padding]で層を表し、listに格納
convnet =[[3,1,1], [3,1,1], [2,2,0],
[3,1,1], [3,1,1], [2,2,0],
[3,1,1], [3,1,1], [3,1,1], [2,2,0],
[3,1,1], [3,1,1], [3,1,1], [2,2,0],
[3,1,1], [3,1,1], [3,1,1], [2,2,0],
[7,1,3], [1,1,0],]... |
from django.contrib import admin
from webdnd.player.models.campaigns import (
Campaign,
CampaignPreference,
Player,
)
from webdnd.player.admin.user import PreferenceInline, PreferenceAdmin
from webdnd.shared.admin import fk_link
class CampaignAdmin(admin.ModelAdmin):
model = Campaign
fields = ('o... |
"""I totally stole most of this from melange, thx guys!!!"""
import collections
import datetime
import inspect
import os
import shutil
import time
import types
import uuid
from eventlet.timeout import Timeout
import jinja2
from oslo_concurrency import processutils
from oslo_log import log as logging
from oslo_service... |
"""
HTML rendering for twisted.web.
@var VALID_HTML_TAG_NAMES: A list of recognized HTML tag names, used by the
L{tag} object.
@var TEMPLATE_NAMESPACE: The XML namespace used to identify attributes and
elements used by the templating system, which should be removed from the
final output document.
@var ta... |
"""Simple Request handler using Jinja2 templates."""
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
import logging
import os
import jinja2
import webapp2
from google.appengine.api import users
from dashboard.common import utils
from dashboard.common impo... |
import boto
import datetime
import uuid
import json
import sys
class S3DataIngestSource:
"""Ingest data from S3"""
def __init__(self, config):
self.config = config
def __iter__(self):
aws_access_key_id = self.config['aws_access_key_id']
aws_secret_access_key = self.config['aws_secret_access_key']
... |
from django import forms
from django.conf import settings
from django.contrib.admin import widgets
from mongoforms import MongoForm
FORM_WIDGETS = {
'fields': {
forms.DateTimeField: widgets.AdminSplitDateTime,
forms.DateField: widgets.AdminDateWidget,
forms.TimeField: widgets.AdminTimeWidge... |
import os
import gio
import sys
import bisect
import types
import shlex
import glib
import re
import os
import module
import method
import result
import exceptions
from accel_group import AccelGroup
from accel_group import Accelerator
__all__ = ['is_commander_module', 'Commands', 'Accelerator']
def attrs(**kwargs):... |
#!/usr/bin/env python2.5
# -*- coding: utf-8 -*-
__author__ = "Soeren Apel (<EMAIL>), F. Gau (<EMAIL>), Thomas Gstaedner (thomas (a) gstaedtner (.) net)"
__version__ = "prototype"
__copyright__ = "Copyright (c) 2008"
__license__ = "GPL3"
from epydial import *
STYLE = """
DEFAULT='font=Sans font_size=18 align=left col... |
# -*- coding: utf-8 -*-
import os
import sys
import webbrowser
from invoke import task, run
docs_dir = 'docs'
build_dir = os.path.join(docs_dir, '_build')
@task
def test(coverage=False, browse=False):
flake()
import pytest
args = []
if coverage:
args.extend(['--cov=webargs', '--cov-report=ter... |
import math
import pdb
import torch
import torch.nn.functional as F
from torch.nn.parameter import Parameter
def log_sum_exp(x, axis=1):
m = torch.max(x, dim=1)[0]
return m + torch.log(torch.sum(torch.exp(x - m.unsqueeze(1)), dim=axis))
def reset_normal_param(L, stdv, weight_scale=1.0):
assert type(L) =... |
# -*- coding: utf-8 -*-
import sqlite3
import logging
from .settings import DATABASE_PATH
class PinboardDatabase(object):
def __init__(self):
self.conn = sqlite3.connect(DATABASE_PATH)
self.c = self.conn.cursor()
try:
self.c.execute("SELECT * FROM pinboard")
except s... |
"""
Bootcmd
-------
**Summary:** run commands early in boot process
This module runs arbitrary commands very early in the boot process,
only slightly after a boothook would run. This is very similar to a
boothook, but more user friendly. The environment variable ``INSTANCE_ID``
will be set to the current instance id f... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import cStringIO
import urllib
import web
import qrcode
try:
from PIL import Image
except ImportError:
import Image
from lib.mime import ImageMIME
from lib import charset
web.config.debug = True
urls = (
'/', 'Index', # 首页
'/qr', 'QR', # 二维码图片
'/.*',... |
#!/usr/bin/python -tt
# -*- coding: utf-8 -*-
from pytraits import extendable
# Let's start by creating a simple class with some values. It contains
# class variables and instance variables. Composed methods will have
# access to all these variables.
@extendable
class ExampleClass(object):
PUBLIC = 24
_HIDDEN... |
"""
This file is part of XDEMO
Copyright(c) <Florian Lier>
https://github.com/warp1337/xdemo
This file may be licensed under the terms of the
GNU Lesser General Public License Version 3 (the ``LGPL''),
or (at your option) any later version.
Software distributed under the License is distributed
on an ``AS IS'' basis... |
#!/usr/bin/python
import random
import colorsys
import yaml
import bisect
#############################################################################
BCOUNT = 3
random.seed(1)
unique_id = 0
global_time = 0
traffic = []
branches = []
branches_by_ident = {}
markers = []
###########################################... |
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
"""
This test ensures that the design matrices of the FIAC dataset match
with fMRIstat's, at least on one block and one event trial.
Taylor, J.E. & Worsley, K.J. (2005). \'Inference for
magnitudes and... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from __future__ import absolute_import
from django.views.generic import CreateView, UpdateView, ListView, DeleteView
from django.http import HttpResponse
from django.core.urlresolvers import reverse, reverse_lazy
from django.shortcuts import redirect, get... |
from typing import Any
class Response:
"""
Abstract class for response object. Defines shared methods
for both Success and Failure response.
"""
def __bool__(self) -> bool:
"""
This method is used for checking if the response is failure or success.
Needs to be implemented ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
import logging
from sqlalchemy import Column, Integer, String, Boolean, Float, ForeignKey, DateTime, Text, BigInteger, Index, desc
from sqlalchemy.orm import relationship, load_only
import datetime
import localization
from database import Base
db_encoding = 'u... |
# Wolfram Alpha (Science)
#
# @website https://www.wolframalpha.com
# @provide-api yes (https://api.wolframalpha.com/v2/)
#
# @using-api yes
# @results XML
# @stable yes
# @parse url, infobox
from urllib import urlencode
from lxml import etree
# search-url
search_url = 'https://api.wolframalpha.c... |
#!/usr/bin/env python
'''
This module has the following method:
count_GOterms_with_EXP:
This method takes four input arguments:
(1) a uniprot-swissProt file handle,
(2) a taxonomy id,
(3) the set of EXP codes.
This method counts the number of pro... |
from data import Point, Color, View, Light
def get_eye_point(argv):
if '-eye' in argv:
flag_index = argv.index('-eye')
try:
x = float(argv[flag_index + 1])
except:
print "eye_point x value incorrectly defined... using default"
x = 0
try:
y = float(argv[flag_index + 2])
except:
print "eye_poin... |
# coding:UTF-8
from common.models import SelectCourse,Course,Score
from users.models import StudentProfile,SmallClass
from const.models import SchoolYear
from django.contrib.auth.models import User
student_list = {}
try:
rfile = open("../jd5.txt")
for line in rfile:
s=line.strip().split()
# st... |
from twisted.application import service
from twisted.internet import defer
from twisted.internet import task
from twisted.python import log
from buildbot import util
class ClusteredService(service.Service, util.ComparableMixin):
compare_attrs = ('name',)
POLL_INTERVAL_SEC = 5 * 60 # 5 minutes
service... |
import pytest
from icomoon.utils import IcomoonSettingsError, extend_webfont_settings
def test_extend_settings_success():
"""
Correct settings, nothing to do
"""
webfont_settings = {
'fontdir_path': 'static/fonts',
'csspart_path': 'static/css/icomoon_icons.scss',
}
result = ex... |
"""Tests for config services."""
from core.domain import config_domain
from core.domain import config_services
from core.tests import test_utils
class ConfigServicesTests(test_utils.GenericTestBase):
"""Tests for config services."""
def test_can_set_config_property(self):
self.assertFalse(config_dom... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.