content
string
""" This module define a widget that displays icons to launch softwares or commands when clicked -- a launchbar. Only png icon files are displayed, not xpm because cairo doesn't support loading of xpm file. The order of displaying (from left to right) is in the order of the list. If no icon was found for the name prov...
#!/usr/bin/env python """This is a much simpler version of the aliens.py example. It makes a good place for beginners to get used to the way pygame works. Gameplay is pretty similar, but there are a lot less object types to worry about, and it makes no attempt at using the optional pygame modules. It does provide a go...
#!usr/bin/python # -*- coding: utf-8 -*- from random import randint import subprocess import traceback import os import json from utils import log # TODO Sunlight und temperature json dict nicht vollständig, da fehlen werte dazwischen class FlowerPowerService(): """ This Class represents a FlowerPower Device ...
""" convert train.tsv to libsvm, save vocabulary, skip empty lines: text2libsvm.py train.tsv train.txt -s vocab.txt convert test.tsv to libsvm using previously saved vocabulary: text2libsvm.py test.tsv test.txt -l vocab.txt -t 1 """ import sys import csv import json import argparse import numpy as np from sklearn.dat...
ANSIBLE_METADATA = { 'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community' } from ansible.module_utils.six import string_types from ansible.module_utils.stonesoft_util import ( StonesoftModuleBase, format_element) try: from smc.vpn.policy import PolicyVPN except Impor...
from __future__ import absolute_import, division, print_function from .data_viewer import DataViewer from ...external.qt.QtGui import QTableView from ...external.qt.QtCore import Qt, QAbstractTableModel import numpy as np class DataTableModel(QAbstractTableModel): def __init__(self, data): super(DataT...
from iDrive.models import * from rest_framework import serializers from django.contrib.auth.models import User class BarUserSerializer(serializers.ModelSerializer): promotions = serializers.PrimaryKeyRelatedField( many=True, required=False) cur_parties = serializers.SerializerMethodField( 'get...
import nltk from nltk.corpus import wordnet as wn, stopwords from nltk.tag import * def get_wordnet_pos(treebank_tag): ''' Used to convert POS to a format usable with wordnet ''' if treebank_tag.startswith('J'): return wn.ADJ elif treebank_tag.startswith('V'): return wn.VERB el...
from openerp import models, fields, api, _ from openerp.exceptions import UserError import requests import tempfile import StringIO import zipfile import os import logging try: import unicodecsv except ImportError: unicodecsv = None logger = logging.getLogger(__name__) class BetterZipGeonamesImport(models.T...
include NATLayer_rpc.repy # This test connects a server to a forwarder and uses waitforconn # Then it is tested to make the forwarder will reject clients once the max number # is connected (currently 8 per server) # There is no expected output serverMac = "SERVERSERVER" MAX_CONNECTED = 4 # The test will be forced...
# -*- coding: utf-8 -*- """Lightweight and dynamic MPlayer wrapper with a Pythonic API Classes: Player -- provides a clean, Pythonic interface to MPlayer CmdPrefix -- contains the prefixes that can be used with MPlayer commands Step -- use with property access to implement the 'step_property' command AsyncPlayer --...
from pyramid import testing from pytest import mark from pytest import fixture from webtest import TestResponse # TODO: move _create_proposal to somewhere in backend fixtures as the # natural dependency ordering is "frontend depends on backend" from mercator.tests.fixtures.fixturesMercatorProposals1 import _create_pro...
from __builtin__ import unicode from antlr4.Token import Token from antlr4.error.ErrorListener import ProxyErrorListener, ConsoleErrorListener class Recognizer(object): tokenTypeMapCache = dict() ruleIndexMapCache = dict() def __init__(self): self._listeners = [ ConsoleErrorListener.INSTANCE ] ...
import uuid from flask import Blueprint, request, url_for, flash, redirect from flask import render_template from flask.ext.login import login_user, logout_user from flask.ext.wtf import Form, TextField, TextAreaField, PasswordField, validators, ValidationError from bibserver.config import config import bibserver.dao...
from pyparsing import QuotedString, Keyword from invenio.modules.jsonalchemy.parser import FieldBaseExtensionParser, \ ModelBaseExtensionParser, indentedBlock class DescriptionParser(FieldBaseExtensionParser, ModelBaseExtensionParser): """ Handles the description section in model and field definitions:: ...
"""Combinatorial parsing framework""" # Copyright (c) 2017 Darren M. Struthers <<EMAIL>> # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation...
''' Provides a GUI interface using the Wx backend. ''' try: from wxgui_swig import * except ImportError: dirname, filename = os.path.split(os.path.abspath(__file__)) __path__.append(os.path.join(dirname, "..", "..", "swig")) from wxgui_swig import *
from __future__ import print_function # import ContinuousComponentModel as CCM hyper_map = dict() hyper_map["mu"] = 1.0 hyper_map["s"] = 1.0 hyper_map["nu"] = 1.0 hyper_map["r"] = 2.0 CCM.set_string_double_map(hyper_map) component_model = CCM.p_ContinuousComponentModel(hyper_map) print(component_model.calc_marginal_...
""" Disqus OAuth2 backend, docs at: http://psa.matiasaguirre.net/docs/backends/disqus.html """ from social.backends.oauth import BaseOAuth2 class DisqusOAuth2(BaseOAuth2): name = 'disqus' AUTHORIZATION_URL = 'https://disqus.com/api/oauth/2.0/authorize/' ACCESS_TOKEN_URL = 'https://disqus.com/api/oauth...
# -*- coding: utf-8 -*- from __future__ import print_function import argparse import os import stat import sys # find the import for catkin's python package - either from source space or from an installed underlay if os.path.exists(os.path.join('/opt/ros/kinetic/share/catkin/cmake', 'catkinConfig.cmake.in')): sys....
import os from sqlalchemy.orm import scoped_session from wsgiref.simple_server import make_server from pyramid.config import Configurator from pyramid.response import Response # FIXME: Why is this import needed? If not present the server will fail # to work. (ti) <2014-05-20 17:08> from sqlalchemy.orm import scoped_se...
import pytest from pex.util import named_temporary_file from pex.variables import Variables def test_process_pydoc(): def thing(): # no pydoc pass assert Variables.process_pydoc(thing.__doc__) == ('Unknown', 'Unknown') def other_thing(): """Type Properly formatted text. """...
from util import exception import annotate def find_window_tokens(tokens, current_token_idx, window_start, window_size): ''' Window tokens for the estimation position. Duplicate tokens are considered only once. :param tokens: list of text tokens :param current_token_idx: the curren...
import sys, time import numpy as np from numpy.random import normal, multivariate_normal from six.moves import range try: import nestle except(ImportError): pass try: import dynesty from dynesty.utils import * from dynesty.dynamicsampler import _kld_error except(ImportError): pass __all__ =...
from database.db0 import db0, Channel, ConstDB from utils.log import Logger, Resource, Action from binascii import hexlify, unhexlify from userver.object.device import ClassType from userver.frequency_plan import frequency_plan class ConstCMD: DutyCycleReq = b'\x04' RXParamSetupReq = b'\x05' DevStatusReq ...
"""WebElement implementation.""" from command import Command from selenium.common.exceptions import NoSuchAttributeException from selenium.webdriver.common.by import By from selenium.webdriver.common.keys import Keys class WebElement(object): """Represents an HTML element. Generally, all interesting operatio...
#-*-coding:utf-8-*- import re,sys,os import locale,codecs ''' open file use the default encoding 以默认的编码格式打开文件:没有使用binary格式 ''' def print_str(str): print(str) def print_len(str): str_len = len(str) print(str_len) def codecs_encode(str,encoding='utf-8'): return str.encode(encodi...
import ssl as ssl_module from eventlet import patcher from oslo_serialization import jsonutils from murano.common.messaging import subscription kombu = patcher.import_patched('kombu') class MqClient(object): def __init__(self, login, password, host, port, virtual_host, ssl=False, ca_certs=None...
import mock from ironic.common import dhcp_factory from ironic.common import exception from ironic.dhcp import neutron from ironic.dhcp import none from ironic.openstack.common import context from ironic.tests import base class TestDHCPFactory(base.TestCase): def setUp(self): super(TestDHCPFactory, self...
from reaktoro import * editor = ChemicalEditor() editor.addAqueousPhaseWithElementsOf("H2O NaCl CaCO3") editor.addGaseousPhase(["H2O(g)", "CO2(g)"]) editor.addMineralPhase("Calcite") system = ChemicalSystem(editor) problem = EquilibriumInverseProblem(system) problem.add("H2O", 1, "kg") problem.add("NaCl", 0.1, "mol"...
from __future__ import division, print_function, absolute_import import numpy as np from numpy.testing import (run_module_suite, assert_equal, assert_array_equal, assert_array_almost_equal, assert_approx_equal, assert_raises, assert_allclose) from scipy.special imp...
from django.test import TestCase from corehq.apps.users.models import WebUser from corehq.apps.domain.shortcuts import create_domain from django.test.client import Client from django.core.urlresolvers import reverse import os from couchforms.dbaccessors import get_forms_by_type, clear_forms_in_domain from dimagi.utils....
# -*- coding: utf-8 -*- import os import re import string import subprocess from module.plugins.internal.Extractor import Extractor, ArchiveError, CRCError, PasswordError from module.plugins.internal.misc import decode, encode, fsjoin, renice class UnRar(Extractor): __name__ = "UnRar" __type__ = "extr...
"""Tests for base_parser default values.""" import tensorflow as tf from kws_streaming.models import model_params from kws_streaming.train import base_parser FLAGS = None class BaseParserTest(tf.test.TestCase): def test_default_values(self): params = model_params.Params() # validate default parameters to...
from __future__ import absolute_import import numpy as np from .utils import _maybe_get_pandas_wrapper # the data is sampled quarterly, so cut-off frequency of 18 # Wn is normalized cut-off freq #Cutoff frequency is that frequency where the magnitude response of the filter # is sqrt(1/2.). For butter, the normalized...
''' Module containing all errors defined in DOPAL. ''' def as_error(error, error_class, **kwargs): if not isinstance(error, error_class): error = error_class(error=error, **kwargs) return error def raise_as(error, error_class, **kwargs): import sys raise as_error(error, error_class, **kwargs),...
from six import string_types import vcr import types import requests from nose.tools import * # flake8: noqa # Comment line below prevents unittest from deletion in import optimization # noinspection PyUnresolvedReferences import unittest from osf_api_v2_client.settings.local import ( URL, # e.g. ...
# -*- 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 model 'InterimChannel' db.create_table(u'comms_interimchannel', ( (u'id', self.gf('djan...
#!/usr/bin/env python """combine list of tractor cats and match them along the way Example of Matched Comparison: from legacyanalysis.combine_cats import Matched_DataSet import common_plots as plots d= Matched_DataSet(list_of_ref_cats,list_of_test_cats) plots.confusion_matrix(d.ref_matched.t,d.test_matched.t) """ fr...
from .copy_sink import CopySink class BlobSink(CopySink): """A copy activity Azure Blob sink. :param additional_properties: Unmatched properties from the message are deserialized this collection :type additional_properties: dict[str, object] :param write_batch_size: Write batch size. Type: integ...
# -*- coding: utf-8 """Unit tests for didyoumean APIs.""" from didyoumean_api import didyoumean_decorator, didyoumean_contextmanager,\ didyoumean_postmortem, didyoumean_enablehook, didyoumean_disablehook from didyoumean_common_tests import TestWithStringFunction,\ get_exception, no_exception, NoFileIoError, uni...
tlentry(['AUTIA1716', 'AUTIASP', 'AUTIAZ', 'AUTIB1716', 'AUTIBSP', 'AUTIBZ', 'CFINV', 'CSDB', 'DRPS', 'ERET', 'ESB', 'NOP', 'PACIA1716', 'PACIASP', 'PACIAZ', 'PACIB1716', 'PACIBSP', 'PACIBZ', 'PSSBB', 'SB', 'SEV', 'SEVL', 'SSBB', 'WFE', 'WFI', 'XPACLRI', 'YIELD'], '', (), matcher = '', processor = '', ) ...
from BitTorrent.download import download from threading import Event from os.path import abspath from signal import signal from sys import argv, stdout from time import strftime, time def fmttime(n): if n == -1: return 'download not progressing (file not being uploaded by others?)' if n == 0:...
import os.path as op import numpy as np from numpy.testing import (assert_array_almost_equal, assert_array_equal, assert_equal, assert_allclose) import pytest from mne import (read_cov, read_forward_solution, convert_forward_solution, pick_types_forward, read_evokeds, pick_...
import datetime import operator from ceilometer.alarm import evaluator from ceilometer.alarm.evaluator import utils from ceilometer.openstack.common.gettextutils import _ # noqa from ceilometer.openstack.common import log from ceilometer.openstack.common import timeutils LOG = log.getLogger(__name__) COMPARATORS = ...
import numbers from abc import ABCMeta, abstractmethod from typing import Any, TYPE_CHECKING, Union from pandas.api.types import CategoricalDtype from pyspark.sql.types import ( ArrayType, BinaryType, BooleanType, DataType, DateType, FractionalType, IntegralType, MapType, NumericTy...
from tempest.api.identity import base from tempest.common.utils import data_utils from tempest import test class EndPointsTestJSON(base.BaseIdentityV3AdminTest): _interface = 'json' @classmethod @test.safe_setup def setUpClass(cls): super(EndPointsTestJSON, cls).setUpClass() cls.ident...
<<<<<<< HEAD <<<<<<< HEAD # Check every path through every method of UserList from collections import UserList from test import support, list_tests class UserListTest(list_tests.CommonTest): type2test = UserList def test_getslice(self): super().test_getslice() l = [0, 1, 2, 3, 4] u = ...
from collections import defaultdict import xml.etree.ElementTree as ET import json class XMLUtils(object): ''' Utilities methods for XML ''' @staticmethod def string_to_xml(xmlInString): ''' Convert string into XML tree structure ''' pass @s...
#!/usr/bin/python import numpy as np from constants import WEIGHT_DTYPE class Perceptron(): def __init__(self,model): self.model = model self.num_updates = 0 def get_num_updates(self): return self.num_updates def no_update(self): self.model.wstep += 1 ...
#!/usr/bin/env python3 #-*- coding: utf-8 -*- ############################################## # Home : http://netkiller.github.io ############################################## try: from struct import * from optparse import OptionParser, OptionGroup from Protocol import * import socketserver, os, sys except ImportE...
''' Use the peak velocity diskfit with a radial component to estimate the radial mass flow in the disk. ''' from spectral_cube import Projection from astropy.io import fits import astropy.units as u import numpy as np from astropy.table import Table import matplotlib.pyplot as plt import seaborn as sb from constants ...
# -*- coding: utf-8 -*- import pytest from app import APP, auth from helper import login, create_api_creds, get_auth_api # get test user TEST_USER = APP.config['TEST_USER'] @pytest.mark.parametrize('test_user, status_code', [ (TEST_USER[0], 200), (TEST_USER[1], 401)]) def test_valid_users_and_groups(client...
import praw import json import tweepy import nltk import re import unicodedata from collections import Counter from TwitterSearch import * # consumerKey = "abcxlLAasaG6HeFfay0EWqMB9" # consumerSecret = "tgbBqKegyCb2gj5f4oPhAsCz7mfzmPejzDcgVIGHeKp8hSndWf" # accessToken = "984449647-2u5RQKEsptAKI4aDzyYjwFqBsG1JXdWx6T...
from logging import getLogger logger = getLogger(__name__) class CandelabraException(Exception): """ Root exception for all the Candelabra errors """ pass ######################################### # usage and config file class UnsupportedCommandException(CandelabraException): """ Unsupported comm...
import os import shutil import subprocess import tempfile import uuid from multiprocessing import Pool, cpu_count from decorators import checkcache from config import configuration as conf class Converter: def __init__(self): self.conf = conf def textopdf(self, *args, **kwargs): """ D...
from __future__ import print_function import unittest from os import path from shyft import shyftdata_dir from shyft import api from shyft.repository.netcdf.concat_data_repository import ConcatDataRepository #from shyft.repository.netcdf.concant_data_repository import ConcatDataRepositoryError from shapely.geometry im...
# TensorFlow Tutorial #01 Simple Linear Model # by Magnus Erik Hvass Pedersen http://www.hvass-labs.org/ # imports ############################### # %matplotlib inline # import matplotlib.pyplot as plt import tensorflow as tf import numpy as np from sklearn.metrics import confusion_matrix # load data ###############...
import os import os.path import re import stat # URL/Form encoding safe_chars = ('ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz' '0123456789' '_.-') def quote_hex(s, safe=''): """ Replace potentially unsafe characters in 's' with their %XX hexadecimal counterparts. ...
""" Django settings for Libreosteo project. For more information on this file, see https://docs.djangoproject.com/en/1.7/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.7/ref/settings/ """ # Build paths inside the project like this: os.path.join(BASE...
from django.http import HttpResponse from django.views.decorators.csrf import csrf_exempt import json import random import ast import numpy as np from polls.models import Story, CharacterObjects, Frame, Character # Create your views here. def index(request): #example of json return HttpResponse("FIGHTME IRL")...
import os import numpy as np from nibabel.tmpdirs import InTemporaryDirectory from ..dpy import Dpy, have_tables from nose.tools import assert_true, assert_false, \ assert_equal, assert_raises from numpy.testing import assert_array_equal, assert_array_almost_equal import numpy.testing as npt # Decorator to p...
#!/usr/bin/env python """Read events from rtl_433 and gpsd and print out.""" # Needs gpsd (and the Python support from gpsd) # Start gpsd and rtl_433 (rtl_433 -F syslog::1433), then this script from __future__ import print_function import socket import json import gps import threading # rtl_433 syslog address UDP_...
import random import argparse import discord from discord.ext import commands from roxbot import http, config, exceptions class ArgParser(argparse.ArgumentParser): """Create Roxbot's own version of ArgumentParser that doesn't exit the program on error.""" def error(self, message): # By passing here,...
import os import numpy as np import matplotlib.pyplot as plt from matplotlib.pyplot import figure, show, axes, sci from matplotlib import cm, colors from matplotlib.font_manager import FontProperties from numpy import amin, amax, ravel from numpy.random import rand #****************************************************...
## find a topologtical ordering using DFS from collections import defaultdict def DFS(graph, i): global t global ftime ## finish time global dtime ## discovery time global explored ## 1: discovered; 2: finished. Q = [i] while len(Q)>0: v = Q.pop() if not explored[v]: ...
#!/usr/bin/env python import dns.resolver # # This filter resolves DNS name into IP. # # First parameter is the structure that may contains FQDN to resolve. # Second parameter is a list of DNS servers to run a dns query against. # # The first parameter could be one of the following: # 1. hash (dict). See possible opt...
# -*- coding: utf-8 -*- import io from setuptools import setup, find_packages import sys setup( name='django-pipeline', version='2.0.5', description='Pipeline is an asset packaging library for Django.', long_description=io.open('README.rst', encoding='utf-8').read() + '\n\n' + io.open('HISTORY...
#MenuTitle: 12 Randomize Glyph from robofab.world import CurrentFont, CurrentGlyph from robofab.objects.objectsRF import RGlyph from fontTools.pens.basePen import BasePen class MyPen(BasePen): # from fontTools.pens.basePen.BasePen: def __init__(self, glyphSet, writer_pen): self.glyphSet = glyphSet...
from bot import db def save(data): sql = """ insert into clippingsbot.teams ( team_id, access_token, user_id, team_name, scope ) values ( :team_id, :access_token, :user_id, :team_name, :scope ) on conflict (team_id) do update set scope = excluded.scope, access_token = exclud...
LITHUANIAN_NUMBER_COMMON = ("nulis", "vienas", "du", "trys", "keturi", "penki", "šeši", "septyni", "aštuoni", "devyni", "dešimt", "vienuolika", "dvylika", "trylika", "keturiolika", "penkiolika", "šešiolika", "septyniolika", "aštuoniolik...
import sys sys.path.insert(1, "../../../") import h2o, tests import numpy as np import random as rd def glrm_set_loss_by_col_rand(): NUM_LOSS = ["Quadratic", "Absolute", "Huber", "Poisson", "Periodic"] CAT_LOSS = ["Categorical", "Ordinal"] NUM_COLS = [1, 5, 6, 7] CAT_COLS = [0, 2, 3, 4] print ...
__all__ = ['HttpWhoHas'] from gevent import monkey; monkey.patch_all() # flake8: noqa import gevent from gevent.queue import Queue from random import sample import urllib2 import logging class DefaultErrorHandler(urllib2.HTTPDefaultErrorHandler): def http_error_default(self, req, fp, code, msg, headers): ...
import imp import os import re import sys from Blender import Scene class BlenderScript(object): def __init__(self): self.args = Arguments() self.render_path = os.path.dirname(self.args['render_path']) def render(self): scene = Scene.GetCurrent() script = imp.load_source(sel...
#!/usr/bin/env python import os,sys,time,getopt,shlex, shutil from subprocess import Popen, PIPE from glob import glob LAST_COMPILE_TIME = 0 def cmd_output_throws_error(flags, response, err, error_msg): if "error" in response.lower() or "bad session" in response.lower() or "unfinished session" in response.lower(): ...
#!/usr/bin/env python # # tournament.py -- implementation of a Swiss-system tournament import psycopg2 """ from math import log2 def isPowerOfTwo(num): power = int(log2(num) + 0.5) return 2**power == num """ def connect(): """Connect to the PostgreSQL database. Returns a database connection and a...
from ..remote import RemoteModel class SensorDatumRemote(RemoteModel): """ Sensor data about the health of the NetMRI | ``id:`` The internal NetMRI identifier for the table entry. | ``attribute type:`` number | ``data_source_id:`` The internal NetMRI identifier for the collector NetMRI that ...
from datetime import datetime, timedelta from mock import patch from django.test import TestCase from django.contrib.auth.models import User from django.contrib.messages import constants as message_const from django_dynamic_fixture import get from django_dynamic_fixture import new from readthedocs.core.models import ...
from .. import _create_enum_class from ._ffi import ffi, lib from .gibaseinfo import GIBaseInfo, GIInfoType from .gitypeinfo import GITypeInfo GIFieldInfoFlags = _create_enum_class(ffi, "GIFieldInfoFlags", "GI_FIELD_IS_") @GIBaseInfo._register(GIInfoType.FIELD) class GIFieldInfo(GIBaseInfo): def get_flags(self...
import socket, threading, select import greensd.logger from greensd.constants import IPC_SERVER_PORT, IPC_DELIMITER, LIVE_SESSION_INIT, LIVE_SESSION_ERROR #******************************************************* # IPC Server Class #******************************************************* class IPCSrv(threading.Thread):...
from collections import namedtuple import os import re import unittest from mock import patch, ANY from common import SushiError, format_time from sushi import parse_args_and_run, detect_groups, interpolate_nones, get_distance_to_closest_kf, fix_near_borders, \ running_median, smooth_events, groups_from_chapters h...
#!/usr/bin/env python # """make coverage stats for bam files in directory""" import sys import pysam import os input_dir = sys.argv[1] watson_bam = pysam.AlignmentFile(os.path.join(input_dir,'watson.dedup.bam'),'rb') crick_bam = pysam.AlignmentFile(os.path.join(input_dir,'crick.dedup.bam'),'rb') coverage_dict = {'s...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('board', '0014_auto_20150729_0927'), ] operations = [ migrations.CreateModel( name='Attachment', fiel...
import argparse import collections import fnmatch import os import sys VALID_TOOLCHAINS = [ 'bionic', 'clang-newlib', 'newlib', 'glibc', 'pnacl', 'win', 'linux', 'mac', ] # 'KEY' : ( <TYPE>, [Accepted Values], <Required?>) DSC_FORMAT = { 'DISABLE': (bool, [True, False], False), 'SEL_LDR': (boo...
# Server code for the CheeseCave import BaseHTTPServer import cgi import json import subprocess import sys class CheesecaveHandler(BaseHTTPServer.BaseHTTPRequestHandler): DOC_ROOT = "/opt/pi/CheeseCave/DocRoot" SNAPSHOT = "/opt/pi/CheeseCave/current_snapshot" # def do_HEAD(self): # if self.path == "/": # self.s...
from google.cloud.mediatranslation_v1beta1.services.speech_translation_service.client import ( SpeechTranslationServiceClient, ) from google.cloud.mediatranslation_v1beta1.services.speech_translation_service.async_client import ( SpeechTranslationServiceAsyncClient, ) from google.cloud.mediatranslation_v1beta1...
from flask import Blueprint, url_for, request, flash, redirect, session, current_app from .models import User blueprint = Blueprint('auth.oauth', __name__) def oauth_failed(next_url): flash('You denied the request to sign in.') return redirect(next_url) @blueprint.route("/login/oauth/<provider>") def login...
from collections import namedtuple from decimal import Decimal as D from . import availability, prices # A container for policies PurchaseInfo = namedtuple( 'PurchaseInfo', ['price', 'availability', 'stockrecord']) class Selector(object): """ Responsible for returning the appropriate strategy class for...
#!/usr/bin/env python3 import argparse import os import sys from util.utils import fail, shellcomm ################### # main() handling # ################### def parse_args(): desc = """ Use virtio-win-guest-tools-installer.git to build driver .msis and .exe to add to the ISO Example: %(prog)s /path/to/built...
""" * と ** のアンパック演算子についてのサンプルです PEP484 の動作について REFERENCES:: http://bit.ly/2VMowpQ """ from trypython.common.commoncls import SampleBase from trypython.common.commonfunc import pr # noinspection PyMethodMayBeStatic class Sample(SampleBase): def exec(self): # ----------------------------------------------...
import argparse import subprocess import time from helpers import fake2db_logger logger, extra_information = fake2db_logger() class InstantiateDBHandlerException(Exception): '''An Exception at the instantiation of the handler ''' class MissingDependencyException(Exception): '''An Exception to be throw...
from redis import Redis, RedisError, ConnectionPool import itertools import time import six from six.moves import zip from .document import Document from .result import Result from .query import Query, Filter from ._util import to_string from .aggregation import AggregateRequest, AggregateResult, Cursor class Field(...
from pdu import * class PDU(object): def __init__(self, command_id, command_status, sequence_number, **kwargs): super(PDU, self).__init__() self.obj = {} self.obj['header'] = {} self.obj['header']['command_length'] = 0 self.obj...
# -*- coding: utf-8 -*- import sae.const DEBUG = False SITE_TITLE = u"博客标题" SITE_SUB_TITLE = u"博客副标题" SITE_KEYWORDS = u"博客关键字" SITE_DECRIPTION = u"博客描述" AUTHOR_NAME = u"博客作者" #显示在RSS订阅里面 #CONACT_MAIL = "<EMAIL>" #暂未用到 THEMES = ['octopress','admin'] LINK_BROLL = [ {'text': u"爱简单吧", 'url': "http://www.ijd8.c...
import logging from pantomime import normalize_mimetype, normalize_extension log = logging.getLogger(__name__) class Ingestor(object): """Generic ingestor class.""" MIME_TYPES = [] EXTENSIONS = [] SCORE = 3 def __init__(self, manager): self.manager = manager def ingest(self, file_p...
from __future__ import absolute_import, division, print_function from datetime import datetime from json import loads from urllib import urlencode import requests from flask import current_app from flask_login import current_user from idutils import is_arxiv from invenio_search import current_search_client as es from...
import time import pickle from pydal import DAL, Field from ._compat import unittest from ._adapt import DEFAULT_URI, IS_IMAP, IS_MSSQL from ._helpers import DALtest class SimpleCache(object): storage = {} def clear(self): self.storage.clear() def _encode(self, value): return value ...
import sling from action import Action # Outputs a list of transitions that represent a given document's frame graph. class TransitionGenerator: # Bookkeeping for one frame. class FrameInfo: def __init__(self, handle): self.handle = handle self.type = None self.edges = [] self.from_ment...
import numpy as np import matplotlib.patches import matplotlib.collections import matplotlib.pyplot as plt # plt.style.use('kostas') def initial_xy_polar(r_min, r_max, r_N, theta_min, theta_max, theta_N): return np.array([[(r * np.cos(theta), r * np.sin(theta)) for r in np.linspace(r_min, ...
import unittest import numpy as np import six import chainer from chainer import functions as F from chainer import optimizers from chainer import testing _all_optimizers = [ 'AdaDelta', 'AdaGrad', 'Adam', 'AdamW', 'AMSGrad', 'AdaBound', 'AMSBound', 'CorrectedMomentumSGD', 'Momen...