content stringlengths 4 20k |
|---|
"""
Tests for twisted.enterprise reflectors.
"""
import random
from twisted.internet import reactor, interfaces, defer
from twisted.enterprise.row import RowObject
from twisted.enterprise.reflector import EQUAL
from twisted.enterprise.sqlreflector import SQLReflector
from twisted.enterprise import util
from twisted.t... |
from numpy import *
def unroll_params(arr, d, len_voc, deep=1):
mat_size = d * d
ind = 0
params = []
for i in range(0, deep):
params.append(arr[ind : ind + mat_size].reshape( (d, d) ))
ind += mat_size
params.append(arr[ind : ind + d].reshape( (d, 1) ))
ind ... |
microcode = '''
def macroop UCOMISS_XMM_XMM {
mcmpf2rf xmml, xmmlm, size=4
};
def macroop UCOMISS_XMM_M {
ldfp ufp1, seg, sib, disp, dataSize=8
mcmpf2rf xmml, ufp1, size=4
};
def macroop UCOMISS_XMM_P {
rdip t7
ldfp ufp1, seg, riprel, disp, dataSize=8
mcmpf2rf xmml, ufp1, size=4
};
def macroo... |
from datetime import datetime, tzinfo
try:
import pytz
except ImportError:
pytz = None
from django.template import Node
from django.template import TemplateSyntaxError, Library
from django.utils import six
from django.utils import timezone
register = Library()
# HACK: datetime is an old-style class, create... |
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
import traceback
try:
import ovirtsdk4 as sdk
except ImportError:
pass
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.ovirt import check_... |
"""
Various bayesian regression
"""
from __future__ import print_function
# Authors: V. Michel, F. Pedregosa, A. Gramfort
# License: BSD 3 clause
from math import log
import numpy as np
from scipy import linalg
from scipy.linalg import pinvh
from .base import LinearModel
from ..base import RegressorMixin
from ..util... |
#!/usr/bin/env python
# coding=utf-8
import sys
import os
from glob import glob
import platform
def running_under_virtualenv():
if hasattr(sys, 'real_prefix'):
return True
elif sys.prefix != getattr(sys, "base_prefix", sys.prefix):
return True
if os.getenv('VIRTUAL_ENV', False):
r... |
from absl import app
from iree.tf.support import tf_test_utils
import numpy as np
import tensorflow.compat.v2 as tf
class FillModule(tf.Module):
def __init__(self):
pass
@tf.function(input_signature=[
tf.TensorSpec([2], tf.int32),
tf.TensorSpec([], tf.float32)
])
def fill(self, dims, value):... |
"""Middleware for embargoing site and courses.
IMPORTANT NOTE: This code WILL NOT WORK if you have a misconfigured proxy
server. If you are configuring embargo functionality, or if you are
experiencing mysterious problems with embargoing, please check that your
reverse proxy is setting any of the well known client IP... |
'''
Copyright (c) Microsoft Open Technologies, Inc. All rights reserved.
The MIT License (MIT)
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 limitati... |
#!/usr/bin/env python
execfile('scripts/make_docs.py')
execfile('scripts/pack.py')
import os
import sys
import glob
import zipfile
import re
def json_encode(o, indent=0):
if isinstance(o, dict):
if len(o) == 0:
yield '{}'
else:
yield '{\n'
first = True
... |
import warnings
from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union
from google.api_core import gapic_v1 # type: ignore
from google.api_core import grpc_helpers_async # type: ignore
from google.auth import credentials as ga_credentials # type: ignore
from google.auth.transport.grpc import... |
__revision__ = "$Id$"
import sys
if sys.version_info[0] is 2 and sys.version_info[1] is 1:
from Crypto.Util.py21compat import *
from Crypto.Util.py3compat import *
import struct
from Crypto.Util.number import ceil_shift, exact_log2, exact_div
from Crypto.Util import Counter
from Crypto.Cipher import AES
import... |
# -*- coding: utf-8 -*-
import collections
import json
import re
from abc import ABCMeta, abstractmethod
from six import add_metaclass, string_types as basestring, iteritems
SPLIT_REGEX = r"(?<!\\)(\.)"
def is_dotted_key(key):
"""Returns True if the key has any not-escaped dot inside"""
return len(re.fin... |
import os
import unittest
from telemetry import value
from telemetry.page import page_set
from telemetry.value import list_of_scalar_values
from telemetry.value import none_values
class TestBase(unittest.TestCase):
def setUp(self):
self.page_set = page_set.PageSet(file_path=os.path.dirname(__file__))
self.... |
"""
qvality must be on the $PATH.
run on a file with pvalues in column 4:
$ python qvality.py --column 4 input.bed > output.bed
output file will have extra columns for PEP (posterior error prob)
and q-value.
if input.bed has a header, it is retained.
TODO: handle null via --null [column_number]
"""
from __future... |
"""
Example that sends a single message and exits using the simple interface.
You can use `simple_receive.py` (or `complete_receive.py`) to receive the
message sent.
"""
import eventlet
from kombu import BrokerConnection
eventlet.monkey_patch()
def send_many(n):
#: Create connection
#: If hostname, user... |
from ansible.compat.tests import unittest
from ansible.compat.tests.mock import Mock
from ansible.module_utils.netscaler import ConfigProxy, get_immutables_intersection, ensure_feature_is_enabled, log, loglines
class TestNetscalerConfigProxy(unittest.TestCase):
def test_values_copied_to_actual(self):
a... |
"""Defines SQLAlchemy's system of class instrumentation.
This module is usually not directly visible to user applications, but
defines a large part of the ORM's interactivity.
instrumentation.py deals with registration of end-user classes
for state tracking. It interacts closely with state.py
and attributes.py whic... |
import webob
from nova import compute
from nova import db
from nova import exception
from nova.objects import instance as instance_obj
from nova.openstack.common import jsonutils
from nova import test
from nova.tests.api.openstack import fakes
from nova.tests import fake_instance
UUID1 = '00000000-0000-0000-0000-0000... |
import pywikibot
import pywikibot.pagegenerators as pagegenerators
import re
def main():
site = pywikibot.Site('15mpedia', '15mpedia')
catnames = [
'Categoría:Personas fusiladas por el franquismo',
'Categoría:Víctimas del nazismo',
]
start = ''
for catname in catnames:
... |
import re, string
##
# File handler for GIMP's palette format.
class GimpPaletteFile:
rawmode = "RGB"
def __init__(self, fp):
self.palette = map(lambda i: chr(i)*3, range(256))
if fp.readline()[:12] != "GIMP Palette":
raise SyntaxError, "not a GIMP palette file"
... |
"""Testing for the boost module (sklearn.ensemble.boost)."""
import numpy as np
from sklearn.utils.testing import assert_almost_equal
from sklearn.utils.testing import assert_equal
from sklearn.linear_model import LogisticRegression
from sklearn.naive_bayes import GaussianNB
from sklearn.ensemble import RandomForestCl... |
import sys
import os
VERSION_FILENAME = 'CORE_VERSION'
CORE_NOT_COMPATIBLE_MESSAGE = (
'ycmd can\'t run: ycm_core lib too old, PLEASE RECOMPILE'
)
def DirectoryOfThisScript():
return os.path.dirname( os.path.abspath( __file__ ) )
def SetUpPythonPath():
sys.path.insert( 0, os.path.join( DirectoryOfThisScript(... |
"""
################################################################################
#
# SOAPpy - Cayce Ullman (<EMAIL>)
# Brian Matthews (<EMAIL>)
# Gregory Warnes (<EMAIL>)
# Christopher Blunck (<EMAIL>)
#
#######################################################################... |
""" addons.xml generator """
import os
import sys
# Compatibility with 3.0, 3.1 and 3.2 not supporting u"" literals
if sys.version < '3':
import codecs
def u(x):
return codecs.unicode_escape_decode(x)[0]
else:
def u(x):
return x
class Generator:
"""
Generates a new addons.x... |
import re
import dbhelper
import time
from tande_filters import *
from ticket_daemon import *
from usermanual import *
from trac.ticket import ITicketChangeListener, Ticket
from trac.core import *
from trac.env import IEnvironmentSetupParticipant
from trac.perm import IPermissionRequestor, PermissionSystem
from webui i... |
from taiga.base.api.permissions import (TaigaResourcePermission, IsAuthenticated)
class NotifyPolicyPermission(TaigaResourcePermission):
retrieve_perms = IsAuthenticated()
create_perms = IsAuthenticated()
update_perms = IsAuthenticated()
partial_update_perms = IsAuthenticated()
destroy_perms = IsA... |
"""Module containing a preprocessor that removes the outputs from code cells"""
# Copyright (c) IPython Development Team.
# Distributed under the terms of the Modified BSD License.
import os
from textwrap import dedent
try:
from queue import Empty # Py 3
except ImportError:
from Queue import Empty # Py 2
... |
"""HMAC (Hash-based Message Authentication Code) algorithm
HMAC is a MAC defined in RFC2104_ and FIPS-198_ and constructed using
a cryptograpic hash algorithm.
It is usually named *HMAC-X*, where *X* is the hash algorithm; for
instance *HMAC-SHA1* or *HMAC-MD5*.
The strength of an HMAC depends on:
- the strength of... |
import copy
import mock
from nova.api.openstack.compute import hypervisors \
as hypervisors_v21
from nova.api.openstack.compute.legacy_v2.contrib import hypervisors \
as hypervisors_v2
from nova.api.openstack import extensions
from nova import objects
from nova import test
from nova.tests.unit.api.ope... |
import unittest
try:
from io import BytesIO
except ImportError:
from cStringIO import StringIO as BytesIO
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.common.by import By
from selenium.webdriver.support.events import EventFiringWebDriver, \
... |
import os
import re
import gcs_async
import log_parser
import kubelet_parser
import regex
import view_base
@view_base.memcache_memoize('log-file-junit://', expires=60*60*4)
def find_log_junit(build_dir, junit, log_file):
'''
Looks in build_dir for log_file in a folder that
also includes the junit file.
... |
import re
from collections import namedtuple
from time import sleep
from typing import Dict, Sequence
from azure.mgmt.containerinstance.models import (
Container, ContainerGroup, EnvironmentVariable, ResourceRequests, ResourceRequirements, VolumeMount,
)
from msrestazure.azure_exceptions import CloudError
from ai... |
from ansible.module_utils.basic import *
from ansible.module_utils.ec2 import *
try:
from boto.ec2.blockdevicemapping import BlockDeviceType, BlockDeviceMapping
import boto.ec2.autoscale
from boto.ec2.autoscale import LaunchConfiguration
from boto.exception import BotoServerError
HAS_BOTO = True
ex... |
import numpy as np
# Make sure that caffe is on the python path:
caffe_root = '../caffe/' # this file is expected to be in {caffe_root}/examples
import sys
sys.path.insert(0, caffe_root + 'python')
import caffe
test_listfile = '/scratch/16824/data/testlist_class.txt'
result_file = 'cls_results.txt'
cmat ... |
from optparse import make_option
from django.contrib.auth.models import User
from django.core.management.base import BaseCommand, CommandError
import re
class Command(BaseCommand):
option_list = BaseCommand.option_list + (
make_option('--unset',
action='store_true',
... |
import datetime
import urllib
import urlparse
from django.contrib.staticfiles.templatetags.staticfiles import static
from django.conf import settings
from django.template import defaultfilters
from django.utils.encoding import smart_str
from django.utils.html import strip_tags
from jingo import register
from jingo_mi... |
import os
from cerbero.config import Platform, Architecture, Distro
from cerbero.utils import shell, to_unixpath
from cerbero.utils import messages as m
import shutil
import re
class Build (object):
'''
Base class for build handlers
@ivar recipe: the parent recipe
@type recipe: L{cerbero.recipe.Reci... |
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
"""Provides interfaces to various commands provided by diffusion toolkit
Change directory to provide relative paths for doctests
>>> import os
>>> filepath = os.path.dirname( os.path.realpath( __f... |
#! /bin/env python
# -*- coding: utf-8 -*-
'''
YAPMG -- Yet Another PhotoMosaic Generator written in Python
'''
import Image
import ImageOps
import os
import random
import ImageStat
import cPickle as p
__author__ = "Reverland (<EMAIL>)"
def add_frame(image):
'''Add frame for image.'''
im = ImageOps.expand... |
import os
from vee.pipeline.generic import GenericBuilder
from vee.cli import style_note
from vee.subproc import call
from vee.utils import find_in_tree
from vee import log
class MakeBuilder(GenericBuilder):
factory_priority = 1000
@classmethod
def factory(cls, step, pkg):
if step not ... |
from django.utils.encoding import python_2_unicode_compatible
from ..models import models
from ..utils import gisfield_may_be_null
@python_2_unicode_compatible
class NamedModel(models.Model):
name = models.CharField(max_length=30)
objects = models.GeoManager()
class Meta:
abstract = True
... |
import os, sys
sys.path.append(os.path.realpath('scrape_rotten/'))
import json
from twisted.internet import reactor
import scrapy
from scrapy.crawler import CrawlerProcess
from scrapy.crawler import CrawlerRunner
from scrapy.utils.log import configure_logging
from scrapy.utils.project import get_project_settings
fr... |
# This scripts runs the modified Gram-Schmidt method
# for the largest dimensions: n = 256 for double,
# n = 128 for double double, and n = 80 for quad double.
from os import system
def run_maxdim():
"""
Runs the modified Gram-Schmidt method for the largest
dimensions with double (256), double double (128),... |
"""
This module handles the detection of crawlers, so that we can handle them
appropriately in other parts of the code.
"""
from config_models.models import ConfigurationModel
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
@python_2_unicode_compatible
class CrawlersConfig... |
import turtle
from random import randint
CHESSBOARD_COLORS = ['black', 'white']
SQUARE_SIDES = 4
SQUARE_SIDE_LENGTH = 15
SQUARE_ANGLE_DEGREE = 90
def draw_chessboard(rows, cols):
turtle.speed('fastest')
turtle.bgcolor('red')
color_index = randint(0, 1)
turtle.color(CHESSBOARD_COLORS[color_index])
... |
# coding=utf8
"""
Formato phylip, supportata lettura e scrittura
non ci sono controlli e si basa sul formato dato da CLC sequence viewer.
i file scritti non presenta nell'header il numero di sequenze contenute
nel file, per cui potrebbe presentare problemi nel caricamento in un altro
programma
"""
import os, re
FILE_... |
import os
import sys
# parse_qsl moved to urlparse module in v2.6
try:
from urlparse import parse_qsl
except:
from cgi import parse_qsl
import oauth2 as oauth
REQUEST_TOKEN_URL = 'https://api.twitter.com/oauth/request_token'
ACCESS_TOKEN_URL = 'https://api.twitter.com/oauth/access_token'
AUTHORIZATION_URL = 'ht... |
def gen():
i = 0
while 1:
yield i
i += 1
g = gen()
try:
g.pend_throw
except AttributeError:
print("SKIP")
raise SystemExit
# Verify that an injected exception will be raised from next().
print(next(g))
print(next(g))
g.pend_throw(ValueError())
v = None
try:
v = next(g)
excep... |
import logging
from webkitpy.common.memoized import memoized
_log = logging.getLogger(__name__)
class Attachment(object):
rollout_preamble = "ROLLOUT of r"
def __init__(self, attachment_dictionary, bug):
self._attachment_dictionary = attachment_dictionary
self._bug = bug
# FIXME: T... |
# -*- coding: utf-8 -*-
"""
werkzeug.debug.console
~~~~~~~~~~~~~~~~~~~~~~
Interactive console support.
:copyright: (c) 2014 by the Werkzeug Team, see AUTHORS for more details.
:license: BSD.
"""
import sys
import code
from types import CodeType
from werkzeug.utils import escape
from werkzeug.loca... |
"""Amazon media storage module."""
from io import BytesIO
from os.path import splitext
from urllib.parse import urlparse
import json
import logging
import time
import boto3
import bson
from botocore.client import Config
from eve.io.media import MediaStorage
from mimetypes import guess_extension
from superdesk.media.... |
import re
import os
from autotest.client.shared import error
from autotest.client import utils
from virttest import virsh
from virttest import utils_libvirtd
def run(test, params, env):
"""
Test command: virsh domxml-from-native.
Convert native guest configuration format to domain XML format.
1.Pre... |
"""TaskResult file download handler.
This module uses blobstore_handlers, which is webapp1 stuff.
No available AppEngine documentation talks about having a webapp2
equivalent for doing blobstore_handlers.BlobstoreDownloadHandler.send_blob.
This should all be converted to webapp2 when send_blob becomes available.
"""
... |
import csv
from urllib.request import Request, urlopen
import dateutil.parser
import re
from sys import argv
from bs4 import BeautifulSoup
import scrape_util
default_sale, base_url, prefix = scrape_util.get_market(argv)
report_path = 'market-reports.html'
strip_char = ';,. \n\t\xa0'
def is_number(string):
has_s... |
from PyQt4.QtCore import QObject, SIGNAL, QUrl, QIODevice, QByteArray
from PyQt4 import QtNetwork
from PyQt4.QtNetwork import QNetworkAccessManager, QNetworkRequest
from core.network.InterceptFormData import InterceptFormData
from core.network.StoreNetworkReply import StoreNetworkReply
from core.network.InMemoryCache ... |
import unittest
import nest
HAVE_SIONLIB = nest.ll_api.sli_func("statusdict/have_sionlib ::")
class TestRecordingBackends(unittest.TestCase):
def testAAAResetKernel(self):
"""Test reset of recording backend defaults.
As ResetKernel is used by many of the tests in this file to
ensure a c... |
import time
from datetime import datetime
from dateutil.relativedelta import relativedelta
from calendar import isleap
from openerp.tools.translate import _
from openerp.osv import fields, osv
import openerp.addons.decimal_precision as dp
DATETIME_FORMAT = "%Y-%m-%d"
class hr_contract(osv.osv):
"""
Employee ... |
import numpy as np
import math
class RandSampler(object):
"""
Random sampler base class, used for data augmentation
Parameters:
----------
max_trials : int
maximum trials, if exceed this number, give up anyway
max_sample : int
maximum random crop samples to be generated
"""... |
import psycopg2 as psy
import sqlalchemy
from sqlalchemy import text
from sqlalchemy.dialects.postgresql import JSON,JSONB
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.exc import ProgrammingError
from sqlalchemy.orm import (
scoped_session,
sessionmaker,
relationship,
aliase... |
from .euctwfreq import (EUCTW_CHAR_TO_FREQ_ORDER, EUCTW_TABLE_SIZE,
EUCTW_TYPICAL_DISTRIBUTION_RATIO)
from .euckrfreq import (EUCKR_CHAR_TO_FREQ_ORDER, EUCKR_TABLE_SIZE,
EUCKR_TYPICAL_DISTRIBUTION_RATIO)
from .gb2312freq import (GB2312_CHAR_TO_FREQ_ORDER, GB2312_TABLE_SIZ... |
# coding=utf-8
"""InaSAFE Wizard Step Threshold."""
from collections import OrderedDict
from functools import partial
import logging
from PyQt4.QtGui import QDoubleSpinBox, QHBoxLayout, QLabel
from qgis.core import QgsRasterBandStats
from safe.utilities.i18n import tr
from safe import messaging as m
from safe.defini... |
import MaKaC.common.filters as filters
from MaKaC.webinterface.common.contribStatusWrapper import ContribStatusList
class TypeFilterField( filters.FilterField ):
"""
"""
_id = "type"
def satisfies( self, contribution ):
"""
"""
if len(self._conf.getContribTypeList()) == len(se... |
import sys, os
import io, math, numpy
from Lod import *
from OpenGL.GL import *
from OpenGL.GLUT import *
from OpenGL.GLU import *
from PIL import Image
import logging, logging.config
class TextureManager(object):
'''Texture loading and rendering class'''
def __init__(self, lm):
logging.config.fil... |
"""SCons.Tool.aixc++
Tool-specific initialization for IBM xlC / Visual Age C++ compiler.
There normally shouldn't be any need to import this module directly.
It will usually be imported through the generic SCons.Tool.Tool()
selection method.
"""
#
# Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
def find_starting_email(apps, schema_editor): # pylint: disable-msg=unused-argument
# We can't import the Thread model directly as it may be a newer
# version than this migration expects. We use the histo... |
"""
Testing signals emitted on changing m2m relations.
"""
from django.db import models
from django.test import TestCase
from models import Part, Car, SportsCar, Person
class ManyToManySignalsTest(TestCase):
def m2m_changed_signal_receiver(self, signal, sender, **kwargs):
message = {
'instan... |
"""Reporter foundation for Coverage."""
import fnmatch, os
from coverage.codeunit import code_unit_factory
from coverage.files import prep_patterns
from coverage.misc import CoverageException, NoSource, NotPython
class Reporter(object):
"""A base class for all reporters."""
def __init__(self, coverage, confi... |
"""Tests for type_info module."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
from tensorflow.python.autograph.pyct import compiler
from tensorflow.python.autograph.pyct.testing import codegen
from tensorflow.python.platform import t... |
"""Module for depositing record metadata and uploading files."""
import os
from setuptools import find_packages, setup
readme = open('README.rst').read()
history = open('CHANGES.rst').read()
tests_require = [
'check-manifest>=0.25',
'coverage>=4.0',
'invenio-access>=1.0.0a11',
'invenio-accounts>=1.0... |
#
# $Id$
#
import sys, re
if len(sys.argv)!=3:
print 'Usage: python resolve.py BACKTRACE SYMBOLS'
sys.exit(0)
def myopen(name):
if name == '-':
return sys.stdin
fh = open(name, 'r')
if not fh:
print 'FATAL: failed to open %s' % name
sys.exit(1)
return fh
syms = []
fp = myopen(sys.argv[2])
for line in fp... |
"""Writes dependency ordered list of native libraries.
The list excludes any Android system libraries, as those are not bundled with
the APK.
This list of libraries is used for several steps of building an APK.
In the component build, the --input-libraries only needs to be the top-level
library (i.e. libcontent_shell... |
import logging
from datetime import datetime
from odoo import http, fields
from odoo.http import request
from werkzeug.exceptions import BadRequest, NotFound
from werkzeug.wrappers import Response
from werkzeug.datastructures import Headers
_logger = logging.getLogger(__name__)
class RestController(http.Controller... |
#!/usr/bin/env python3
'''
kicad-footprint-generator is free software: you can redistribute it and/or
modify it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
kicad-footprint-generator is distribut... |
from __future__ import unicode_literals
from django.contrib.gis.db.models import fields
from django.core.exceptions import ImproperlyConfigured
from django.db import connection, migrations, models
from django.db.migrations.migration import Migration
from django.db.migrations.state import ProjectState
from django.test ... |
import paramiko
from scp import SCPClient
from time import time
from robot.api import logger
__all__ = ["exec_cmd"]
# TODO: Attempt to recycle SSH connections
# TODO: load priv key
class SSH(object):
__MAX_RECV_BUF = 10*1024*1024
__existing_connections = {}
def __init__(self):
self._ssh = param... |
"""Implementation of Gaussian mixture model (GMM) clustering using tf.Learn."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import time
import numpy as np
from tensorflow.contrib import framework
from tensorflow.contrib.factorization.python.ops import ... |
bodyDefault = '''
importScripts('worker-testharness.js');
importScripts('test-helpers.sub.js');
importScripts('/common/get-host-info.sub.js');
var host_info = get_host_info();
test(function() {
var import_script_failed = false;
try {
importScripts(host_info.HTTPS_REMOTE_ORIGIN +
base_path() + 'e... |
from __future__ import unicode_literals
import webnotes
from webnotes.utils import cstr, flt
from webnotes import _
def execute(filters=None):
account_details = {}
for acc in webnotes.conn.sql("""select name, debit_or_credit, group_or_ledger
from tabAccount""", as_dict=1):
account_details.setdefault(acc.name, ... |
from monascaclient.common import monasca_manager
class NotificationsManager(monasca_manager.MonascaManager):
base_url = '/notification-methods'
def create(self, **kwargs):
"""Create a notification."""
body = self.client.create(url=self.base_url,
json=kwargs)
... |
from django.conf import settings
from django.contrib.auth import authenticate
from django.contrib.auth import login
from django.contrib.auth.models import User
from registration import signals
from registration.forms import RegistrationForm
class SimpleBackend(object):
"""
A registration backend which implem... |
import unittest
from underscore import array as _
from itertools import chain
class TestFlatten(unittest.TestCase):
def test_flat_list(self):
l = [1,2,3,4]
flat = list(_.flatten(l))
self.assertEqual(l,flat)
def test_flat_generator(self):
l = range(0, 10)
flat = _.flat... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import re
import json
from ansible.module_utils._text import to_text, to_bytes
from ansible.plugins.terminal import TerminalBase
from ansible.errors import AnsibleConnectionFailure
class TerminalModule(TerminalBase):
termin... |
# -*- coding: utf-8 -*-
"""
@organization: U{World Wide Web Consortium<http://www.w3.org>}
@author: U{Ivan Herman<a href="http://www.w3.org/People/Ivan/">}
@license: This software is available for use under the
U{W3C® SOFTWARE NOTICE AND LICENSE<href="http://www.w3.org/Consortium/Legal/2002/copyright-software-20021231"... |
"""
Verifies that app bundles are rebuilt correctly.
"""
from __future__ import print_function
import TestGyp
import sys
if sys.platform == 'darwin':
print("This test is currently disabled: https://crbug.com/483696.")
sys.exit(0)
test = TestGyp.TestGyp(formats=['ninja', 'make', 'xcode'])
CHDIR = 'rebuild'... |
from plyer.facades import Notification
import Foundation
import objc
import AppKit
class OSXNotification(Notification):
def _notify(self, **kwargs):
NSUserNotification = objc.lookUpClass('NSUserNotification')
NSUserNotificationCenter = objc.lookUpClass('NSUserNotificationCenter')
notificat... |
import re
from pylons.controllers.util import Request
from routes.util import URLGenerator
from mediadrop.config.routing import add_routes, create_mapper
from mediadrop.lib.test.db_testcase import DBTestCase
from mediadrop.lib.test.pythonic_testcase import *
from mediadrop.lib.test.request_mixin import RequestMixin
f... |
from typing import TYPE_CHECKING
import warnings
from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error
from azure.core.paging import ItemPaged
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import HttpR... |
import logging
import os
import re
from ctypes import CDLL, CFUNCTYPE, c_char_p, c_int
from ctypes.util import find_library
from django.contrib.gis.gdal.error import GDALException
from django.core.exceptions import ImproperlyConfigured
logger = logging.getLogger('django.contrib.gis')
# Custom library path set?
try:
... |
from django.conf.urls.defaults import *
from django.contrib import admin
from django.conf import settings
from common.rpc4django.utils import rpc_url
import re
admin.autodiscover()
from vt_manager_kvm.utils.ThemeManager import ThemeManager
from vt_manager_kvm.communication.southCommInterface import *
from vt_manager_... |
import sys
from collections import defaultdict
import hasher
import in_generator
import name_utilities
import template_expander
from in_file import InFile
def _symbol(tag):
# FIXME: Remove this special case for the ugly x-webkit-foo attributes.
if tag['name'].startswith('-webkit-'):
return tag['name... |
"""Drag-and-drop support for Tkinter.
This is very preliminary. I currently only support dnd *within* one
application, between different windows (or within the same window).
I an trying to make this as generic as possible -- not dependent on
the use of a particular widget or icon type, etc. I also hope that
this wi... |
from __future__ import absolute_import
from __future__ import print_function
import numpy as np
import matplotlib.pyplot as plt
from .tools import unit_normalize
from .material import Material, material_property
class AnisotropicMaterial(Material):
"""
A class that represents an anisotropic elastic material.... |
# coding: utf-8
import re
from itertools import chain
from .token import blocks_default, list_items, block_footnotes, inlines_default, inline_htmls
class Scanner(object):
'''
scanner to do the actual parsing job
'''
# default regex: parse default blocks
default_regex = blocks_default
# list_... |
from __future__ import unicode_literals
import gzip
import os
import re
from difflib import SequenceMatcher
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured, ValidationError
from django.utils import lru_cache
from django.utils._os import upath
from django.utils.encoding import ... |
'''
==================
Multicolored lines
==================
This example shows how to make a multi-colored line. In this example, the line
is colored based on its derivative.
'''
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.collections import LineCollection
from matplotlib.colors import ListedC... |
import math
from logbook import Logger
from sqlalchemy.orm import reconstructor, validates
import eos.db
from eos.const import FittingSlot
from eos.effectHandlerHelpers import HandledCharge, HandledItem
from eos.modifiedAttributeDict import ChargeAttrShortcut, ItemAttrShortcut, ModifiedAttributeDict
from eos.saveddat... |
# coding=utf-8
import os
import shutil
import unittest
from os.path import join
from conans import load
from conans.test.utils.test_files import temp_folder
from conans.util.files import mkdir, save, merge_directories
class MergeDirectoriesTest(unittest.TestCase):
def setUp(self):
self.source = temp_fol... |
'''
此程式的工作:
1. 多執行緒抓圖片url
* 如果下載中意外停止,可以先使用update_url.py
來快速清理已經下載的連結,讓下載時間縮短。
工作方式:
one thread put(file.readline)
other thread get() , parse, requests and download images
'''
import os
import queue
import threading
import time
import requests
# 設定總執行緒數
num_threads = 31
# 等待put thread 先處理一陣子,在加入 get threads,秒
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.