content
stringlengths
4
20k
import socket import requests import threading import hashlib import json try: import PyQt4 except Exception: sys.exit("Error: Could not import PyQt4 on Linux systems, you may try 'sudo apt-get install python-qt4'") from PyQt4.QtGui import * from PyQt4.QtCore import * import PyQt4.QtCore as QtCore import PyQt...
import requests import json import base64 import logging from odoo.tests.common import HttpCase from odoo.tests import tagged _logger = logging.getLogger(__name__) @tagged('post_install', '-at_install', '-standard', 'external') class TestPingenSend(HttpCase): def setUp(self): super(TestPingenSend, self)...
from __future__ import with_statement import os, sys import tempfile import shutil from wic import kickstart from wic import msger from wic.utils.errors import CreatorError from wic.utils import misc, runner, fs_related as fs class BaseImageCreator(object): """Base class for image creation. BaseImageCreator ...
import pytest from pytest_bdd import ( scenarios, then, when, ) from . import browsersteps pytestmark = [ pytest.mark.bdd, pytest.mark.usefixtures('workbook', 'admin_user'), ] scenarios( 'title.feature', 'select_variant.feature', 'variant_curation_tabs.feature', 'generics.feature',...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ An example showing how to deploy a minimal weblayer application on `Google App Engine`_. Note that you must have :ref:`weblayer` and its dependencies included in :py:obj:`sys.path`, e.g.: by copying them into this folder. Check the ``install_requires`` lis...
from __future__ import division from datetime import timedelta, datetime from collections import defaultdict from matplotlib.ticker import EngFormatter import matplotlib.pyplot as plt import pickle import sys from copy import deepcopy import numpy as np # mswim module path sys.path.insert(0, '/var/www/mswim/') # msw...
# coding=utf-8 from __future__ import unicode_literals, print_function from flask import request, jsonify import bugsnag from . import replication from webhookdb.models import PullRequestFile from webhookdb.exceptions import MissingData, StaleData from webhookdb.tasks.pull_request import process_pull_request from webh...
""" Utility functions for SDA Includes batch generation methods, and generator repeating/merging. Ken Chen """ import random import csv import time from math import ceil from functools import wraps def stopwatch(f): """Simple decorator that prints the execution time of a function.""" @wraps(f) def wra...
import time from ..settings import Arguments class TDMA_Scheduler(object): def __init__(self, id, arguments): """ Initialize the TDMA scheduler. """ if isinstance(arguments, Arguments): self._settings = arguments.get_settings("zigbee_tdma_scheduler") else: ...
from __future__ import division import thorpy import pygame import parameters from thorpy import LifeBar ##class LifeBar(thorpy.Element): ## ## def __init__(self, text, color=(255,165,0), text_color=(0,0,0), ## size=(200,30), font_size=None): ## thorpy.Element.__init__(self) ## pain...
import inspect import os from robot.errors import DataError from robot.libraries import STDLIBS, DEPRECATED_STDLIBS from robot.output import LOGGER from robot.utils import (getdoc, get_error_details, Importer, is_java_init, is_java_method, JYTHON, normalize, seq2str2, unic) from .dynamicmetho...
from core.loggers import dlog from core import config import re import urllib.parse import random import utils import string import base64 import urllib.request, urllib.error, urllib.parse import hashlib import zlib import http.client import string PREPEND = utils.strings.randstr(16, charset = string.printable) APPEND...
""" Data iterator for text datasets that are used for language modeling. """ __docformat__ = 'restructedtext en' __authors__ = ("Razvan Pascanu " "Caglar Gulcehre " "KyungHyun Cho ") __contact__ = "Razvan Pascanu <r.pascanu@gmail>" import numpy import logging logger = logging.getLogger(_...
""" To be used with ipython when it starts up. Create a sym-link to this file in the default ipython profile like so: ln -s ~/repo/sandpit/start_ipython.py ~/.ipython/profile_default/startup/start_ipython.py """ import datetime import decimal import itertools import json import math imp...
from qpid.datatypes import Message, RangedSet from qpid.testlib import TestBase010 class ExampleTest (TestBase010): """ An example Qpid test, illustrating the unittest framework and the python Qpid client. The test class must inherit TestBase. The test code uses the Qpid client to interact with a qpid...
# -*- coding: utf-8 -*- """ Tests for student profile views. """ import datetime import ddt import mock from lms.djangoapps.certificates.tests.factories import GeneratedCertificateFactory # pylint: disable=import-error from course_modes.models import CourseMode from django.conf import settings from django.core.urlre...
import functools import os import shutil import tempfile class temporary_directory(object): def __init__(self, prefix=''): self.prefix = prefix def __enter__(self): self.original_cwd = os.getcwd() self.temp_path = tempfile.mkdtemp(prefix=self.prefix) os.chdir(self.temp_path) ...
import sys sys.path.insert(1,"../../") import h2o from tests import pyunit_utils def weights_api(): h2o_iris_data = h2o.import_file(pyunit_utils.locate("smalldata/iris/iris.csv")) r = h2o_iris_data.runif() iris_train = h2o_iris_data[r > 0.2] iris_valid = h2o_iris_data[r <= 0.2] # tra...
import pecan from pecan import rest import wsmeext.pecan as wsme_pecan from solum.api.controllers.camp.datamodel import platform_endpoint as model from solum.api.controllers.camp.v1_1 import uris from solum.common import exception URI_STRING = '%s/camp/camp_v1_1_endpoint' NAME_STRING = 'Solum_CAMP_v1_1_endpoint' DES...
from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['stableinterface'], 'supported_by': 'core'} DOCUMENTATION = r''' --- module: find author: Brian Coca (based on Ruggero Marchei's Tidy)...
import logging from mla.datasets import load_mnist from mla.metrics import accuracy from mla.neuralnet import NeuralNet from mla.neuralnet.layers import Activation, Convolution, MaxPooling, Flatten, Dropout, Parameters from mla.neuralnet.layers import Dense from mla.neuralnet.optimizers import Adadelta from mla.utils ...
''' Copyright (c) 2012 Matt Layman Gzip cache ---------- A plugin to create .gz cache files for optimization. ''' import logging import os import zlib from pelican import signals logger = logging.getLogger(__name__) # A list of file types to exclude from possible compression EXCLUDE_TYPES = ( # Compressed typ...
"""Tests for converters utilities.""" from textwrap import dedent from maasserver.utils.converters import ( human_readable_bytes, machine_readable_bytes, round_size_to_nearest_block, XMLToYAML, ) from maastesting.testcase import MAASTestCase class TestXMLToYAML(MAASTestCase): def test_xml_to_ya...
from ..utils.errors import ProgressiveError from ..core.utils import indices_len, fix_loc from ..table.module import TableModule from ..table.table import Table from ..core.slot import SlotDescriptor from ..core.decorators import * import numpy as np # Should use a Cython implementation eventually from tdigest import...
"""Streaming HTTP uploads module. This module extends the standard httplib and urllib2 objects so that iterable objects can be used in the body of HTTP requests. In most cases all one should have to do is call :func:`register_openers()` to register the new streaming http handlers which will take priority over the def...
import demisto_client.demisto_api from demisto_client.demisto_api.rest import ApiException from datetime import datetime import tempfile import os import time api_key = None # set to your 'YOUR_API_KEY' or set environment variable: DEMISTO_API_KEY base_url = None # set to your 'http://DEMISTO_HOST' or set environmen...
__author__ = "Nick Wong" ''' Windows下运行 分布式进程 服务进程 在Unix/Linux下,multiprocessing模块封装了fork()调用,使我们不需要关注fork()的细节。由于Windows没有fork调用, 因此,multiprocessing需要“模拟”出fork的效果,父进程所有Python对象都必须通过pickle序列化再传到子进程去, 所有,如果multiprocessing在Windows下调用失败了,要先考虑是不是pickle失败了。 不支持匿名函数,所以将其提取出来定义 ''' import random, time, queue from mult...
""" Simple example: .. UIExample:: 50 b = ui.Button(text="Push me") Example with interaction: .. UIExample:: 200 from flexx import app, ui, event class Example(ui.BoxPanel): def init(self): with ui.VBox(): self.b1 = ui.Button(text='apple') self.b2...
""" Useful things for plotting GeoClaw results. """ from pyclaw.plotters import colormaps from matplotlib.colors import Normalize from pyclaw.geotools import topotools from numpy import ma # Colormaps from geoclaw # Color attributes, single instance per run # Colors black = [0.0,0.0,0.0] white = [1.0,1.0,1.0] red =...
from render import get_html from bs4 import BeautifulSoup as bs4 import sys # -*- Coding: utf-8 -*- def scrape(url): soup = bs4(get_html(url), "lxml") # Uncomment to debug and/or find more css selectors #print soup s_type = find_field_from_css(soup, "span.ml-cards-entity-category.ml-cards-entity-link") pri...
#!/usr/bin/env python # coding: utf-8 """ python-creole utils ~~~~~~~~~~~~~~~~~~~ :copyleft: 2008-2011 by python-creole team, see AUTHORS for more details. :license: GNU GPL v3 or above, see LICENSE for more details. """ from __future__ import division, absolute_import, print_function, unicode_...
"""Demonstrates how to authenticate to Google Cloud Platform APIs using the Google Cloud Client Libraries.""" import argparse def implicit(): from google.cloud import storage # If you don't specify credentials when constructing the client, the # client library will look for credentials in the environmen...
# -*- coding: utf-8 -*- from setuptools import setup, find_packages # Always prefer setuptools over distutils from codecs import open # To use a consistent encoding from os import path here = path.abspath(path.dirname(__file__)) # Get the long description from the relevant file with open(path.join(here, 'README.md'...
import uuid import threading import IN import sys import struct from socket import * class UpnpListener: def __init__(self, responsePort, responseAddress, serverPort): self.enabled = True self.responsePort = responsePort self.responseAddress = responseAddress self.serverPort = serve...
#!/usr/bin/env python from pyspark import SparkConf, SparkContext from pyspark.sql import SparkSession, SQLContext import pyspark.sql.types as types import matplotlib.pyplot as plt from bokeh.plotting import figure, show, output_file from bokeh.io import output_notebook import traceback, sys def describe_statistics()...
from __future__ import absolute_import import unittest import numpy as np from tests.sample_data import SampleData from pyti import triangular_moving_average class TestTriangularMovingAverage(unittest.TestCase): def setUp(self): """Create data to use for testing.""" self.data = SampleData().get_s...
""" Factories for course mode models. """ import random import six from factory import lazy_attribute from factory.django import DjangoModelFactory from opaque_keys.edx.keys import CourseKey from common.djangoapps.course_modes.models import CourseMode from openedx.core.djangoapps.content.course_overviews.models imp...
# -*- coding: UTF-8 -*- import re import os import urllib, urllib2 from xbmcaddon import Addon from operator import itemgetter, attrgetter # Return Game search list def _get_games_list(search): results = [] display = [] try: req = urllib2.Request('http://thegamesdb.net/api/GetGamesList.php?name=...
""" unit.py ======= Contains a base class for units to force common interfaces """ from math import ceil class Unit: """ A base class supposed to contains the interface elements shared by all unit types. """ def __init__(self): # Declare some variables to shut up error checkers se...
import weakref from defcon.tools.identifiers import makeRandomIdentifier class Point(object): """ This object represents a single point. """ __slots__ = ["_x", "_y", "_segmentType", "_smooth", "_name", "_identifier"] def __init__(self, (x, y), segmentType=None, smooth=False, name=None, identifi...
from tjptemplates import tjptemplates from tjworkinghours import * class TjResource(object): # Tasks that have an effort specification need to have at least one # resource assigned to do the work. # Use this property to define resources or groups of resources. def __init__(self, id, name): se...
from pyramid import testing from paasta_tools import marathon_tools from paasta_tools.api import settings from paasta_tools.api.views.marathon_dashboard import marathon_dashboard from paasta_tools.utils import SystemPaastaConfig def test_list_instances(): settings.cluster = 'fake_cluster' system_paasta_confi...
# encoding: 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 'Bookmark.publicstate' db.add_column('bookmarks_bookmark', 'publicstate', self.gf('django.d...
__author__ = 'popov.sn' class ContactHelper: def __init__(self, app): self.app = app def add_new_contact(self, contact): wd = self.app.wd self.go_to_new_contact_page() self.fill_contact_form(contact) wd.find_element_by_xpath("//div[@id='content']/form/input[21]").click...
from fabric.api import local from jinja2 import Environment, FileSystemLoader template_env = Environment(loader=FileSystemLoader('.')) presentations = [{'name': 'fundamentals', 'title': 'Hadoop Fundamentals'}] #{'name': 'operational', 'title': 'Hadoop Operational'}] def build_all(): [build_one(...
from spack import * import sys class Mesa18(AutotoolsPackage): """Mesa is an open-source implementation of the OpenGL specification - a system for rendering interactive 3D graphics.""" homepage = "http://www.mesa3d.org" maintainers = ['v-dobrev', 'chuckatkins'] # Note that we always want to bu...
from st2reactor.sensor.base import PollingSensor class SimplePollingSensor(PollingSensor): """ * self._sensor_service - provides utilities like get_logger() for writing to logs. dispatch() for dispatching triggers into the system. * self._config - contains configura...
import datetime import pytz from mock import patch from unittest2 import TestCase from ob2.util.time import ( now_str, format_time, parse_time, parse_to_relative, ) class TestTime(TestCase): def test_time_functions(self): timestamp_str = now_str() timestamp_obj = parse_time(timest...
NSEEDS=512 MAX_SEEDS_PER_ASN=2 MIN_BLOCKS = 337600 # These are hosts that have been observed to be behaving strangely (e.g. # aggressively connecting to every node). SUSPICIOUS_HOSTS = { "130.211.129.106", "178.63.107.226", "83.81.130.26", "88.198.17.7", "148.251.238.178", "176.9.46.6", "54.173.72.127", ...
import smbus import time class TricolourLeds8(): #I2C Addresses #------------------------------------------------------------------------------- #Default bus is 0. To change the bus assign it when initialising the object #Bus to be use depends on the model of the Raspberry Pi used address_leds = 0x23 ...
""" .. function:: postgres(host, port, user, passwd, db, query:None) Connects to an PostgreSQL DB and returns the results of query. Examples: >>> sql("select * from (postgres h:127.0.0.1 port:5432 u:root p:rootpw db:testdb select 5 as num, 'test' as text);") num | text ----------- 5 | test """ im...
#!/usr/bin/env python # -*- coding: UTF-8 -*- from collections import defaultdict import math import multiprocessing from multiprocessing import Pool from itertools import repeat import json #from stemming.porter2 import stem import numpy as np import glob, os from multiprocessing import Process, Manager from multipro...
#!/usr/bin/env python # coding: utf-8 import json import os import shutil import unittest from feed2maildir.converter import Converter, HTMLStripper, ExternalHTMLStripper class AttrDict(dict): """This is a dict that can be accessed via attributes, just like the Feedparser Dict""" def __init__(self, *arg...
import json from eris.inventory.inventory_base import ErisInventoryBase class ErisAnsibleInventory(ErisInventoryBase): def __init__(self, eris_config): """ Create the Eris File Inventory from various parameters for rally and a deployment map. :param eris_config: The config file a...
import numpy as np from glotaran.parameter import ParameterGroup from glotaran.builtin.models.kinetic_image import KineticImageModel from glotaran.builtin.models.kinetic_image.kinetic_image_matrix import kinetic_image_matrix def test_baseline(): model = KineticImageModel.from_dict({ 'initial_concentratio...
import numpy as np import pytest from pandas import Index, date_range from pandas.core.reshape.util import cartesian_product import pandas.util.testing as tm class TestCartesianProduct: def test_simple(self): x, y = list('ABC'), [1, 22] result1, result2 = cartesian_product([x, y]) expect...
""" Module for QA plots """ from __future__ import print_function, absolute_import, division, unicode_literals import numpy as np from scipy import signal import scipy import pdb from desispec.log import get_logger from desispec import fluxcalibration as dsflux from desispec.util import set_backend set_backend() imp...
from django.urls.base import reverse_lazy from django.views.generic.detail import DetailView from django.views.generic.edit import CreateView, UpdateView, DeleteView from django.views.generic.list import ListView from misc.models import SubjectSector, Faculty class SubjectSectorList(ListView): model = SubjectSec...
import xbmc, xbmcaddon, xbmcgui, xbmcplugin,os,base64,sys,xbmcvfs import urllib2,urllib import re import glob import extract import downloader import time import common as Common import wipe AddonTitle="Imperio Tuga Wizard" USERDATA = xbmc.translatePath(os.path.join('special://home/userdata','')) CHECKVERSION = ...
""" Created on 10/5/16 3:44 PM @author: Numan Laanait -- <EMAIL> """ from __future__ import division, print_function, absolute_import, unicode_literals from warnings import warn import numpy as np from scipy.signal import find_peaks_cwt from .utils.be_sho import SHOestimateGuess, SHOfunc class GuessMethods(object):...
from pani import db from pani.model.user import User from pani.model.project import Project class UserProject(db.Model): __tablename__ = 'users_projects' user_id = db.Column(db.Integer, primary_key=True) project_id = db.Column(db.Integer, primary_key=True) def get_choices_form(self, user_id): ...
import time import numpy as np from mantra.util.data.labeled_object import LabeledObject from mantra.util.progress_bar import ProgressBar from mantra.util.solver.solver_utils import SolverUtils class SSGSolver: def __init__(self, loss=None, lambdaa=1e-4, num_epochs=25, sample='perm', do_weighted_averaging=False, s...
from __future__ import unicode_literals # pragma: no cover """ Configuration settings are read in this order: 1) ~/.green 2) A config file specified by the environment variable $GREEN_CONFIG 3) A config file specified by the command-line argument --config FILE 4) Command-line arguments. Any arguments specified in mor...
import chainer from chainer.backends import cuda from chainer import gradient_check from chainer import testing from chainer.testing import attr from chainer.testing import condition import numpy as np import unittest from chainercv import functions def _outsize(x): if isinstance(x, chainer.utils.collections_abc...
""" A menu driven daemon diagnostics module """ import time, os, sys, ConfigParser import init_core, init_motion, daemon_whip, mutex def daemon_diagnostic(): """ Generate a primative CLI daemon control menu and act on selections args : excepts : return : none """ # set kmot...
import sys import logging import traceback from colorlog import ColoredFormatter from logging.handlers import RotatingFileHandler LOG_NAME = 'qrl' LOG_FILENAME_DEFAULT = 'qrl.log' LOG_MAXBYTES = 100 * 1024 * 1024 LOG_FORMAT_FULL = '%(asctime)s - %(levelname)s - %(message)s' LOG_FORMAT_SMALL = '%(asctime)s - %(messag...
#!/bin/env python import re, time from datetime import datetime import mechanize from tardyrush import db, models def post_to_vbulletin_3_7(url, forum_id, username, password, subject, message): retval = None url = url.strip('/') def find_login_form(form): if re.search("login\.php", form.action):...
# -*- coding: utf-8 -*- from __future__ import print_function, absolute_import import os, json from learnbot_dsl.blocksConfig.blocks import pathBlocks as pathImgBlocks pathConfig = os.path.dirname(os.path.realpath(__file__)) renamedB = {"blockVertical":"block1", "blockBoth":"block3", "blockLeft":"block4"} def relo...
import os import requests class GoogleApi: _geocode_url = 'https://maps.googleapis.com/maps/api/geocode/json?place_id={0}&key={1}' _distance_url = 'https://maps.googleapis.com/maps/api/distancematrix/json?origins={0},{1}&destinations={2},{3}&key={4}' _api_key = 'AIzaSyCMXvF5nhmLpAYb6HcZ4YtUWDWlGcMlpE8' ...
'''applications.py: common classes for ufw''' # # Copyright 2008-2012 Canonical Ltd. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License version 3, # as published by the Free Software Foundation. # # This program is distributed in t...
#!/usr/bin/python3 from json import dumps from datetime import datetime import os from bottle import app as bottleapp from bottle import route, run, static_file, template from pymongo import MongoClient import sprout os.chdir(os.path.dirname(os.path.abspath(__file__))) mongo = MongoClient('localhost', 27017) col = mo...
#!/usr/bin/python import sys from StringIO import StringIO real_stdout = sys.stdout sys.stdout = StringIO() from knxmonitor import knxmonitor_decoder from knxmonitor.netcat import Netcat for a in sys.argv[1:]: args = [sys.argv[0], "-j"] args.append("-i") args.append(a) groups = [("3/2/0", "temp"), ...
"""Unit tests for gwsumm.html.static """ __author__ = 'Alex Urban <<EMAIL>>' import os.path from collections import OrderedDict from gwdetchar.io.html import (CSS_FILES as GWDETCHAR_CSS_FILES, JS_FILES as GWDETCHAR_JS_FILES) from .. import static # test simple utils def test_get_c...
import argparse import sys import util from seccomp import * def test(args): f = SyscallFilter(KILL) f.add_rule_exactly(ALLOW, "read") f.add_rule_exactly(ALLOW, "write") f.add_rule_exactly(ALLOW, "close") f.add_rule_exactly(ALLOW, "rt_sigreturn") return f args = util.get_opt() ctx = test(arg...
""" ================================================================ Plot the decision surface of a decision tree on the iris dataset ================================================================ Plot the decision surface of a :ref:`decision tree <tree>` trained on pairs of features of the iris dataset. For each p...
from opencv.highgui import * from opencv.cv import * from opencv import * import os class Camera: """ Clase para trabajar con las cámaras que estén conectadas al ordenador""" def __init__(self): self.name_cameras = [] self.capture = None def check_name_cameras(self): """Funció...
# -*- coding: utf-8 -*- from django.db import models from django.core.urlresolvers import reverse from django.contrib.sites.models import Site from django.db.models.signals import post_save from django.contrib.comments.signals import comment_was_posted from django.dispatch import receiver import os import ConfigParse...
""" This contains useful functions to set up Google Cloud Platform services for use with lcproc_gcp.py. """ ############# ## LOGGING ## ############# import logging from astrobase import log_sub, log_fmt, log_date_fmt DEBUG = False if DEBUG: level = logging.DEBUG else: level = logging.INFO LOGGER = logging....
import json import os import re from . import common class Memory(object): def __init__(self, user): self.max_words = 800 self.next_symble = '....' self.max_dialogs = 3 self.user = user log_path = common.Cfg().get('local', 'mem_path') mem_name = '%s.log' % self.us...
# -*- coding: utf-8 -*- """ <DefineSource> @Date : Fri Nov 14 13:20:38 2014 \n @Author : Erwan Ledoux \n\n </DefineSource> Systemer """ #<DefineAugmentation> import ShareYourSystem as SYS BaseModuleStr="ShareYourSystem.Standards.Controllers.Shower" DecorationModuleStr="ShareYourSystem.Standards.Classors.Classer" ...
import numpy as np import audioread as ar import math import sys, time #ファイル名 wavName_hi = "../wav/02-Are You Real.wav" wavName_cd = "../wav/02-Are You Real_CD.wav" csvName_hi = "../result_hi.csv" csvName_cd = "../result_cd.csv" #取得する振幅値の数 N = 20 #参考: http://wrist.hatenablog.com/entry/2013/08/06/015240 def pcm2float...
# System documented in https://zulip.readthedocs.io/en/latest/subsystems/logging.html from typing import Any, Dict, Optional from django.conf import settings from django.http import HttpRequest, HttpResponse from django.views.decorators.csrf import csrf_exempt from django.views.decorators.http import require_POST fro...
#!/usr/bin/env python """ Script that helps setting the token of the elements in RSS. It can acquire or release the token. If the releaseToken switch is used, no matter what was the previous token, it will be set to rs_svc (RSS owns it). If not set, the token will be set to whatever username is defined on the proxy lo...
import http import json # Load API key api_key = "" with open('data/api_key.auth') as file: api_key = file.readline() def shorten_url(url): if api_key: connection = http.client.HTTPSConnection("www.googleapis.com") body = json.dumps({'longUrl': url}) headers = {'Content-Type': 'application/json'} connection...
# -*- coding: utf-8 -*- from south.utils import datetime_utils as datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Changing field 'HostMaintenance.finished_at' db.alter_column(u'mainten...
from ige import * from xml.dom.minidom import Node from IPlayer import IPlayer from ige.IDataHolder import IDataHolder import Rules, Utils from Const import * import math, time class IAIPlayer(IPlayer): typeID = T_AIPLAYER def init(self, obj): IPlayer.init(self, obj) # obj.name = u'Rebels' obj.login = '*' ...
import copy from oslo_log import log as logging from mistral.tests.unit.workbook.v2 import base from mistral import utils LOG = logging.getLogger(__name__) class ActionSpecValidation(base.WorkbookSpecValidationTestCase): def test_base_required(self): actions = {'actions': {'a1': {}}} excepti...
# -*- coding: utf-8 -*- """ lantz.ui.scan ~~~~~~~~~~~~~ A Scan frontend and Backend. Requires scan.ui :copyright: 2015 by Lantz Authors, see AUTHORS for more details. :license: BSD, see LICENSE for more details. """ import time import math from enum import IntEnum from lantz.utils.qt import QtC...
from django.contrib import auth from autotest.frontend.afe import models from south.signals import post_migrate BASIC_ADMIN = 'Basic admin' def create_admin_group(app, **kwargs): """ Create a basic admin group with permissions for managing basic autotest objects. """ print "Creatin/updating Basic...
# -*- coding: cp1252 -*- # Import a library of functions called 'pygame' import pygame import pygame.freetype import threading from math import pi class janela(threading.Thread): def __init__(self, group=None, target=None, name=None, args=(), kwargs=None, verbose=None): ''' Deriva a classe threading, ...
from weblate.trans.management.commands import WeblateCommand class Command(WeblateCommand): help = 'pushes all changes to upstream respository' def add_arguments(self, parser): super(Command, self).add_arguments(parser) parser.add_argument( '--force-commit', action='st...
# pylint: skip-file """ Transformers for Discussion-related events. """ from django.contrib.auth.models import User from django.urls import NoReverseMatch, reverse from eventtracking.processors.exceptions import EventEmissionExit from opaque_keys import InvalidKeyError from opaque_keys.edx.locator import CourseLocator ...
# -*- coding: utf-8 -*- """ Flask-Hookserver: GitHub webhooks using Flask. :copyright: (c) 2016 by Nick Frost. :license: MIT, see LICENSE for more details. """ from flask import request from functools import wraps from werkzeug.exceptions import BadRequest, Forbidden, ServiceUnavailable import hashlib import hmac imp...
from __future__ import print_function import unittest import paddle.fluid as fluid import paddle.fluid.core as core from paddle.fluid.dygraph import LSTMCell import numpy as np np.random.seed = 123 def sigmoid(x): return 1. / (1. + np.exp(-x)) def tanh(x): return 2. * sigmoid(2. * x) - 1. def non_cudnn...
from django.db import models class SimplestModel(models.Model): """ The simplest Django model you can have """ class TimeClass(models.Model): """ A model with all the time based fields """ t = models.TimeField() d = models.DateField() dt = models.DateTimeField() ...
__author__ = """Johannes Raggam <<EMAIL>>""" __docformat__ = 'plaintext' from zodict.node import Node from zope.interface import implements from activities.metamodel.interfaces import ActivitiesException from activities.metamodel.interfaces import IElement from activities.metamodel.interfaces import IAction from acti...
from sqlalchemy.exc import OperationalError from sqlalchemy.orm.exc import NoResultFound from ...util import log from ..dbsession import DBSession class KVError(Exception): pass class KeyNotFound(Exception): pass class KVStore: def __init__(self, table): self._dbsession = DBSession() self._table = table ...
from setuptools import setup, find_packages setup( name='Lektor', version='2.0.dev0', url='http://github.com/lektor/lektor/', description='A static content management system.', license='BSD', author='Armin Ronacher', author_email='<EMAIL>', packages=find_packages(), include_package...
""" Migration script to create "handler" column in job table. """ from sqlalchemy import * from sqlalchemy.orm import * from migrate import * from migrate.changeset import * import logging log = logging.getLogger( __name__ ) # Need our custom types, but don't import anything else from model from galaxy.model.custom_...
import os import time import logging from slackclient import SlackClient from duckduckpy import query import wolframalpha class Robot: def __init__(self, name='robot'): self.name = name self.slack_client = SlackClient(os.environ.get('SLACK_BOT_TOKEN')) self.bot_id = self.get_bot_id() ...