content stringlengths 4 20k |
|---|
# coding: utf-8
from django import forms
from django.utils.translation import ugettext_lazy as _
from django.db.models import Q
from django.contrib.auth.models import User
from django.contrib.admin import widgets
from django.shortcuts import get_object_or_404
from sharing.models import Lending, Profile
from library.mo... |
"""Test truncated SVD transformer."""
import numpy as np
import scipy.sparse as sp
from sklearn.decomposition import TruncatedSVD
from sklearn.utils import check_random_state
from sklearn.utils.testing import (assert_array_almost_equal, assert_equal,
assert_raises, assert_greater,
... |
# -*- coding: utf-8 -*-
__author__ = 'frank'
from PyrserPTT import PyserPtt
from mongoengine import *
import multiprocessing
import time
import hashlib
import sys
connect('admin',host='mongodb://')
boardList = []
def getNewAtricalByBorad(board,pages=2):
graber = PyserPtt.PyserPtt(board,pages)
articalList ... |
"""Tests for qutebrowser.misc.crashdialog."""
from qutebrowser.misc import crashdialog
VALID_CRASH_TEXT = """
Fatal Python error: Segmentation fault
_
Current thread 0x00007f09b538d700 (most recent call first):
File "", line 1 in testfunc
File "filename", line 88 in func
"""
VALID_CRASH_TEXT_EMPTY = """
Fatal P... |
# -*- coding: utf-8 -*-
from __future__ import with_statement
from contextlib import contextmanager
import inspect
from itertools import chain
import os
from django.conf import settings
from django.template import Lexer, TOKEN_BLOCK
from django.utils import six
from django.utils.decorators import method_decorator
from... |
from typing import List
from django import forms
from django.contrib.auth import forms as auth_forms
from django.contrib.auth import get_user_model
from django.contrib.auth.forms import AuthenticationForm
from django.contrib.auth.tokens import default_token_generator
from django.utils.encoding import force_bytes
from ... |
import smtplib
from email.message import EmailMessage
import tweepy
import authentication
CONSUMER_KEY = authentication.CONSUMER_KEY
CONSUMER_SECRET = authentication.CONSUMER_SECRET
ACCESS_TOKEN = authentication.ACCESS_KEY
ACCESS_TOKEN_SECRET = authentication.ACCESS_SECRET
SEND_EMAIL_ADDRESS = authentication.SEND_EMA... |
import os
import shutil
from lib.util.mysqlBaseTestCase import mysqlBaseTestCase
server_requirements = [[]]
servers = []
server_manager = None
test_executor = None
# we explicitly use the --no-timestamp option
# here. We will be using a generic / vanilla backup dir
backup_path = None
class basicTest(mysqlBaseTestCa... |
# This file implements a class which forms an interface to the .cdplayerrc
# file that is maintained by SGI's cdplayer program.
#
# Usage is as follows:
#
# import readcd
# r = readcd.Readcd()
# c = Cdplayer(r.gettrackinfo())
#
# Now you can use c.artist, c.title and c.track[trackno] (where trackno
# starts at 1). Whe... |
"""Convert pdb to sym for given directories"""
import errno
import glob
import optparse
import os
import Queue
import re
import subprocess
import sys
import threading
CONCURRENT_TASKS=4
SOURCE_ROOT=os.path.abspath(os.path.dirname(os.path.dirname(os.path.dirname(__file__))))
DUMP_SYMS=os.path.join(SOURCE_ROOT, 'vendo... |
from mako import exceptions, util
_cache_plugins = util.PluginLoader("mako.cache")
register_plugin = _cache_plugins.register
register_plugin("beaker", "mako.ext.beaker_cache", "BeakerCacheImpl")
class Cache(object):
"""Represents a data content cache made available to the module
space of a specific :class:`... |
"""
Support for RFXtrx sensors.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/sensor.rfxtrx/
"""
import logging
import voluptuous as vol
import homeassistant.components.rfxtrx as rfxtrx
import homeassistant.helpers.config_validation as cv
from homeass... |
from __future__ import unicode_literals
import frappe
from frappe import _
from frappe.utils import flt, cint
from erpnext.accounts.report.trial_balance.trial_balance import validate_filters
def execute(filters=None):
validate_filters(filters)
show_party_name = is_party_name_visible(filters)
columns = get_columns... |
# -*- coding: utf-8 -*-
{
'!langcode!': 'af',
'!langname!': 'Afrikaanse',
'%Y-%m-%d': '%Y-%m-%d',
'%Y-%m-%d %H:%M:%S': '%Y-%m-%d %H:%M:%S',
'%s %%{row} deleted': '%s rows deleted',
'%s %%{row} updated': '%s rows updated',
'(requires internet access)': '(vereis internet toegang)',
'(something like "it-it")': '(iets soos... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import os
from ansible.module_utils.common.file import is_executable
def get_bin_path(arg, opt_dirs=None, required=None):
'''
Find system executable in PATH. Raises ValueError if executable is not found.
Optional arg... |
import unittest
import sys
import os.path
sys.path.insert(1, os.path.abspath(os.path.join(os.path.dirname(__file__), '../lib')))
sys.path.insert(1, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
from sickbeard import common
class QualityTests(unittest.TestCase):
# TODO: repack / proper ? air-b... |
import gensim
import logging
import sys
# logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO)
def book_to_sentences(filename):
with open(filename, 'rb') as infile:
sentences = []
sentence = []
for line in infile.readlines():
clean_lin... |
"""Tests for the Incremental Update feature
:Requirement: Inc Updates
:CaseAutomation: Automated
:CaseLevel: Acceptance
:CaseComponent: Hosts-Content
:TestType: Functional
:CaseImportance: High
:Upstream: No
"""
from datetime import date, timedelta, datetime
from fauxfactory import gen_alpha
from nailgun import... |
"""Tests for python distort_image_ops."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import time
import numpy as np
from six.moves import xrange # pylint: disable=redefined-builtin
from tensorflow.contrib.image.python.ops import distort_image_ops
fr... |
"""Tests for the swig wrapper tf_optimizer."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensorflow.core.protobuf import rewriter_config_pb2
from tensorflow.python.framework import constant_op
from tensorflow.python.framework import meta_graph
fr... |
from subprocess import *
import os
system_lib = ['re', 'optparse', 'os', 'sys', 'shutil', 'warnings', 'Queue', 'osc', 'numpy', 'math', 'xml.dom', 'logging', 'random', 'ctypeasc', 'ConfigParser', 'getopt', 'ctypes', 'gzip', 'urllib', 'gtk', 'operator', 'time']
system_lib_find = ['cssutils', 'pyglet', 'encutils', 'squir... |
"""Tests for locally-connected layers."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
from tensorflow.python import keras
from tensorflow.python.framework import test_util as tf_test_util
from tensorflow.python.keras import testing_u... |
import _ast
from _ast import *
from rope.base import fscommands
def parse(source, filename='<string>'):
# NOTE: the raw string should be given to `compile` function
if isinstance(source, unicode):
source = fscommands.unicode_to_file_data(source)
if '\r' in source:
source = source.replace(... |
from sympy import (symbols, pi, Piecewise, sin, cos, sinc, Rational,
oo, fourier_series, Add)
from sympy.series.fourier import FourierSeries
from sympy.utilities.pytest import raises
x, y, z = symbols('x y z')
fo = fourier_series(x, (x, -pi, pi))
fe = fourier_series(x**2, (-pi, pi))
fp = fourier_se... |
"""Trains on embeddings using Keras."""
from absl import app
from absl import flags
import tensorflow.compat.v2 as tf
from non_semantic_speech_benchmark.eval_embedding.finetune import get_data
from non_semantic_speech_benchmark.eval_embedding.finetune import models
FLAGS = flags.FLAGS
flags.DEFINE_string('file_pat... |
import os
import sys
from trace import Trace
HEAD = 'HEAD'
R_HEADS = 'refs/heads/'
R_TAGS = 'refs/tags/'
R_PUB = 'refs/published/'
class GitRefs(object):
def __init__(self, gitdir):
self._gitdir = gitdir
self._phyref = None
self._symref = None
self._mtime = {}
@property
def all(self):
... |
import unittest2 as unittest
from social.backends.base import BaseAuth
class BrokenBackendAuth(BaseAuth):
name = 'broken'
class BrokenBackendTest(unittest.TestCase):
def setUp(self):
self.backend = BrokenBackendAuth()
def tearDown(self):
self.backend = None
def test_auth_url(self)... |
# -*- coding: utf-8 -*-
"""
werkzeug.contrib.wrappers
~~~~~~~~~~~~~~~~~~~~~~~~~
Extra wrappers or mixins contributed by the community. These wrappers can
be mixed in into request objects to add extra functionality.
Example::
from werkzeug.wrappers import Request as RequestBase
fr... |
#!/usr/bin/env python2
"""Set up an external DB on an appliance over SSH.
Appliance address and database address are required.
Database name and region are optional and default to 'vmdb_production' and 0 respectively.
Credentials are optional but default values must be set in credentials.yaml under 'database' key.
... |
from heat.engine.components import Component
from heat.engine.components import Components
from heat.tests.common import HeatTestCase
class ComponentTest(HeatTestCase):
def test_init(self):
comp = Component()
self.assertEqual(comp.type, 'OS::Heat::SoftwareConfig')
self.assertEqual(comp.pr... |
import datetime
import ipaddress
import time
import functools
import typing
SIZE_TABLE = [
("b", 1024 ** 0),
("k", 1024 ** 1),
("m", 1024 ** 2),
("g", 1024 ** 3),
("t", 1024 ** 4),
]
SIZE_UNITS = dict(SIZE_TABLE)
def pretty_size(size):
for bottom, top in zip(SIZE_TABLE, SIZE_TABLE[1:]):
... |
#! /usr/local/bin/python
import argparse
import os
import shutil
import sys
import tempfile
import git
IGNORE_PATTERNS = ('.git', ".DS_Store")
SAFE_CHARS = ["-", "_", "."]
MAX_LENGTH = 100
STUDENT = "student"
DEVELOP = "develop-"
DEVELOP_DEFAULT = "all develop branches"
DIFF_FORMAT = """
You can download a zip of... |
from .resolver import resolver
from django.utils.importlib import import_module
def __repr__(self):
return '<%s, %s, %s, %s>' % (self.alias, self.col, self.field.name,
self.field.model.__name__)
from django.db.models.sql.where import Constraint
Constraint.__repr__ = __repr__
# TODO: manipulate a copy of ... |
"""
Django admin page for bulk email models
"""
from django.contrib import admin
from bulk_email.models import CourseEmail, Optout, CourseEmailTemplate, CourseAuthorization
from bulk_email.forms import CourseEmailTemplateForm, CourseAuthorizationAdminForm
class CourseEmailAdmin(admin.ModelAdmin):
"""Admin for co... |
from django.core.exceptions import ImproperlyConfigured
from django.template import engines
from django.test import SimpleTestCase, override_settings
class TemplateStringsTests(SimpleTestCase):
@override_settings(TEMPLATES=[{
'BACKEND': 'raise.import.error',
}])
def test_backend_import_error(self... |
"""
RealAudio (.ra) parser
Author: Mike Melanson
References:
http://wiki.multimedia.cx/index.php?title=RealMedia
Samples:
http://samples.mplayerhq.hu/real/RA/
"""
from lib.hachoir_parser import Parser
from lib.hachoir_core.field import (FieldSet,
UInt8, UInt16, UInt32,
Bytes, RawBytes, String,
PascalS... |
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn import svm
train_set = pd.read_csv('../Titanic_Dataset/train.csv')
test_set = pd.read_csv('../Titanic_Dataset/test.csv')
###Data preparation
train_set["Embarked"].replace("S", "0", True)
train_set["Embarked"].replace("C", "1", True)
t... |
"""Check if any previous rules have matched."""
__all__ = [
'Any',
]
from mailman.core.i18n import _
from mailman.interfaces.rules import IRule
from zope.interface import implementer
@implementer(IRule)
class Any:
"""Look for any previous rule match."""
name = 'any'
description = _('Look for... |
from mod_pywebsocket import msgutil
def web_socket_do_extra_handshake(request):
# Exact number of headers that will fit in 256KB. Above 256KB an
# ERR_RESPONSE_HEADERS_TOO_BIG error is triggered instead.
for i in xrange(5978):
request.extra_headers.append(
('Set-Cookie', 'WK-websocket-... |
import os
from google.appengine.ext import ndb
from controllers.base_controller import LoggedInHandler
from helpers.media_helper import MediaHelper, MediaParser
from helpers.suggestions.suggestion_creator import SuggestionCreator
from models.media import Media
from models.team import Team
from template_engine impo... |
from openerp import models, fields, api, exceptions, _
class MrpWorkcenter(models.Model):
_inherit = 'mrp.workcenter'
capacity_per_cycle = fields.Float(
string='Capacity per Cycle Max.', help='Capacity per cycle maximum.')
capacity_per_cycle_min = fields.Float(
string='Capacity per Cycle ... |
"""Proxy AMI-related calls from cloud controller to objectstore service."""
import base64
import binascii
import os
import shutil
import tarfile
import tempfile
import boto.s3.connection
import eventlet
from lxml import etree
from oslo_concurrency import processutils
from oslo_config import cfg
from oslo_log import l... |
from __future__ import print_function
import os
import logging
from scrapy.utils.job import job_dir
from scrapy.utils.request import request_fingerprint
class BaseDupeFilter(object):
@classmethod
def from_settings(cls, settings):
return cls()
def request_seen(self, request):
return Fals... |
"""Implements building blocks for neural networks."""
from typing import Optional
from absl import logging
import tensorflow as tf
from deeplab2.model import utils
from deeplab2.model.layers import convolutions
from deeplab2.model.layers import squeeze_and_excite
backend = tf.keras.backend
layers = tf.keras.layers
... |
from __future__ import unicode_literals
import frappe
from frappe import _
from frappe.utils import flt
def execute(filters=None):
if not filters: filters = {}
columns = get_columns()
last_col = len(columns)
item_list = get_items(filters)
aii_account_map = get_aii_accounts()
if item_list:
item_tax, tax_accoun... |
import warnings
from django.utils import six
from django.utils.deprecation import (
DeprecationInstanceCheck, RemovedInDjango20Warning,
RemovedInDjango110Warning,
)
from . import engines
from .backends.django import DjangoTemplates
from .base import Origin
from .engine import (
_context_instance_undefined... |
{
'name': 'Google Users',
'version': '1.0',
'category': 'Tools',
'description': """
The module adds google user in res user.
========================================
""",
'author': 'OpenERP SA',
'website': 'https://www.odoo.com',
'depends': ['base_setup'],
'data': [
'google_accou... |
from copy import copy
from gi.repository import Gtk
# This component allows applying style-properties from (css-)style-providers to text-tag's.
class GtkStyleProviderToTextViewAdapter:
__styleProvider = None # Gtk.StyleProvider
__attachedTextViews = [] # list(Gtk.TextView)
__ignoreEvents = False # bool... |
import os, sys, time
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), os.path.pardir, 'common')))
import driver, scenario_common, utils, vcoptparse
op = vcoptparse.OptParser()
scenario_common.prepare_option_parser_mode_flags(op)
_, command_prefix, serve_options = scenario_common.parse_mode_flag... |
# coding: utf-8
from PyQt5.QtWidgets import (QHBoxLayout, QPushButton)
from PyQt5.QtCore import QCoreApplication
from .content import Content
class Error(Content):
def __init__(self, parent=None, button_func=None, params=None):
super().__init__(parent, 'Error', params)
if self.params.... |
from openerp import models, fields, api
class HrEmployee(models.Model):
_inherit = "hr.employee"
@api.multi
@api.depends(
"loan_ids",
"payment_schedule_ids")
def _compute_loan(self):
obj_loan = self.env["hr.loan"]
obj_schedule = self.env["hr.loan.payment.schedule"]
... |
{
'name': 'Public Budget',
'version': '0.1',
'url': 'http://launchpad.net/openerp-ccorp-addons',
'author': 'ClearCorp',
'website': 'http://clearcorp.co.cr',
'category': 'Generic Modules/Base',
'description': """ This module adds the logic for Public Budget management and it's different proce... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.shortcuts import render, redirect, get_object_or_404
from django.forms import ModelForm
from annoying.decorators import render_to
from annoying.decorators import ajax_request
from annoying.functions import get_object_or_None
from django.views.d... |
class ModuleDocFragment(object):
# Avi common documentation fragment
DOCUMENTATION = """
options:
controller:
description:
- IP address or hostname of the controller. The default value is the environment variable C(AVI_CONTROLLER).
username:
description:
- Usernam... |
from __future__ import absolute_import
from __future__ import print_function
from typing import Any
from argparse import ArgumentParser
import sys
from django.contrib.auth import authenticate, login, get_backends
from django.core.management.base import BaseCommand
from django.conf import settings
from django_auth_l... |
import zmq
from zmq.tests import BaseZMQTestCase, have_gevent, GreenTest
x = b' '
class TestPair(BaseZMQTestCase):
def test_basic(self):
s1, s2 = self.create_bound_pair(zmq.PAIR, zmq.PAIR)
msg1 = b'message1'
msg2 = self.ping_pong(s1, s2, msg1)
self.assertEqual(msg1, msg2)
... |
from __future__ import print_function, division
from sympy.ntheory import isprime
from sympy.combinatorics.permutations import Permutation, _af_invert, _af_rmul
from sympy.core.compatibility import range
rmul = Permutation.rmul
_af_new = Permutation._af_new
############################################
#
# Utilities ... |
#!/usr/bin/env python
# This is a simple script that reads in a csv file, selects a column, and then
# forms an "s-curve" graph of that column.
import argparse
import csv
import sys
def get_data(input_file, before_column, after_column):
def get_selected_csv_rows(input_file, before_column, after_column):
... |
from setuptools import Command
from distutils.errors import DistutilsOptionError
import sys
from pkg_resources import *
from pkg_resources import _namespace_packages
from unittest import TestLoader, main
class ScanningLoader(TestLoader):
def loadTestsFromModule(self, module):
"""Return a suite of all test... |
"""alexandria URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.9/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-... |
"""SCons.Tool.default
Initialization with a default tool list.
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 The SCons Foundation
#
# Permis... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from django.db.models import Prefetch
from django.core.management.base import BaseCommand
from ponyFiction.sphinx import sphinx
from ponyFiction.models import Story, Chapter, Author
class Command(BaseCommand):
help = 'Load all stories and chapters into sphinx rt ind... |
from __future__ import print_function
import glob
import os
import sys
from setuptools import setup, find_packages
from shutil import copyfile, copytree, rmtree
if sys.version_info < (2, 7):
print("Python versions prior to 2.7 are not supported for pip installed PySpark.",
file=sys.stderr)
exit(-1)
... |
# Copyright (c) 2015 Alex Meade. All Rights Reserved.
# Copyright (c) 2015 Yogesh Kshirsagar. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http... |
import os
import re
import sys
comaSplit = re.compile(",")
def printHeader():
print("""mob_db: (
// Mobs Database
//
/******************************************************************************
************* Entry structure ************************************************
***********************************... |
"""SiteCompare module for simulating keyboard input.
This module contains functions that can be used to simulate a user
pressing keys on a keyboard. Support is provided for formatted strings
including special characters to represent modifier keys like CTRL and ALT
"""
import time # for sleep
import win32a... |
"""metaMDS """
from __future__ import print_function
import os
import sys
from setuptools import setup, find_packages
#####################################
VERSION = "0.1.0"
ISRELEASED = False
if ISRELEASED:
__version__ = VERSION
else:
__version__ = VERSION + '.dev0'
#####################################
wi... |
"""SCons.Tool.gfortran
Tool-specific initialization for gfortran, the GNU Fortran 95/Fortran
2003 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, 200... |
import unittest
from ftplib import error_perm
from mock import MagicMock
from airflow.contrib.hooks.ftp_hook import FTPHook
from airflow.contrib.sensors.ftp_sensor import FTPSensor
class TestFTPSensor(unittest.TestCase):
def setUp(self):
super(TestFTPSensor, self).setUp()
self._create_hook_orig ... |
import unittest
import os
import comm
from xml.etree import ElementTree
import json
class TestCrosswalkApptoolsFunctions(unittest.TestCase):
def test_init_manifest_defaultPlatforms(self):
comm.setUp()
os.chdir(comm.XwalkPath)
comm.clear("org.xwalk.test")
os.mkdir("org.xwalk.test")... |
# -*- coding: utf-8 -*-
from openerp.osv import osv
from openerp.tools.translate import _
from openerp.addons.base.ir.ir_actions import VIEW_TYPES
from logging import getLogger
from lxml import etree
_logger = getLogger(__name__)
VIEW_TYPE = ('chart-d3', _('Chart D3'))
VIEW_TYPES.append(VIEW_TYPE)
class iruiview(os... |
# -*- coding: utf-8 -*-
"""The artifact definitions registry."""
from __future__ import unicode_literals
from artifacts import definitions
from artifacts import errors
from artifacts import source_type
class ArtifactDefinitionsRegistry(object):
"""Artifact definitions registry."""
_source_type_classes = {
... |
class ZSearch(object):
"""
Returns Z, the Fundamental Preprocessing of S. Z[i] is the length of the substring
beginning at i which is also a prefix of S. This pre-processing is done in O(n) time,
where n is the length of S.
"""
def fundamental_preprocess(self, S):
if len(S) == 0: # Han... |
import json
from libmproxy import utils
from netlib import odict
import tutils
utils.CERT_SLEEP_TIME = 0
def test_format_timestamp():
assert utils.format_timestamp(utils.timestamp())
def test_format_timestamp_with_milli():
assert utils.format_timestamp_with_milli(utils.timestamp())
def test_isBin():
... |
from django.conf import settings
from django.core import signals
from django.core.exceptions import ImproperlyConfigured
from django.db.utils import ConnectionHandler, ConnectionRouter, load_backend, DEFAULT_DB_ALIAS, \
DatabaseError, IntegrityError
from django.utils.functional import curry
... |
#!/usr/bin/env python
# Compute 10 ** exp with exp in the range [min_exponent, max_exponent] and print
# normalized (with most-significant bit equal to 1) significands in hexadecimal.
from __future__ import print_function
min_exponent = -348
max_exponent = 340
step = 8
significand_size = 64
exp_offset = 2000
class f... |
import types
import bookland
from timtools.misc.etc import isnumber
from timtools.misc import debug
from timtools.sdoc.memo import parseMemo
class ParseError(RuntimeError):
pass
"""
"""
class Writer:
def __init__(self):
self._txt = None
self._autoPara = True
def flush(self):
if... |
#!/usr/bin/env python2.7
"""settings.py: Project settings, preferences, and presets"""
__copyright__ = "Copyright 2017, Josh Wheeler"
__license__ = "GPL-3.0"
__status__ = "Development"
# radcast: radical podcast automation
# Copyright (C) 2017 Josh Wheeler
#
# This program is free software: you can redistri... |
# -*- coding: utf-8 -*-
"""
Copyright [2009-2018] EMBL-European Bioinformatics Institute
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by... |
"""Pseudo terminal utilities."""
# Bugs: No signal handling. Doesn't set slave termios and window size.
# Only tested on Linux.
# See: W. Richard Stevens. 1992. Advanced Programming in the
# UNIX Environment. Chapter 19.
from select import select
import os
import tty
__all__ = ["openpty","... |
"""
Fakes For Cells tests.
"""
from oslo_config import cfg
from nova.cells import driver
from nova.cells import manager as cells_manager
from nova.cells import state as cells_state
from nova.cells import utils as cells_utils
import nova.db
from nova.db import base
from nova import exception
from nova import objects
... |
# -*- coding: utf-8 -*-
"""
Copyright (C) 2014 Dariusz Suchojad <dsuch at zato.io>
Licensed under LGPLv3, see LICENSE.txt for terms and conditions.
"""
from __future__ import absolute_import, division, print_function, unicode_literals
# stdlib
import logging
# Zato
from zato.admin.web.forms.notif.cloud.openstack.s... |
from Orange.widgets.settings import DomainContextHandler
class SelectAttributesDomainContextHandler(DomainContextHandler):
"""Select Columns widget has context settings in a specific format.
This context handler modifies match and clone_context to account for that.
"""
def match_value(self, setting, ... |
__version__=''' $Id: grids.py 3107 2007-06-30 11:43:41Z rgbecker $ '''
from reportlab.lib import colors
from reportlab.lib.validators import isNumber, isColorOrNone, isBoolean, isListOfNumbers, OneOf, isListOfColors, isNumberOrNone
from reportlab.lib.attrmap import AttrMap, AttrMapValue
from reportlab.graphics.sh... |
import string
import sys
import os.path
from suds.client import Client
try:
# suds 0.3.8 and prior
from suds.transport.cache import FileCache
except:
# suds 0.3.9+
from suds.cache import FileCache
import suds.sudsobject
from suds.sax.element import Element
class SforceBaseClient(object):
_sforce = None
... |
import http.server
import threading
import logging
import pytest
from PyQt5.QtCore import QUrl
from PyQt5.QtNetwork import (QNetworkProxy, QNetworkProxyQuery, QHostInfo,
QHostAddress)
from qutebrowser.browser.network import pac
pytestmark = pytest.mark.usefixtures('qapp')
def _pac_com... |
from __future__ import print_function
# Time: O(n)
# Space: O(1)
# Rotate an array of n elements to the right by k steps.
#
# For example, with n = 7 and k = 3, the array [1,2,3,4,5,6,7] is rotated to [5,6,7,1,2,3,4].
#
# Note:
# Try to come up as many solutions as you can, there are at least 3 different ways to solv... |
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
class User(models.Model):
username = models.CharField(max_length=12, unique=True)
serial = models.IntegerField()
class UserSite(models.Model):
user = models.ForeignKey(User, models.CASCADE, to_field="username")
... |
import license
import gl_XML, glX_XML
import sys, getopt
class PrintGenericStubs(gl_XML.gl_print_base):
def __init__(self):
gl_XML.gl_print_base.__init__(self)
self.name = "gl_x86_asm.py (from Mesa)"
self.license = license.bsd_license_template % ( \
"""Copyright (C) 1999-2001 Brian Paul All Rights Reserved... |
from manila.api import common
class ViewBuilder(common.ViewBuilder):
"""Model a server API response as a python dictionary."""
_collection_name = 'share_networks'
_detail_version_modifiers = ["add_gateway", "add_mtu"]
def build_share_network(self, request, share_network):
"""View of a share ... |
import numpy as np
import numpy.linalg as nl
def find_peak(corr, method='gaussian'):
"""Peak detection algorithm switch
After loading the correlation window an maximum finder is invoked.
The correlation window is cut down to the necessary 9 points around the maximum.
Afterwards the maximum is checked ... |
"""Contains the classes that deal with the normal mode representation.
Copyright (C) 2013, Joshua More and Michele Ceriotti
This program 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 Li... |
"""Contains a helper context for running queue runners.
@@NestedQueueRunnerError
@@QueueRunners
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from contextlib import contextmanager
import threading
from tensorflow.python.framework import ops
from te... |
from pykickstart.base import KickstartCommand
from pykickstart.errors import KickstartValueError, formatErrorMsg
from pykickstart.options import KSOptionParser
from pykickstart.i18n import _
class F20_Eula(KickstartCommand):
"""The 'eula' kickstart command"""
def __init__(self, *args, **kwargs):
Kick... |
def hash_name(varlist, pserver_endpoints):
"""
hash variable names to several endpoints.
Args:
varlist(list): a list of Variables
Returns(dict): a map of pserver endpoint -> varname
"""
def _hash_block(block_str, total):
return hash(block_str) % total
eplist = []
for ... |
"""Manage shelves of pickled objects using bsddb database files for the
storage.
"""
#------------------------------------------------------------------------
import sys
absolute_import = (sys.version_info[0] >= 3)
if absolute_import :
# Because this syntaxis is not valid before Python 2.5
exec("fro... |
# pylint: disable=too-many-public-methods
"""Test for letsencrypt_nginx.configurator."""
import os
import shutil
import unittest
import mock
import OpenSSL
from acme import challenges
from acme import messages
from letsencrypt import achallenges
from letsencrypt import errors
from letsencrypt_nginx.tests import uti... |
from __future__ import unicode_literals, division, absolute_import
from tests import FlexGetBase
class TestManipulate(FlexGetBase):
__yaml__ = """
tasks:
test_1:
mock:
- {title: 'abc FOO'}
manipulate:
- title:
replace:
... |
"""
Linux swap file.
Documentation: Linux kernel source code, files:
- mm/swapfile.c
- include/linux/swap.h
Author: Victor Stinner
Creation date: 25 december 2006 (christmas ;-))
"""
from hachoir_parser import Parser
from hachoir_core.field import (ParserError, GenericVector,
UInt32, String,
Bytes, NullByt... |
"""
Interfaces for serializing Django objects.
Usage::
from django.core import serializers
json = serializers.serialize("json", some_queryset)
objects = list(serializers.deserialize("json", json))
To add your own serializers, use the SERIALIZATION_MODULES setting::
SERIALIZATION_MODULES = {
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.