code stringlengths 1 199k |
|---|
trip_date = object.trip_id.trip_start or False
rs = True
def invalid(emailaddress):
if len(emailaddress) < 7:
return True # Address too short.
try:
localpart, domainname = emailaddress.rsplit('@', 1)
host, toplevel = domainname.rsplit('.', 1)
except ValueError:
return True # ... |
from __future__ import unicode_literals
from datetime import datetime
from itertools import chain
from blinker import Signal
from flask import url_for
from mongoengine.signals import pre_save, post_save
from werkzeug import cached_property
from udata.core.storages import avatars, default_image_basename
from udata.front... |
from odoo.tests.common import SavepointCase
class TestCommon(SavepointCase):
@classmethod
def setUpClass(cls):
super().setUpClass()
def _create_stock_move(self, location_dest_id, qty):
move = self.env["stock.move"].create(
{
"name": "Stock move in",
... |
__author__ = "Nick Wong"
class Dict(dict):
def __init__(self, **kw):
super().__init__(**kw)
def __getattr__(self,key):
try:
return self[key]
except KeyError:
raise AttributeError(r"'Dict' object has no attribute '%s'." % key)
def __setattr__(self,key,value):
... |
"""
Module :mod:`openquake.hazardlib.correlation` defines correlation models for
spatially-distributed ground-shaking intensities.
"""
import abc
import numpy
class BaseCorrelationModel(metaclass=abc.ABCMeta):
"""
Base class for correlation models for spatially-distributed ground-shaking
intensities.
""... |
class Handler(object):
def __init__(self, client):
self.client = client
self.commands = client.commands
self.priority = 3
self.db = client.db
self.modules = client.modules |
from lettuce import world, step
from terrain.steps import reload_the_page
from selenium.webdriver.common.keys import Keys
from common import type_in_codemirror, upload_file
from django.conf import settings
from nose.tools import assert_true, assert_false, assert_equal # pylint: disable=E0611
TEST_ROOT = settings.COMMO... |
from django.contrib import admin
from instruments.models import Instrument
class InstrumentAdmin(admin.ModelAdmin):
list_display = ('number', 'name')
ordering = ('number',)
admin.site.register(Instrument, InstrumentAdmin) |
"""Composition."""
import random
import os
import math
import music21
import mido
ranges = open("ranges.json")
ranges = eval(ranges.read())
class Voice(music21.stream.Voice):
"""Create a Music21 Voice of random notes from a selected scale."""
def __init__(self,
name="",
scale=m... |
"""Add a new column client_id in the tables channel, cause and tag
Revision ID: 49de30166071
Revises: 3775ac5a659f
Create Date: 2014-11-26 14:05:59.823204
"""
revision = '49de30166071'
down_revision = '3775ac5a659f'
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import postgresql
def upgrade():... |
from pathlib import Path
from typing import Optional, List
import aiohttp_jinja2
import aiopg.sa
from aiohttp import web
import jinja2
from poster.routes import init_routes
from poster.utils.common import init_config
path = Path(__file__).parent
def init_jinja2(app: web.Application) -> None:
'''
Initialize jinj... |
class Color(object):
def __init__ (self,red, green, blue, alpha=1.0):
self.red = red
self.green = green
self.blue = blue
self.alpha = alpha
__colors = {
"black": Color(0,0,0),
"blue": Color(0,0,1),
"red": Color(1,0,0),
"green": Color(0,1,0),
"yellow": Color(1,1,0)... |
import re
from django.utils.html import strip_spaces_between_tags
from django.conf import settings
RE_MULTISPACE = re.compile(r'\s{2,}')
RE_NEWLINE = re.compile(r'\n')
class MinifyHTMLMiddleware(object):
def process_response(self, request, response):
if 'text/html' in response['Content-Type'] and settings.C... |
import sys
from paravistest import datadir, pictureext, get_picture_dir
from presentations import CreatePrsForFile, PrsTypeEnum
import pvserver as paravis
myParavis = paravis.myParavis
picturedir = get_picture_dir("IsoSurfaces/F2")
file = datadir + "T_COUPLEX1.med"
print " --------------------------------- "
print "fil... |
'''
class Aniaml:
count = 10
def __init__(self,name):
self.name = name
self.num = None
hobbie = 'meat'
@classmethod #类方法,不能访问实例变量
def talk(self):
print('%s is talking ...'%self.hobbie )
@staticmethod #静态方法,不能访问类变量及实例变量
def walk():
print('is walking ...')
... |
from ConfigParser import ConfigParser
class Properties(object):
#default values
VERIFY_MESSAGE = True
VERIFY_TIMESTAMP = True
VERIFY_CERTIFICATE = True
CHECK_CRL = True
FORCE_CRL_DOWNLOAD = False
# these properties are expected boolean
_boolean_values = [
"VERIFY_MESSAGE", "VERIFY_... |
"""Module that handles keys stored in PSKC files."""
import array
import binascii
from pskc.policy import Policy
class EncryptedValue(object):
"""A container for an encrypted value."""
def __init__(self, cipher_value, mac_value, algorithm):
self.cipher_value = cipher_value
self.mac_value = mac_v... |
import fedmsg.tests.test_meta
from .common import add_doc
class TestPubPushStop(fedmsg.tests.test_meta.Base):
""" "Pub" is the system used to push Red Hat releases for distribution.
Pub will publish a message to the message bus when pushes start and stop.
This is an example of a stop message announced when ... |
from django.core.management.base import BaseCommand, CommandError
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from optparse import make_option
from imp import find_module, load_module
from yadsel.execution import AVAILABLE_ACTIONS, AVAILABLE_MODES, do
from yadsel import core... |
from spack import *
class RAdsplit(RPackage):
"""This package implements clustering of microarray gene expression
profiles according to functional annotations. For each term genes
are annotated to, splits into two subclasses are computed and a
significance of the supporting gene set is determined."""
... |
import FreeCAD,Draft,ArchComponent,DraftVecUtils
from FreeCAD import Vector
if FreeCAD.GuiUp:
import FreeCADGui
from PySide import QtGui,QtCore
from DraftTools import translate
else:
def translate(ctxt,txt):
return txt
__title__="FreeCAD Arch Commands"
__author__ = "Yorik van Havre"
__url__ = "h... |
from spack import *
class RDygraphs(RPackage):
"""An R interface to the 'dygraphs' JavaScript charting library (a copy of
which is included in the package). Provides rich facilities for charting
time-series data in R, including highly configurable series- and
axis-display and interactive features like z... |
import os
import sys
try:
import termios
except ImportError:
pass # windows
from urwid.util import int_scale
from urwid import signals
from urwid.compat import B, bytes3
UNPRINTABLE_TRANS_TABLE = B("?") * 32 + bytes3(range(32,256))
UPDATE_PALETTE_ENTRY = "update palette entry"
INPUT_DESCRIPTORS_CHANGED = "input... |
import sys
from libavg import avg, app, player, widget
class VideoPlayer(app.MainDiv):
CONTROL_WIDTH=240
def onArgvParserCreated(self, parser):
parser.set_usage("%prog [options] <filename>")
parser.add_option("-d", "--disable-accel", dest="disableAccel",
action="store_true", defa... |
import os
from functools import lru_cache
import hashlib
import inspect
from cerbero.build.filesprovider import FilesProvider
from cerbero.enums import License, Platform, Distro
from cerbero.packages import PackageType
from cerbero.utils import remove_list_duplicates, get_class_checksum, messages as m
class PackageBase... |
"""Displays a GUI for Orca navigation list dialogs"""
__id__ = "$Id$"
__version__ = "$Revision$"
__date__ = "$Date$"
__copyright__ = "Copyright (c) 2012 Igalia, S.L."
__license__ = "LGPL"
from gi.repository import GObject, Gdk, Gtk
from . import debug
from . import guilabels
from . import orca_state
cla... |
from ROOT import TH1F, TF1
from ROOT import gROOT
from array import array
x = ( 1.913521, 1.953769, 2.347435, 2.883654, 3.493567,
4.047560, 4.337210, 4.364347, 4.563004, 5.054247,
5.194183, 5.380521, 5.303213, 5.384578, 5.563983,
5.728500, 5.685752, 5.080029, 4.251809, 3.372246,
2.207432, 1.2275... |
"""
class to check hash for all files for file integrity
"""
import simplejson
import redis
import hashlib
import os
import yaml
from local_variables import root_folder
f= redis.StrictRedis(host='localhost', port=6379, db=7)
c_files=["auth.py","base_config.py"]
c_dir=["etc"]
def versione():
conf_read = open(root_fo... |
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('retail', '0002_auto_20170521_2317'),
]
operations = [
migrations.AlterModelOptions(
name='employee',
options={'ordering': ['-number']},
... |
"""
Contains the functions required to model a material in Blender.
"""
import bpy
import phobos.defs as defs
from phobos.utils.validation import validate
from phobos.phoboslog import log
@validate('material')
def createMaterial(material, logging=False, adjust=False, errors=[]):
"""
Args:
material:
... |
"""
sphinx-autopackage-script
This script parses a directory tree looking for python modules and packages and
creates ReST files appropriately to create code documentation with Sphinx.
It also creates a modules index (named modules.<suffix>).
"""
import os
import optparse
OPTIONS = ['members',
#'undoc-member... |
from django.apps import AppConfig
class GeogameConfig(AppConfig):
name = 'geogame' |
import re
from distutils.core import setup
VERSION_FILE = "nest/_version.py"
verstrline = open(VERSION_FILE, "rt").read()
VSRE = r'^__version__ = [\'"]([^\'"]*)[\'"]'
mo = re.search(VSRE, verstrline, re.M)
if mo:
VERSION = mo.group(1)
else:
raise RuntimeError("Unable to find version string in {0}".format(VERSI... |
print "Processing fifth case"
lineSpec = isLineSpec(slicedCubes)
shortRange = isShortRange(obs)
ffUpsample = getUpsample(obs)
waveGrid = wavelengthGrid(slicedCubes, oversample=2,
upsample=ffUpsample, calTree=calTree)
slicedCubes = activateMasks(slicedCubes,
String1d... |
import sys, os, datetime
sys.path.insert(0, os.path.abspath('..'))
sys.path.insert(0, os.path.abspath('../jedi'))
sys.path.append(os.path.abspath('_themes'))
extensions = ['sphinx.ext.autodoc', 'sphinx.ext.viewcode', 'sphinx.ext.todo']
templates_path = ['_templates']
source_suffix = '.rst'
source_encoding = 'utf-8'
mas... |
"""
Test suite for Dutch language Integer and Digits classes
============================================================================
"""
from dragonfly.test.infrastructure import RecognitionFailure
from dragonfly.test.element_testcase import ElementTestCase
from dragonfly.language.base.integer import In... |
class UIConsts():
RID_COMMON = 500
RID_DB_COMMON = 1000
RID_FORM = 2200
RID_QUERY = 2300
RID_REPORT = 2400
RID_TABLE = 2600
RID_IMG_REPORT = 1000
RID_IMG_FORM = 1100
RID_IMG_WEB = 1200
INVISIBLESTEP = 99
INFOIMAGEURL = "private:resource/dbu/image/19205"
'''
The tabind... |
from PySide2.QtCore import *
from PySide2.QtGui import *
from PySide2.QtWidgets import *
from api_rest.Gui.Main.MainWindow import *
import json
import requests
import os.path
import pandas as pd
import sys
from matplotlib import pyplot as plt
import os
os.environ['no_proxy'] = '127.0.0.1,localhost'
__author__ = 'Santia... |
import os
from distutils.core import setup, Extension
sources = [
'src/python/core.c',
'src/libethash/io.c',
'src/libethash/internal.c',
'src/libethash/sha3.c']
if os.name == 'nt':
sources += [
'src/libethash/util_win32.c',
'src/libethash/io_win32.c',
'src/libethash/mmap_win3... |
import hashlib
import time
from collections import defaultdict
class Value(object):
"""
Class for storing DHT values.
"""
def __init__(self, id_, data, max_age, version):
self.id = id_
self.data = data
self.last_update = time.time()
self.max_age = max_age
self.ver... |
"""
CairoSVG non-regression tests.
This test suite compares the CairoSVG output with a reference version
output.
"""
import os
import tempfile
import pytest
from . import FILES, cairosvg, reference_cairosvg
@pytest.mark.parametrize('svg_filename', FILES)
def test_image(svg_filename):
"""Check that the pixels match ... |
from pycp2k.inputsection import InputSection
from ._each355 import _each355
from ._cubes7 import _cubes7
class _molecular_states4(InputSection):
def __init__(self):
InputSection.__init__(self)
self.Section_parameters = None
self.Add_last = None
self.Common_iteration_levels = None
... |
"""
Copyright (C) 2015 Franklin "Snaipe" Mathieu <https://snai.pe>
This file is part of 'git gud'.
'git gud' 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... |
"""
Bootstraps package management in an existing Python 2 or 3 installation.
After running this script, install packages using 'arnie':
arnie install PackageName
Or force installation into the site packages of specific Python version:
arnie2 install PackageName
arnie3 install PackageName
"""
import os
impor... |
"""Bolidozor Log Server.
.. moduleauthor:: Jan Milík <milikjan@fit.cvut.cz>
"""
__version__ = "0.1"
def main():
print __doc__
if __name__ == "__main__":
main() |
"""
"""
from types import *
def setPdsmember(self,member,attribute,value):
_vcs.setPdsmember(self.parent, member, attribute, value, self.template_parent.mode)
def getPdsmember(self,member,attribute):
return _vcs.getPdsmember(self,member,attribute)
class Pds:
"""
Class: Pds # Template text
Description... |
""" Configuration reader module """
import multiprocessing
import os
import kaptan
from six import with_metaclass
from voiceplay.utils.helpers import Singleton
class Config(with_metaclass(Singleton)):
"""
VoicePlay configuration object
"""
# Simple POST request
bugtracker_url = 'http://7d93bbb8914ae... |
import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
SECRET_KEY = 'dk)s2e105ct2t7@vh%awj(qk=@%!54^mp4d(is-=9yc+u&+r)n'
DEBUG = True
TEMPLATE_DEBUG = True
ALLOWED_HOSTS = []
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.session... |
from flask import Flask, request, session, url_for, redirect, \
render_template, abort, g, flash, _app_ctx_stack, make_response, \
redirect
from time import time
import redis as _redis
import hashlib
import sys
app = Flask(__name__)
app.debug = True
def get_rand():
data = None
with open("/dev/random",... |
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 = [
... |
from distutils.core import setup
setup(
name='django-diggpaginator',
version='1.0.0',
description="Support for Digg-style paginator.",
long_description=open('README.md').read(),
author='Arapov Denis',
author_email='d.arapov@undev.ru',
license='BSD',
url='http://github.com/jordanm/django-... |
import random, sys
from splunklib.modularinput import *
class MyScript(Script):
"""All modular inputs should inherit from the abstract base class Script
from splunklib.modularinput.script.
They must override the get_scheme and stream_events functions, and,
if the scheme returned by get_scheme has Scheme... |
"""
文件名:hachina.py.
文件位置:HomeAssistant配置目录/custom_components/sensor/hachina.py
演示程序,一个平台实现多个传感器.
"""
import json
from urllib import request, parse
import logging
from datetime import timedelta
import voluptuous as vol
from homeassistant.components.sensor import PLATFORM_SCHEMA
from homeassistant.const import (
ATTR... |
from __future__ import (nested_scopes, generators, division, absolute_import, with_statement,
print_function, unicode_literals)
import copy
import sys
from pants.base.build_environment import pants_release
from pants.goal.goal import Goal
from pants.option.arg_splitter import ArgSplitter, GLOBAL... |
"""
Admin views for managing volumes and snapshots.
"""
from django.conf import settings
from django.urls import reverse
from django.urls import reverse_lazy
from django.utils.translation import ugettext_lazy as _
from horizon import exceptions
from horizon import forms
from horizon import tables
from horizon.utils imp... |
from model.group import Group
import random
import string
import os.path
import jsonpickle
import getopt
import sys
try:
opts, args = getopt.getopt(sys.argv[1:], "n:f:", ["number of groups", "file"])
except getopt.GetoptError as err:
getopt.usage()
sys.exit(2)
n = 5
f = "data/groups.json"
for o, a in opts:
... |
from tempest import exceptions
class Manager(object):
"""
Base manager class
Manager objects are responsible for providing a configuration object
and a client object for a test case to use in performing actions.
"""
def __init__(self):
self.client_attr_names = []
# we do this everywh... |
import struct
import time
import os_ken.lib.packet
from os_ken.lib.packet import dhcp
from oslo_log import log
from dragonflow.controller.common import constants
from dragonflow.tests.common import app_testing_objects
from dragonflow.tests.common import constants as const
from dragonflow.tests.common import utils as te... |
from pyscf import dft, gto
from pyscf.eph import eph_fd, uks
import numpy as np
import unittest
mol = gto.M()
mol.atom = '''O 0.000000000000 0.000000002577 0.868557119905
H 0.000000000000 -1.456050381698 2.152719488376
H 0.000000000000 1.456050379121 2.152719486067'''
mol.unit = 'Bohr'
mol.b... |
import imp, json, os, shutil, sys, tempfile, zipfile
import imp
try:
imp.find_module('texttable')
from texttable import Texttable
except ImportError:
sys.stderr.write("Could not import Texttable\nRetry after 'pip install texttable'\n")
exit()
tmpdir = tempfile.mkdtemp()
def extract_zip(filename):
file_dir = ... |
import inspect
import numpy as np
import numpy.random as rn
from .data_assimilation_class import DataAssimilationClass
class DA_smoother(DataAssimilationClass):
# This implements a data assimilation scheme in previous data are
# used together with the most recent data point to adjust the
# ensemble and para... |
import sys
from itertools import *
from functools import *
from operator import *
from collections import defaultdict
import re, copy
from cStringIO import StringIO
from datetime import datetime
import amara
from amara.namespaces import *
from amara.bindery import html
from amara.lib import inputsource
from amara.binde... |
"""The unit testing module for policy_util."""
import functools
import unittest
from src.training import policy_util
import tensorflow as tf
from tf_agents.bandits.agents import lin_ucb_agent
from tf_agents.bandits.environments import environment_utilities
from tf_agents.bandits.environments import movielens_py_environ... |
import mock
from oslo_config import cfg
import six
from senlin.common import consts
from senlin.common import exception
from senlin.engine import cluster as cm
from senlin.engine import cluster_policy as cpm
from senlin.engine import health_manager
from senlin.engine import node as node_mod
from senlin.objects import c... |
import mox
import paramiko
from heat.common import exception
from heat.common import template_format
from heat.db import api as db_api
from heat.engine import clients
from heat.engine import environment
from heat.engine import parser
from heat.engine import resource
from heat.engine.resources import image
from heat.eng... |
import json
import logging
import re
from api.api_samples.python_client.api_client import CloudBoltAPIClient
from api.api_samples.python_client.samples.api_helpers import wait_for_order_completion
from common.methods import set_progress
from servicecatalog.models import ServiceBlueprint
from utilities.exceptions import... |
from typing import Optional
from airflow.providers.microsoft.azure.hooks.wasb import WasbHook
from airflow.sensors.base_sensor_operator import BaseSensorOperator
from airflow.utils.decorators import apply_defaults
class WasbBlobSensor(BaseSensorOperator):
"""
Waits for a blob to arrive on Azure Blob Storage.
... |
import pytest
class Test_message_length:
@pytest.fixture
def target(self):
from suddendeath import message_length
return message_length
@pytest.mark.parametrize("test_input, expected", [
("突然の死", 8),
("한글", 4),
("english", 7),
("git入門", 7),
("mixed두개",... |
""" This file holds the trashview functions that is not currently being used."""
def trashview(request, account):
storage_url = request.session.get('storage_url', '')
auth_token = request.session.get('auth_token', '')
#Users are only allowed to view the trash of their own account.
if storage_url == '' o... |
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('editor', '0041_auto_20191030_1330'),
]
operations = [
migrations.CreateModel(
name='Tip',
fields=[
('id', models.AutoFie... |
import json
import unittest
from titus.reader import yamlToAst
from titus.genpy import PFAEngine
from titus.errors import *
def unsigned(x):
if x < 0:
return chr(x + 256)
else:
return chr(x)
def signed(x):
if ord(x) >= 128:
return ord(x) - 256
else:
return ord(x)
class Te... |
"""
.. module: security_monkey.tests.scheduling.test_celery_scheduler
:platform: Unix
.. version:: $$VERSION$$
.. moduleauthor:: Mike Grima <mgrima@netflix.com>
"""
import json
import boto3
import mock
from mock import patch
from moto import mock_iam, mock_sts
from pytest import raises
from security_monkey import ... |
"""UnitTest class for nsxv.py"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import unittest
from xml.etree import ElementTree as ET
from lib import naming
from lib import nsxv
from lib import policy
import nsxv_moc... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import pathlib
import sys
sys.path.append(str(pathlib.Path(__file__).parent.parent))
import tensorflow as tf
from dreamer import models
from dreamer.tools import overshooting
class _MockCell(models.Base):
def ... |
"""Module to provider installing progress calculation for the adapter.
.. moduleauthor:: Xiaodong Wang <xiaodongwang@huawei.com>
"""
import logging
import re
from compass.db.api import database
from compass.db import models
from compass.log_analyzor.line_matcher import Progress
class AdapterItemMatcher(object):
... |
import concurrent.futures
import logging
import sys
import threading
import uuid
from py4j.java_gateway import CallbackServerParameters
from pyspark import SparkContext
import mlflow
from mlflow.exceptions import MlflowException
from mlflow.tracking.client import MlflowClient
from mlflow.tracking.context.abstract_conte... |
"""Support for Template alarm control panels."""
from enum import Enum
import logging
import voluptuous as vol
from homeassistant.components.alarm_control_panel import (
ENTITY_ID_FORMAT,
FORMAT_NUMBER,
FORMAT_TEXT,
PLATFORM_SCHEMA as PARENT_PLATFORM_SCHEMA,
AlarmControlPanelEntity,
)
from homeassis... |
from django.db import models
from django.contrib.auth.models import User
notify = False
class Server (models.Model):
idServerDetails = models.AutoField(primary_key=True)
user = models.ForeignKey(User)
serverAddress = models.URLField()
serverUsername = models.CharField(max_length=128)
serverPassword ... |
from django.db import models
from django.contrib import admin
from django.utils.translation import ugettext_lazy as _
from django.utils import timezone
class FutsalTeamEnrollmentAdmin(admin.ModelAdmin):
list_display = ('person', 'futsal_team', 'state_enrollment', 'is_admin')
fieldsets = ((None, {'fields': ('per... |
import sys
import socket
import time
if sys.argv[1] != "0":
server = sys.argv[1]
else :
server = raw_input("server: ")
if sys.argv[2] != "0":
port = sys.argv[2]
else:
port = raw_input("port: ")
chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!_,.@$#"
s = socket.socket()
s.connect(... |
"""Enables Docker software containers via the {u,}docker or podman runtimes."""
import csv
import datetime
import math
import os
import re
import shutil
import subprocess # nosec
import sys
import threading
from io import StringIO # pylint: disable=redefined-builtin
from typing import Callable, Dict, List, MutableMap... |
from __future__ import absolute_import
from __future__ import print_function
from typing import List, Set, Tuple
import os
import re
GENERIC_KEYWORDS = [
'active',
'alert',
'danger',
'condensed',
'disabled',
'error',
'expanded',
'hide',
'show',
'notdisplayed',
'popover',
... |
"""
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this ... |
"""
Initially downlaoded from
http://oauth.googlecode.com/svn/code/python/oauth/
Hacked a bit by Ben Adida (ben@adida.net) so that:
- access tokens are looked up with an extra param of consumer
"""
import urllib
import time
import random
import urlparse
import hmac
import base64
import logging
import hashlib
VERSION = ... |
"""The met_eireann component."""
from datetime import timedelta
import logging
import meteireann
from homeassistant.const import CONF_ELEVATION, CONF_LATITUDE, CONF_LONGITUDE, Platform
from homeassistant.helpers.aiohttp_client import async_get_clientsession
from homeassistant.helpers.update_coordinator import DataUpdat... |
import math
from .Cesar import Cesar
class AnalisisFrecuencia(object):
"""docstring for AnalisisFrecuencia"""
def __init__(self, mensaje):
super(AnalisisFrecuencia, self).__init__()
self.frecuenciaIngles = {
'A': 0.08167, 'B': 0.01492, 'C': 0.02782, 'D': 0.04253, 'E': 0.130001, 'F': 0.02228, 'G': 0.02015,
'... |
"""
Reads a file of SMILES and enumerates undefined chiral centres, tautomers and charge states.
Writes results as SMILES.
"""
import sys, argparse, traceback
from pipelines_utils import utils
from rdkit import Chem
from rdkit.Chem.rdForceFieldHelpers import UFFGetMoleculeForceField
from molvs.tautomer import TautomerE... |
"""Copyright 2014 Cyrus Dasadia
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
distribu... |
"""
Tools to automate loading of test fixtures
"""
import json
from datetime import datetime, time, date
from google.appengine.ext import ndb
from google.appengine.ext.ndb.model import (DateTimeProperty, DateProperty,
TimeProperty, StructuredProperty,
... |
from mmsServer import db
from sqlalchemy.dialects import mysql
class Member( db.Model):
__tablename__ = 'members'
# Columns
id = db.Column( db.Integer, primary_key = True)
membership_id = db.Column( db.Integer) # This is a manually managed foreign key into "Membership"
first_name = db.Column( db.Tex... |
from setuptools import setup
setup(
name='PyDrive',
version='1.0.0',
author='JunYoung Gwak',
author_email='jgwak@dreamylab.com',
packages=['pydrive', 'pydrive.test'],
url='http://pypi.python.org/pypi/PyDrive/',
license='LICENSE',
description='Google Drive API made easy.',
long_descri... |
"""Write a program that will calculate the average word length of a text
stored in a file (i.e the sum of all the lengths of the word tokens in the
text, divided by the number of word tokens)."""
def average_word_length(file_name):
pass
average_word_length('hapax.txt') |
import re
import os
import unittest
import mox
from nose.plugins.attrib import attr
from oslo.config import cfg
from heat.common import exception
from heat.common import context
from heat.common import template_format
from heat.engine import parser
from heat.engine.resources import instance
from heat.engine.resources i... |
"""A demo of the Google Assistant GRPC recognizer."""
import logging
import os
import aiy.assistant.grpc
import aiy.audio
import aiy.voicehat
logging.basicConfig(
level=logging.INFO,
format="[%(asctime)s] %(levelname)s:%(name)s:%(message)s"
)
def main():
status_ui = aiy.voicehat.get_status_ui()
status_u... |
taskTable = {
"id" : "id",
"title" : "title",
"description" : "description",
"creator" : "creator_id",
# "is_assignee_group" : "is_assignee_group",
"dueDate" : "due_date",
"seen" : "seen",
"isSubmitted" : "is_submitted",
"isCompleted" : "is_completed",
"submissionDate" : "submission_date",
"completionDate" :... |
from django.contrib import admin
from . import models
class BlogArticlesAdmin(admin.ModelAdmin):
list_display = ("title", "author", "publish")
list_filter = ("publish", "author")
search_fields = ("title", "body")
raw_id_fields = ("author",)
date_hierarchy = "publish"
ordering = ['publish', 'auth... |
from flask import render_template, flash, redirect
from . import app, db, models
from forms import LoginForm, PostForm, ClearForm
from qdata import QueryData
import os
@app.route('/login', methods = ['GET', 'POST'])
def login():
form = LoginForm()
if form.validate_on_submit():
flash('Login requested for... |
import numpy as np
import random
import json
import sys
import config
from env import make_env
import time
import os
import cma
from es import SimpleGA, CMAES, PEPG, OpenES
from gym.wrappers import Monitor
final_mode = False
render_mode = True
RENDER_DELAY = True
record_video = False
MEAN_MODE = False
record_rgb = Fals... |
from alembic.migration import MigrationContext
from alembic.operations import Operations
import sqlalchemy as sa
from toolz.curried import do, operator as op
from zipline.assets.asset_writer import write_version_info
from zipline.utils.compat import wraps
from zipline.errors import AssetDBImpossibleDowngrade
from zipli... |
import os
import mock
import grpc
from grpc.experimental import aio
import math
import pytest
from proto.marshal.rules.dates import DurationRule, TimestampRule
from google.api_core import client_options
from google.api_core import exceptions as core_exceptions
from google.api_core import future
from google.api_core imp... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.