content
stringlengths
4
20k
from django.utils.functional import SimpleLazyObject from auth_token import utils # pylint: disable=E0401 from auth_token.config import settings as auth_token_settings # pylint: disable=E0401 from auth_token.middleware import TokenAuthenticationMiddleware, get_user # pylint: disable=E0401 from auth_token.models imp...
"""defines class, that describes C++ namespace declaration""" import declaration import scopedef import algorithm class namespace_t( scopedef.scopedef_t ): """ describes C++ namespace """ def __init__( self, name='', declarations=None ): """creates class that describes C++ namespa...
from django.http import HttpResponse from django.conf import settings from django.utils.decorators import method_decorator from django.views.decorators.cache import cache_page from rest_framework import serializers from rest_framework.viewsets import ModelViewSet from olympia import amo from olympia.accounts.views im...
import params import numpy import loaddata ######################################## ## Class for building valuation tools ## ######################################## class Valuation(object): def __init__(self,db,year): return def batter_values(self): # Return a list of tuples (dbid, ...
from django.conf.urls import patterns, include, url from django.conf.urls.static import static from django.conf import settings from django.views.generic import TemplateView # Uncomment the next two lines to enable the admin: from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', url(r'^...
from __future__ import absolute_import, print_function, unicode_literals from streamparse.bolt import Bolt from extractors.extract_website import ExtractWebsite from kafka.client import KafkaClient from kafka.producer import SimpleProducer import datetime import operator import time import urllib2 import traceback impo...
""" gybote, a twitter bot.""" # begin imports, so our tears will dry upwards import time import tweepy import logging import random import datetime from config import config API_KEY = config["api_key"] API_SECRET = config["api_secret"] ACCESS_TOKEN = config["access_token"] ACCESS_SECRET = config["access_...
import os import re from . import LOGGER class IdentityTransformer(object): def __init__(self): pass def transform(self, line): return line def __str__(self): return 'identity' def __eq__(self, other): return isinstance(other, self.__class__) class ReplaceTransfor...
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import print_function from setuptools import setup import re import os import sys name = 'django-ansi2html-filter' package = 'django_ansi2html_filter' description = 'Apply ansi2html transformation in Django templates' url = 'http://www.dabapps.com' author...
import unittest import os import pyfastaq from ariba import sequence_metadata, sequence_variant modules_dir = os.path.dirname(os.path.abspath(sequence_metadata.__file__)) data_dir = os.path.join(modules_dir, 'tests', 'data') class TestSequenceMetadata(unittest.TestCase): def test_init_fails_on_bad_lines(self): ...
import os import sys import logging import openerp import base64 import xmlrpclib import openerp.netsvc as netsvc import openerp.addons.decimal_precision as dp from openerp.osv import fields, osv, expression, orm from datetime import datetime, timedelta from dateutil.relativedelta import relativedelta from openerp impo...
__author__ = """N. Cullen <<EMAIL>>""" from copy import copy import numpy as np from pyBN.classes.factor import Factor from pyBN.classes.factorization import Factorization def ve_map(bn, evidence={}, target=None, prob=False): """ Perform Max-Sum Variable Elimination over...
import argparse import os import sys import pprint import itertools import cv2 from av import open parser = argparse.ArgumentParser() parser.add_argument('-f', '--format') parser.add_argument('-n', '--frames', type=int, default=0) parser.add_argument('path', nargs='+') args = parser.parse_args() max_size = 24 * 60...
"""Utilities for identifying candidate rules.""" from language.nqg.model.induction import rule_utils from language.nqg.model.qcfg import qcfg_rule # Non-terminal with temporary index that is gauranteed to be unused in the # current rule. This should be replaced with NT_1 or NT_2 to form a valid # QCFGRule. NT_TMP = ...
import operator from tempest.api.volume import base from tempest.common import waiters from tempest import config from tempest import test CONF = config.CONF class VolumesListAdminV2TestJSON(base.BaseVolumeAdminTest): @classmethod def resource_setup(cls): super(VolumesListAdminV2TestJSON, cls).reso...
import sys from PySide2.QtCore import * from PySide2.QtWidgets import * class ListModel(QAbstractListModel): def rowCount(self, parent = QModelIndex()): return 0 app = QApplication([]) model = ListModel() v = QListView() v.setModel(model) QTimer.singleShot(0, v.close) app.exec_()
import math import random import numpy from base import EffectLayer, HeadsetResponsiveEffectLayer class FireflySwarmLayer(HeadsetResponsiveEffectLayer): """ Each tree is a firefly. When one blinks, it pulls its neighbors closer or further from blinking themselves, bringing the group into and out of sync. ...
import nanosim import numpy as np import functools import itertools _pascal_cache = {} def pascal_row(n): " Returns the nth row of Pascal's triangle using recursion. Cached to make repeated calls extremely fast." if n in _pascal_cache: return _pascal_cache[n] else: _pascal_cache[n] = _pascal(n) return ...
"""Unit tests.""" import mock import pytest from google.rpc import status_pb2 from google.cloud import videointelligence_v1 from google.cloud.videointelligence_v1 import enums from google.cloud.videointelligence_v1.proto import video_intelligence_pb2 from google.longrunning import operations_pb2 class MultiCallabl...
# -*- 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 'Scan.added' db.alter_column(u'cards_scan', 'added', se...
from nltk.classify import NaiveBayesClassifier from nltk.corpus import subjectivity from nltk.sentiment import SentimentAnalyzer from nltk.sentiment.util import * from pprint import pprint n_instances = 100 subj_docs = [(sent, 'subj') for sent in subjectivity.sents(categories='subj')[:n_instances]] obj_docs = [(sent,...
import subprocess import sys import traceback from setuptools import setup, find_packages REQUIRED_PACKAGES = ['matplotlib', 'mpi4py', 'numpy', 'pandas', 'scikit-learn', 'scipy', 'six'] modality_data = ['data/gammaval.pkl'] if 'install' in sys.argv or 'develop' in sys.argv: try: sub...
# Based on Rapptz's RoboDanny's repl cog import contextlib import inspect import logging import re import sys import textwrap import traceback from io import StringIO from typing import * from typing import Pattern import discord from discord.ext import commands # i took this from somewhere and i cant remember where ...
#!/usr/bin/env python # vim: set fileencoding=utf-8 : # Andre Anjos <<EMAIL>> # Thu 20 Mar 2014 12:43:48 CET """Tests for scripts """ import os import sys import nose.tools def test_new_version(): # Tests the bin/bob_new_version.py script from bob.extension.scripts import new_version # keep the nose tests qu...
from libvirt import libvirtError from libvirttestapi.src import sharedmod from libvirttestapi.utils import utils required_params = ('guestname',) optional_params = {} USER = "root" PASSWD = "redhat" NMI_INFO = "NMI received for unknown reason" def check_rsyslog(ip, logger): cmd = "rpm -qa | grep rsyslog" r...
""" Exception related utilities. """ import logging import sys import time import traceback import six from brick.openstack.common.gettextutils import _LE class save_and_reraise_exception(object): """Save current exception, run some code and then re-raise. In some cases the exception cont...
"""Set of tasks for classification.""" def classify_paper(obj, eng, callback, data, taxonomy, rebuild_cache=False, no_cache=False, output_limit=20, spires=False, match_mode='full', with_author_keywords=False, extract_acronyms=False, only_core...
"""This module contains the PollAnswerHandler class.""" from telegram import Update from .handler import Handler from .utils.types import CCT class PollAnswerHandler(Handler[Update, CCT]): """Handler class to handle Telegram updates that contain a poll answer. Note: :attr:`pass_user_data` and :att...
import numpy as np import pandas as pd import scipy import skbio def simulate_ttest_1(mu_lim, sigma_lim, count_lim=100): """Simulates data for a one sample t test compared to 0. Parameters ---------- mu_lim : list, float The limits for selecting a mean sigma_lim : list, float The ...
# -*- coding: utf-8 -*- from __future__ import unicode_literals, absolute_import, with_statement from contextlib import contextmanager import smtplib from email.mime.text import MIMEText from tranny.app import config from tranny import plugin from tranny.events import EventHandler, EVENT_NOTIFICATION _config_key = 'no...
""" 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 ...
from nssrc.com.citrix.netscaler.nitro.resource.base.base_resource import base_resource from nssrc.com.citrix.netscaler.nitro.resource.base.base_resource import base_response from nssrc.com.citrix.netscaler.nitro.service.options import options from nssrc.com.citrix.netscaler.nitro.exception.nitro_exception import nitro_...
""" @file test_color_isl29125.py """ ## # @addtogroup soletta sensor # @brief This is sensor test based on soletta app # @brief test sensor isl29125 on Galileo/MinnowMax ## import os import time from oeqa.utils.helper import shell_cmd from oeqa.oetest import oeRuntimeTest from oeqa.runtime.sensor.EnvirSetup import Env...
# -*- coding: utf-8 -*- """ Copyright 2008 Serge Matveenko This file is part of PyStarDict. PyStarDict 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 lat...
from __future__ import absolute_import import sys import os import unittest sys.path.insert(0, os.path.realpath('%s/../lib' % os.path.dirname(os.path.realpath(__file__)))) # application libraries PLUGIN_PATH = os.path.join(os.path.dirname(os.path.realpath(__file__)), '..', 'lib', 'plugins') PLUGINS_TESTS_PATH = os.p...
import analysis as an import backtester as bt import exchange_API as API import portfolio as pf import database as db import logging def strategy_update(df, index, strategy): """ Updates the primary dataframe with buy/sell orders and the instrument quantities to exchange. Parameters ----------...
from autopilotlib.instructions.instruction import Instruction from autopilotlib.app.logger import Logger from autopilotlib.app.exceptions import NotFoundException from autopilotlib.app.decorators import Overrides class HideFrameInstruction(Instruction): """ 0 1 2 3 4 command ob...
from datetime import timedelta, date from hscommon.trans import trget, tr from hscommon.gui.column import Column from ..model.account import AccountType from ..model.amount import convert_amount from ..model.date import DateRange from .report import Report, get_delta_perc trcol = trget('columns') class BalanceSheet(...
from nova import db from nova import exception from nova import objects from nova.objects import base from nova.objects import fields from nova.openstack.common import uuidutils from nova import utils class InstanceGroup(base.NovaPersistentObject, base.NovaObject): # Version 1.0: Initial version # Version 1.1...
from flask_wtf import Form from wtforms import StringField, PasswordField from wtforms.validators import DataRequired, ValidationError, EqualTo from app.users.models import User from app import db def validate_login(form, field): user = form.get_user() if user is None: raise ValidationError('Invalid ...
""" Copyright (c) 2015 Red Hat, Inc All rights reserved. This software may be modified and distributed under the terms of the BSD license. See the LICENSE file for details. """ from email.mime.text import MIMEText import smtplib import socket try: from urlparse import urljoin except ImportError: from urllib.p...
""" Models for environments. """ import itertools from collections import defaultdict from django.db import models from ..mtmodel import MTModel class Profile(MTModel): """ A set of Environments for a type of product. For instance, a "browser testing" Profile might be a set of environments releva...
import sys import os from distutils.core import setup from distutils.extension import Extension from Cython.Distutils import build_ext ext_modules = [] libraries = [] library_dirs = ['./alure/build', './lib/'] include_dirs = ['./alure/include', os.getcwd()] extra_link_args = [] if sys.platform == 'win32': libra...
import redis import json import base64 import time class AlarmQueue(object): def __init__(self,redis_handle, time_history_queue = "QUEUES:IRRIGATION:TIME_HISTORY", event_hash = "QUEUES:IRRIGAITION:EVENTS", history = 120, bypass_queue = "QUEUES:IRRIGATION:BYPASS_EVENTS...
import sys, os, string, time, commands, re, pickle, StringIO, popen2, commands, pdb, zipfile, tempfile import scons_utils class idSetup( scons_utils.idSetupBase ): # do not alter the sources, specially with strip and brandelfing def BuildSetup( self, target = None, source = None, env = None ): brandelf_path = so...
from django.utils.translation import ugettext_lazy as _ from django.contrib import admin from modeltranslation.admin import TranslationAdmin from fnpdjango.actions import export_as_csv_action from .models import Offer, Perk, Funding, Spent class OfferAdmin(TranslationAdmin): model = Offer list_display = ['tit...
from __future__ import absolute_import from __future__ import division from __future__ import print_function from tempfile import mkstemp import numpy as np import tensorflow as tf # pylint: disable=g-bad-import-order from official.resnet import cifar10_main from official.utils.testing import integration tf.loggin...
from simple_es.identifier.identifies import Identifies from simple_es.utils import camelize class DomainEvent(): """ Base class for all domain driven events TODO: Split logic around saving to a data store into a separate class TODO: Restrict the ability to toggle recorded """ event_type = Non...
from __future__ import print_function import os import sys import unittest import codecs import gc import re from collections import defaultdict from fuzzywuzzy import fuzz from Levenshtein import distance from bs4 import BeautifulSoup import html2text from readability.readability import Document from goose impor...
#!/usr/bin/env python from collections import Mapping import logging import logging.config import os import ConfigParser from openphoto import Client __all__ = ["Config"] log = logging.getLogger(__name__) DEFAULT_CONFIG_PATH = os.path.join(os.path.expanduser("~"), ".config", "openp...
# # -*- coding: utf-8 # from django.template import Node, NodeList, Template, Context, Variable, Library, TemplateSyntaxError, TemplateDoesNotExist from django.conf import settings from os.path import abspath register = Library() MY_ALLOWED_INCLUDE_ROOTS = ( abspath(settings.ARCHIVE_DIR),) def include_is_allowed(f...
""" This example illustrates how to export a Mealy Machine to Matlab/Simulink/Stateflow (see the very last line). For detailed comments on the example itself, please see examples/robot_planning/discrete.py """ from tulip import transys, spec, synth # import file that contains to_stateflow import sys sys.path.append('...
# -*- coding: utf-8 -*- from setuptools import setup, find_packages, Extension import os import sys __version__ = None #placeholder, will be filled by exec with open('estnltk/__about__.py', 'r') as about_file: exec(about_file.read()) assert __version__ is not None, 'Reading version number from file failed' os.env...
from celery import states from django.conf import settings from django.contrib.contenttypes.fields import GenericForeignKey from django.contrib.contenttypes.models import ContentType from django.contrib.postgres.fields import JSONField from django.db import models, transaction from django.db.models.expressions import F...
#!/usr/bin/python3 # -*- coding: UTF-8 -*- # inspired by https://gist.github.com/netmaniac/a6414149a5a09ba1ebf702ff8d5056c5 import serial, time, struct, array from datetime import datetime ser = serial.Serial() ser.port = "COM5" # Set this to your serial port ser.baudrate = 9600 ser.open() ser.flushInput() def rea...
__author__ = 'tonycastronova' import re from shapely.geometry import * def build_catchments(inp): geoms = {} lines = None with open(inp,'r') as f: lines = f.readlines() # first read all the node coordinates nodes = {} node_order = [] cidx = find(lines, lambda x: 'Polygons' in x)...
# -*- coding: utf-8 -*- import numpy as np import matplotlib.mlab as mlab import matplotlib.pyplot as plt from colors import getRandomColors Htai = { u'恒生ETF': 15150, u'华宝油气': 5280, u'50ETF': 3486.6, u'广发医药': 2911.8, u'创业ETF': 1381.8, u'万家强债': 981, u'cash': 11065.7 + 1039.1, } Ttjj = { ...
""" Utility Mixins for unit tests """ import json import sys import six from django.conf import settings from django.test import TestCase from django.urls import clear_url_caches, resolve from mock import patch from util.db import OuterAtomic if six.PY3: from importlib import reload class UrlResetMixin(objec...
from PyQt4.uic import loadUi from PyQt4.QtCore import Qt from PyQt4.QtGui import QWidget from rexploit.lib.misc.parse import Parse from os.path import join, dirname class Widget(QWidget): def __init__(self, name, parent): super(Widget, self).__init__(parent) ui = join(dirname(__file__.split('rexpl...
from st2common.models.db.marker import DumperMarkerDB from st2common.persistence.marker import DumperMarker from st2common.exceptions.db import StackStormDBObjectNotFoundError from st2common.util import date as date_utils from st2tests import DbTestCase class DumperMarkerModelTest(DbTestCase): def test_dumper_ma...
import os import pytest import pandas as pd from ..data import (limit_rows, MaxRowsError, sample, pipe, to_values, to_json, to_csv) def _create_dataframe(N): data = pd.DataFrame({"x": range(N), "y": range(N)}) return data def _create_data_with_values(N): data = {'values': [{'x': i...
from __future__ import absolute_import, division, print_function from tornado import gen from tornado.ioloop import IOLoop from tornado.log import app_log from tornado.stack_context import (StackContext, wrap, NullContext, StackContextInconsistentError, ExceptionStackContext, run_wit...
try: from collections import OrderedDict except Exception: # python 2.6 or earlier use backport from ordereddict import OrderedDict from fuelmenu.common.modulehelper import ModuleHelper from fuelmenu.common import pwgen from fuelmenu.settings import Settings import logging import urwid import urwid.raw_disp...
from functools import reduce from operator import add from fca.context import Context from fuzzy.fca.fuzzy_context import FuzzyContext ## Search result -> context def getContextFromSR(documents, terms, relation, maxKeywords): keywords = [x['keywords'][:maxKeywords] for x in documents] keywords = [[y[0] for y in x] ...
""" Tools for binarizing scores """ import numpy as np from sklearn_evaluation import validate @validate.argument_is_proportion('top_proportion') def cutoff_score_at_top_proportion(y_score, top_proportion): """ Sort scores and get the score at """ # Sort scores in descending order scores_sorted =...
"""Blogger to Objectapp command module Based on Elijah Rutschman's code""" import sys from getpass import getpass from datetime import datetime from optparse import make_option from django.utils.encoding import smart_str from django.contrib.sites.models import Site from django.contrib.auth.models import User from djan...
# -*- coding: utf-8 -*- """Constants used in the test suite. """ SORTED_COUNTRIES = [ (u"AF", u"Afghanistan"), (u"AX", u"\xc5land Islands"), (u"AL", u"Albania"), (u"DZ", u"Algeria"), (u"AS", u"American Samoa"), (u"AD", u"Andorra"), (u"AO", u"Angola"), (u"AI", u"Anguilla"), (u"AQ", u"...
from datetime import datetime from multiprocessing import Process from uuid import uuid4 import time from collections import OrderedDict import logging import functools import zmq from zmq.eventloop.ioloop import IOLoop, PeriodicCallback from zmq.utils import jsonapi from .socket_configs import DeferredSocket, SockCo...
import json import pytest from saleor.order import OrderStatus from saleor.webhook.event_types import WebhookEventType from saleor.webhook.payloads import ( generate_customer_payload, generate_order_payload, generate_product_payload, generate_sample_payload, ) @pytest.mark.parametrize( "event_na...
import configargparse from typing import Any, Iterable, Union, Sequence, cast from gopythongo.utils import highlight class VersionParserHelpAction(configargparse.Action): def __init__(self, option_strings: Sequence[str], dest: str, default: Any=None, ...
import collections import datetime import random import re from dashie_sampler import DashieSampler import requests class BuiltJenkinsSampler(DashieSampler): JOBS_KEY = ['name'] STATUS_KEY = ['color'] #AUTHOR_KEY_MAP={ 'Joseph Partridge': 'Joeseph Partridge',} #AUTHOR_KEY=['lastBuild', 'changeSet',...
#!/usr/bin/python -u from bottle import * import os import socket import time import yaml class Layer(object): def __init__(self, layer): self.layer = layer self.images = [] with open("layers/%s/config.yml" % self.layer) as configf: self.yaml = yaml.load(configf.read()) cla...
import random import sys from io import BytesIO import gzip import struct import mxnet as mx from mxnet import nd from mxnet.gluon import nn from mxnet import gluon import numpy as np import cv2 def read_data(label_url, image_url): with gzip.open(label_url) as flbl: magic, num = struct.unpack(">II", flbl.r...
import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data import numpy as np import matplotlib.pyplot as plt import matplotlib.gridspec as gridspec import os mb_size = 32 X_dim = 784 z_dim = 64 h_dim = 128 lr = 1e-3 d_steps = 3 mnist = input_data.read_data_sets('../../MNIST_data', one_hot=Tr...
#!/usr/bin/env python """The mirrors module defines classes and methods for Ubuntu archive mirrors. Provides latency testing and mirror attribute getting from Launchpad.""" from sys import stderr from socket import (socket, AF_INET, SOCK_STREAM, gethostbyname, error, timeout, gaierror) from tim...
import time from module import Module from math import * class Calc(Module): def __init__(self, room): self.room = room def calc(self, expression): try: #make a list of safe functions safe_list = ['math','acos', 'asin', 'atan', 'atan2', 'ceil', 'cos', 'cosh', 'degrees', 'e', 'exp', 'fabs', 'floor', 'fmod'...
#!/usr/bin/env python """ Use cookiecutter to create a new XBlock project. """ import os import textwrap from cookiecutter.main import cookiecutter EXPLANATION = """\ This script will create a new XBlock project. You will be prompted for two pieces of information: * short_name: a single word, all lower-case, for ...
# -*- coding: utf-8 -*- from django.db import models, migrations import datetime class Migration(migrations.Migration): dependencies = [ ('rules', '0013_auto_20141229_1527'), ] operations = [ migrations.AlterField( model_name='category', name='created_date', ...
"""NDG XACML ElementTree Policy Reader NERC DataGrid """ __author__ = "P J Kershaw" __date__ = "16/03/10" __copyright__ = "(C) 2010 Science and Technology Facilities Council" __contact__ = "<EMAIL>" __license__ = "BSD - see LICENSE file in top-level directory" __contact__ = "<EMAIL>" __revision__ = "$Id$" from ndg.x...
"""Steadily report the status of this machine to the M&C database. Some M&C information needs to be averaged over long-ish time scales, and it's easiest to provide it by having a long-lived standalone program that's in charge of reporting. """ import os import socket import sys import time from builtins import int fr...
#!/usr/bin/python # -*- coding: utf-8 -*- import redis import csv import argparse if __name__ == '__main__': parser = argparse.ArgumentParser(description='Dump on the disk the daily informations.') parser.add_argument('-f', '--full', action="store_true", default=False, help='Do a full dump (asn, b...
"""Compare local and remote dictionaries and transfer differing files -- like rdist.""" import sys from repr import repr import FSProxy import time import os def main(): pwd = os.getcwd() s = raw_input("chdir [%s] " % pwd) if s: os.chdir(s) pwd = os.getcwd() host = ask("h...
#!/usr/bin/env python # -*- coding: utf-8 -*- """Command line tool to fix, convert, split, normalize, group, merge, deduplicate vCard and VCF files from version 2.1 to 3.0 (even large ones).""" import argparse import logging from sys import stderr, exit as sysexit from os import makedirs from os.path import exists, is...
import pytest import datetime from pytest_mock import mocker from emburse.client import Statement from emburse.errors import EmburseTypeError, EmburseValueError def test_statement_export_requires_account_id(): statement = Statement(auth_token='Test123') with pytest.raises(EmburseValueError): statemen...
from rpython.rlib import jit from rpython.rlib.rarithmetic import ovfcheck from rpython.rlib.rstruct.nativefmttable import native_is_bigendian from topaz.utils.packing.floatpacking import make_float_packer from topaz.utils.packing.intpacking import make_int_packer from topaz.utils.packing.stringpacking import make_str...
''' Created on 2016年1月12日 @author: Darren ''' #encoding:UTF-8 import time import urllib.request import re from collections import deque def crawlerData(url): urlop = urllib.request.urlopen(url) if 'html' not in urlop.getheader('Content-Type'): print("not html") return # 避免程序异常中止, 用tr...
""" This library contails the Utile-class for SmartHomeNG. New helper-functions are going to be implemented in this library. """ import logging import re import hashlib import ipaddress import socket logger = logging.getLogger(__name__) TIMEFRAME_REGEX = re.compile(r'^(\d+)([ihdwmy]?)$', re.VERBOSE | re.IGNORECAS...
'''socket_options.py''' from collections import namedtuple from heron.common.src.python.utils.log import Log import heron.common.src.python.system_constants as const from heron.common.src.python.config import system_config SocketOptions = namedtuple('Options', 'nw_write_batch_size_bytes, nw_write_batch_time_ms, ' ...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('browser', '0009_auto_20150321_1921'), ] operations = [ migrations.AlterField( model_name='rlibrary', ...
# -*- coding: utf-8 -*- from fixture import SubManFixture from subscription_manager.overrides import Overrides, Override class OverrideTests(SubManFixture): def setUp(self): SubManFixture.setUp(self) self.overrides = Overrides() def test_add_function(self): repos = ['x', 'y'] ...
# -*- coding: utf-8 -*- """Streaming, truncating, non-recursive version of :func:`repr`. Differences from regular :func:`repr`: - Sets are represented the Python 3 way: ``{1, 2}`` vs ``set([1, 2])``. - Unicode strings does not have the ``u'`` prefix, even on Python 2. - Empty set formatted as ``set()`` (Python 3), no...
from numpy import zeros, where from dopamine.tools.history import History def abstractMethod(): """ This should be called when an abstract method is called that should have been implemented by a subclass. It should not be called in situations where no implementation (i.e. a 'pass' behavior) is acceptable....
# coding=utf-8 """ This is the custom functions for twitter mirrors(PC/mobile) please copy it to YOUR_EWM_FOLDER/custom_func.py Without this file, twitter mirror won't work normally """ import re from zmirror.zmirror import add_ssrf_allowed_domain, get_group, \ force_https_domains, my_host_scheme, my_host_name, en...
import re from reportlab.lib import colors allcols = colors.getAllNamedColors() regex_t = re.compile('\(([0-9\.]*),([0-9\.]*),([0-9\.]*)\)') regex_h = re.compile('#([0-9a-zA-Z][0-9a-zA-Z])([0-9a-zA-Z][0-9a-zA-Z])([0-9a-zA-Z][0-9a-zA-Z])') def get(col_str): global allcols if col_str in list(allcols.keys())...
# -*- coding: utf-8 -*- import pytest import datetime as dt from django.contrib.sessions.middleware import SessionMiddleware from django.core.exceptions import PermissionDenied from django.urls import resolve from django.urls import reverse from django.test import RequestFactory from django.views.generic import Templ...
import re # Function used for getting zypper version def zypper_version(module): """Return (rc, message) tuple""" cmd = ['/usr/bin/zypper', '-V'] rc, stdout, stderr = module.run_command(cmd, check_rc=False) if rc == 0: return rc, stdout else: return rc, stderr # Function used for g...
from PyQt5.QtSvg import QGraphicsSvgItem, QSvgRenderer from PyQt5.QtWidgets import QGraphicsScene, QWidget from tribler_gui.utilities import get_image_path class LoadingPage(QWidget): """ This page is presented when Tribler is starting. """ def __init__(self): QWidget.__init__(self) ...
import datetime import os import httplib2 import unittest2 from gcloud import _helpers from gcloud._helpers import UTC from gcloud import datastore from gcloud.datastore.helpers import GeoPoint from gcloud.environment_vars import GCD_DATASET from gcloud.environment_vars import TESTS_PROJECT from gcloud.exceptions imp...
# -*- coding: utf-8 -*- import datetime import re import urlparse import scrapy from scrapy.exceptions import CloseSpider from .base import BaseSpider from ..items import Link, Loader FG_URLS = [ 'http://www.fangraphs.com/blogs/', 'http://www.fangraphs.com/community/', 'http://www.fangraphs.com/plus/',...
''' DIRACAccountingCommand The DIRACAccountingCommand class is a command class to interrogate the DIRAC Accounting. ''' from __future__ import absolute_import from __future__ import division from __future__ import print_function # FIXME: NOT Usable ATM # missing doNew, doCache, doMaster __RCSID__ = '$Id$' from...