content stringlengths 4 20k |
|---|
from unittest import TestCase
import hangups
from nose.plugins.attrib import attr
from obs.relay.hangouts_relay import HangoutsRelay
@attr(speed='fast')
class TestHangoutsRelay(TestCase):
def test_is_not_duplicate(self):
test_not_duplicate_msg = hangups.hangouts_pb2.StateUpdate(
event_notif... |
#!/usr/bin/env python
"""Update encrypted deploy password in Travis config file."""
from __future__ import print_function
import base64
import json
import os
from getpass import getpass
import yaml
from cryptography.hazmat.primitives.serialization import load_pem_public_key
from cryptography.hazmat.backends import d... |
"""
Current-flow closeness centrality measures.
"""
# Copyright (C) 2010 by
# Aric Hagberg <<EMAIL>>
# Dan Schult <<EMAIL>>
# Pieter Swart <<EMAIL>>
# All rights reserved.
# BSD license.
__author__ = """Aric Hagberg (<EMAIL>)"""
__all__ = ['current_flow_closeness_centrality','information_centrality... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import shutil
import tensorflow as tf
from tensorflow.tensorboard.backend.event_processing import event_file_inspector as efi
class EventFileInspectorTest(tf.test.TestCase):
def setUp(self):
... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
from ansible.errors import AnsibleError
from ansible.plugins.action import ActionBase
from ansible.utils.vars import merge_hash
class ActionModule(ActionBase):
_VALID_ARGS = frozenset(('jid', 'mode'))
def run(self, tmp=... |
#!/usr/bin/python3
import urwid
import controller
import subprocess
import shortcut_manager
from widgets.FileViewer import FileViewer
from widgets.ResultsViewer import ResultsViewer
class EditBox(urwid.Filler):
signals = [ 'entered', 'canceled' ]
def set_text(self, text):
self.original_widget.set_capt... |
"""Generate a Python dict from input tags from a treebank, in str. As of this version, only treebanks following the Penn notation are supported.
"""
def set_path(dicts, keys, v):
"""Helper function for modifying nested dictionaries
:param dicts: dict: the given dictionary
:param keys: list str: path to a... |
from __future__ import absolute_import, unicode_literals
import logging
import pykka
logger = logging.getLogger(__name__)
def send_async(cls, event, **kwargs):
# This file is imported by mopidy.backends, which again is imported by all
# backend extensions. By importing modules that are not easily installab... |
#!/usr/bin/env python
#
# Wrapper script for invoking the jar.
#
# This script is written for use with the Conda package manager and is ported
# from a bash script that does the same thing, adapting the style in
# the peptide-shaker wrapper
# (https://github.com/bioconda/bioconda-recipes/blob/master/recipes/peptide-sha... |
# -*- coding: utf-8 -*-
def get_setting(name):
from django.conf import settings
from meta_mixin import settings as meta_settings
default = {
'BLOG_IMAGE_THUMBNAIL_SIZE': getattr(settings, 'BLOG_IMAGE_THUMBNAIL_SIZE', {
'size': '120x120',
'crop': True,
'upscale'... |
import smtplib
from threading import Thread
from django.conf import settings
from django.core.mail import EmailMultiAlternatives
from django.template.loader import render_to_string as render
class EmailThread(Thread):
MAX_TRIES = 3
def __init__(self, subject, text, html, to, headers):
Thread.__init_... |
import os, sys
VERSION = "2.6"
SCAN_BLOCKSIZE = 1024 * 1024 * 10
PLUGINPATH = os.path.dirname(__file__)
# If we're in a pyinstaller executable
if hasattr(sys, "frozen"):
try:
PLUGINPATH = sys._MEIPASS #pylint: disable-msg=W0212,E1101
except ImportError:
pass
PLUGINPATH = os.path.join(PLUGINP... |
import os
from ginga.qtw import ImageViewQt as ImageViewQt
from ginga.qtw.QtHelp import QtGui, QtCore, QPixmap
from ginga.misc.plugins import ThumbsBase
from ginga.qtw import QtHelp
from ginga.misc import Bunch
class MyScrollArea(QtGui.QScrollArea):
def resizeEvent(self, event):
rect = self.geometry()
... |
"""Tests for distutils.command.clean."""
import sys
import os
import unittest
import getpass
from distutils.command.clean import clean
from distutils.tests import support
from test.support import run_unittest
class cleanTestCase(support.TempdirManager,
support.LoggingSilencer,
... |
import cgt
from cgt.numeric_diff import numeric_grad, numeric_grad_multi
import numpy as np
def gradcheck_model(cost, params, extravars=(), extravals=(), atol=1e-8, eps=1e-9):
precision = cgt.get_precision()
if precision == "single":
cgt.utils.warn("You're doing a gradient check with %s precision. Use ... |
"""Matcher classes to be used inside of the testtools assertThat framework."""
import pprint
import StringIO
from lxml import etree
from testtools import content
class DictKeysMismatch(object):
def __init__(self, d1only, d2only):
self.d1only = d1only
self.d2only = d2only
def describe(self):... |
# -*- coding: utf8 -*-
import persistence
import webdict
import time
from requests.exceptions import RequestException
from multiprocessing import Pool, Process, Queue
# q为全部查询结果队列,多进程共享
q = Queue()
# 将结果集中的结果写入数据库(写进程任务)
def write_result_into_db():
while True:
if q.empty():
time.sleep(1)
... |
import os
import sys
import flask
sys.path.insert(0, os.path.realpath(os.path.join(os.path.dirname(__file__), '../../')))
from flask_debugtoolbar import DebugToolbarExtension
app = flask.Flask(__name__)
app.config.from_object(__name__)
app.config['MONGODB_SETTINGS'] = {'DB': 'testing'}
app.config['TESTING'] = True
a... |
from webob import exc
from nova.api.openstack import common
from nova.api.openstack.compute.schemas.v3 import networks_associate
from nova.api.openstack import extensions
from nova.api.openstack import wsgi
from nova.api import validation
from nova import exception
from nova.i18n import _
from nova import network
ALI... |
"""Invenio Submission Web Interface config file."""
__revision__ = "$Id$"
import re
## test:
test = "FALSE"
## CC all action confirmation mails to administrator? (0 == NO; 1 == YES)
CFG_WEBSUBMIT_COPY_MAILS_TO_ADMIN = 0
## During submission, warn user if she is going to leave the
## submission by following some li... |
''' This script is run as root by the osmc update module. '''
import apt
from datetime import datetime
import json
import os
import socket
import sys
import time
import traceback
t = datetime
def call_parent(raw_message, data={}):
address = '/var/tmp/osmc.settings.update.sockfile'
print '%s %s sending response... |
import abc
import functools
import os
from oslo_log import log as logging
from oslo_utils import importutils
import six
import webob.dec
import webob.exc
import nova.api.openstack
from nova.api.openstack import wsgi
from nova import exception
from nova.i18n import _
from nova.i18n import _LE
from nova.i18n import _LW... |
from django import template
from django.template import defaultfilters as filters
from django.utils.translation import ugettext_lazy as _
from horizon import tables
from horizon.utils import filters as utils_filters
class ServiceFilterAction(tables.FilterAction):
def filter(self, table, services, filter_string):... |
# ----------------------------------------------------------------------------
# A dictionary of dicts, with only the minimum required is_selected attribute,
# for use with examples using a simple list of integers in a list view.
integers_dict = \
{ str(i): {'text': str(i), 'is_selected': False} for i in xrange... |
import PyQt4.QtGui as qtgui
import PyQt4.QtCore as qtcore
# this class is meant to replace a Qwidget that was put into the designer
class ColorSwatch(qtgui.QWidget):
def __init__(self,master,replacingwidget=None,parent=None,swatchsize=20,color=None):
self.master=master
if color:
self.color=qtgui.QColor(color[... |
'''
Created on Aug 12, 2015
@author: sahil.singla01
'''
from validations import ViewValidations
from functionality import flight_booking
from exceptions import CustomExceptions
def search_flights():
FLAG=0
try:
source=input("Enter the source:")
ViewValidations.validate_source(... |
from sympy import sqrt
from sympy.physics.quantum.qapply import qapply
from sympy.physics.quantum.qubit import IntQubit
from sympy.physics.quantum.grover import (apply_grover, superposition_basis,
OracleGate, grover_iteration, WGate)
def return_one_on_two(qubits):
return qubits == IntQubit(2, qubits.nqubi... |
from __future__ import print_function
from gnuradio import gr, gr_unittest, uhd
class test_uhd(gr_unittest.TestCase):
def setUp(self):
self.tb = gr.top_block()
def tearDown(self):
self.tb = None
def test_000_nop (self):
"""Just see if we can import the module...
They may... |
"""Main Controller"""
import tg
from tg import expose, redirect, config, validate, override_template, response, render_template, tmpl_context
from tg import cache, i18n, request
from tg.decorators import paginate, use_custom_format, with_trailing_slash, Decoration, before_render, decode_params
from tg.controllers impor... |
# -*- encoding: utf-8 -*-
from __future__ import unicode_literals
from django.core.exceptions import ValidationError
from django.db import models
from django.utils.unittest import TestCase
class ValidationMessagesTest(TestCase):
def _test_validation_messages(self, field, value, expected):
with self.asse... |
def max_globally(test=None):
# [START max_globally]
import apache_beam as beam
with beam.Pipeline() as pipeline:
max_element = (
pipeline
| 'Create numbers' >> beam.Create([3, 4, 1, 2])
| 'Get max value' >>
beam.CombineGlobally(lambda elements: max(elements or [None]))
... |
import os
MOZ_OBJDIR = 'obj-firefox'
config = {
'default_actions': [
'clobber',
'clone-tools',
'setup-mock',
'build',
# 'generate-build-stats',
'update', # decided by query_is_nightly()
],
'stage_platform': 'linux64-debug',
'debug_build': True,
'ena... |
{
'name' : 'Authentication via LDAP',
'version' : '1.0',
'depends' : ['base'],
'images' : ['images/ldap_configuration.jpeg'],
'author' : 'OpenERP SA',
'description': """
Adds support for authentication by LDAP server.
===============================================
This module allows users to lo... |
# -*- coding: utf-8 -*-
"""
OpenScrapers Module
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 License, or
(at your option) any later version.
This p... |
"""
Created on Jun 10, 2015
@author: hsorby
"""
from mapclient.core.utils import which
from mapclient.settings.general import getVirtEnvDirectory
from mapclient.core.checks import getPySideRccExecutable
from mapclient.settings.definitions import SHOW_STEP_NAMES, \
DONT_CREATE_VIRTUAL_ENV, OPTIONS_SETTINGS_TAG, \
... |
"""Fichier décrivant la classe Race, détaillée plus bas."""
from abstraits.obase import BaseObj
from bases.collections.flags import Flags
from primaires.format.description import Description
from .stats import Stats
from .genres import Genres
class Race(BaseObj):
"""Classe définissant les races des personnages.... |
"""Fichier contenant la fonction talent."""
from fractions import Fraction
from primaires.format.fonctions import supprimer_accents
from primaires.scripting.fonction import Fonction
from primaires.scripting.instruction import ErreurExecution
class ClasseFonction(Fonction):
"""Retourne le niveau d'un talent conn... |
# -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Removing unique constraint on 'Weblocale', fields ['project', 'locale']
db.delete_unique('webby_weblocale'... |
import logging
from qkan.database.dbfunc import DBConnection
VERSION = "2.5.27"
logger = logging.getLogger("QKan.database.migrations")
def run(dbcon: DBConnection) -> bool:
# Vergleich der Flächengröße mit der Summe der verschnittenen Teile
if not dbcon.sql(
'DROP VIEW IF EXISTS "v_flaechen_check"... |
import logging
LOG = logging.getLogger(__name__)
def parse_templates(template_lines):
o = {}
for line in template_lines:
if ' = ' not in line:
continue
k, v = line.strip().split(' = ')
if not k.startswith('catalog.'):
continue
parts = k.split('.')
... |
"""The config flow tests for the forked_daapd media player platform."""
import pytest
from homeassistant import data_entry_flow
from homeassistant.components.forked_daapd.const import (
CONF_LIBRESPOT_JAVA_PORT,
CONF_MAX_PLAYLISTS,
CONF_TTS_PAUSE_TIME,
CONF_TTS_VOLUME,
DOMAIN,
)
from homeassistant.... |
"""Suppoort for Amcrest IP camera binary sensors."""
from datetime import timedelta
import logging
from amcrest import AmcrestError
from homeassistant.components.binary_sensor import (
DEVICE_CLASS_CONNECTIVITY,
DEVICE_CLASS_MOTION,
BinarySensorDevice,
)
from homeassistant.const import CONF_BINARY_SENSORS... |
"""
Settings for sampleproject project.
"""
import os
BASE_DIR = os.path.abspath(os.path.dirname(__file__))
SECRET_KEY = 'CHANGE_IT_FOR_MORE_SECURITY'
INSTALLED_APPS = (
# django apps
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'd... |
# -*- coding: utf-8 -*-
#------------------------------------------------------------
import sys
PY3 = False
if sys.version_info[0] >= 3: PY3 = True; unicode = str; unichr = chr; long = int
if PY3:
import urllib.parse as urlparse # Es muy lento en PY2. En PY3 es nativo
else:
import... |
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import unittest
class NewVisitorTest(unittest.TestCase):
def setUp(self):
self.browser = webdriver.Firefox()
def tearDown(self):
# Satisfied, she goes back to sleep
self.browser.quit()
def test_can_sta... |
import requests, re
class TrelloError(Exception):
def __init__(self, code):
self.code = code
def get_board_id(session, url):
short_board_id = re.sub("https://trello.com/b/([A-Za-z0-9]+).*", "\\1", url)
r = session.get('/1/boards/' + short_board_id)
if r.status_code != 200:
raise Trello... |
from spack import *
class Folly(AutotoolsPackage):
"""Folly (acronymed loosely after Facebook Open Source Library) is a
library of C++11 components designed with practicality and efficiency
in mind.
Folly contains a variety of core library components used extensively at
Facebook. In particular, i... |
import argparse
import shutil
import sys
import os
def prompt_user_yn(message):
ans = None
while ans not in ["y", "n"]:
print(message)
ans = input()
return ans
def create_folder(name):
if os.path.exists(name):
print("[WARNING]: Folder with name %s already exists" % name)
if prom... |
# In the event of a migration that applies to multiple TLOs, you can put
# functions here so you don't have to duplicate code across several migration
# files.
# For migrating analysis results to their own collection.
# mgoffin
# 2014-09-24
def migrate_analysis_results(self):
from crits.services.analysis_result im... |
import autocomplete_light
from models import Layer
autocomplete_light.register(
Layer,
search_fields=[
'^title',
'^typename'],
autocomplete_js_attributes={
'placeholder': 'Layer name..',
},
) |
import inspect
import logging as std_logging
import os
import random
from oslo.config import cfg
from neutron.common import config
from neutron.common import legacy
from neutron import context
from neutron.openstack.common import importutils
from neutron.openstack.common import log as logging
from neutron.openstack.c... |
from django.utils.translation import ugettext_lazy as _
from horizon import tables
from openstack_dashboard.usage import quotas
class QuotaFilterAction(tables.FilterAction):
def filter(self, table, tenants, filter_string):
q = filter_string.lower()
def comp(tenant):
if q in tenant.n... |
r"""
RENAME:
patchmatch?
CommandLine:
THEANO_FLAGS='device=gpu1'
# --- UTILITY
python -m ibeis_cnn --tf get_juction_dpath --show
# --- LIBERTY EXAMPLES ---
# Build / Ensure Liberty dataset
python -m ibeis_cnn --tf pz_patchmatch --ds liberty --ensuredat... |
# encoding: utf-8
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
from pybb.compat import get_image_field_full_name, get_user_model_path, get_user_frozen_models
AUTH_USER = get_user_model_path()
class Migration(SchemaMigration):
def forwards(self, orm):... |
import fauxfactory
import pytest
from wait_for import wait_for
from widgetastic.exceptions import RowNotFound
from cfme import test_requirements
from cfme.cloud.provider.openstack import OpenStackProvider
from cfme.configure.configuration.region_settings import ReplicationGlobalAddView
from cfme.configure.configuratio... |
from solum.objects import base
class Assembly(base.CrudMixin):
# Version 1.0: Initial version
VERSION = '1.0'
class AssemblyList(list, base.CrudListMixin):
"""List of Assemblies."""
class States(object):
PENDING = 'PENDING'
UNIT_TESTING = 'UNIT_TESTING'
UNIT_TESTING_FAILED = 'UNIT_TESTING_... |
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import absolute_import
import pytest
from tests.image_builder.distributions.centos6 import CentOSBuilder
from tests.utils.dockerized import dockerized_case
from tests.distribution.python_version_change_tests.common import (... |
import os
import datetime
exceptions = { "Bears 23Eagles 28": ((23, 28), (15 + 6 + 4 / 60.0, "TD", "Bears")),
"Bears 31Eagles 28": ((31, 28), (15 + 1 + 29 / 60.0, "TD", "Bears")),
"Giants 14Cardinals 19": ((14,19), (0 + 10 + 10 / 60.0, "TD", "Cardinals")),
"Lions 35Giants 1... |
"""
Script for removing all redundant Mac OS metadata files (with filename ".DS_Store"
or with filename which starts with "._") for all courses
"""
import logging
from django.core.management.base import BaseCommand
from xmodule.contentstore.django import contentstore
log = logging.getLogger(__name__)
class Command... |
from collections import namedtuple
from enum import Enum
import threading
from typing import (
MutableSet,
Optional,
TypeVar,
)
from lxml import etree
T = TypeVar("T", bound=type)
def get_all_subclasses(cls: T) -> MutableSet[T]:
subclasses = set(cls.__subclasses__())
return subclasses.union(
... |
import os
import public
import pickle
attributeList = [
("index", "学号"),
("name", "姓名"),
("sex", "性别"),
("birth", "出生日期"),
("major", "专业"),
("grade", "年级"),
("classname", "班级"),
]
class StudentManager(object):
"""学生管理类, 单例"""
def __init__(self, path=None):
# 用于存储所有学生对象
... |
from spack import *
from six.moves.urllib.parse import urlparse
from os.path import split
class Miniconda3(Package):
"""The minimalist bootstrap toolset for conda and Python3."""
homepage = "https://conda.io/miniconda.html"
url = "https://repo.continuum.io/miniconda/Miniconda3-4.3.11-Linux-x86_64.sh... |
from mercurial import changegroup
from mercurial.node import short
from mercurial.i18n import _
import os
import errno
def _bundle(repo, bases, heads, node, suffix, compress=True):
"""create a bundle with the specified revisions as a backup"""
cg = repo.changegroupsubset(bases, heads, 'strip')
backupdir = ... |
import os
from contextlib import contextmanager
from textwrap import dedent
from pants.backend.python.subsystems.ipython import IPython
from pants.backend.python.tasks.gather_sources import GatherSources
from pants.backend.python.tasks.python_repl import PythonRepl
from pants.backend.python.tasks.resolve_requirements ... |
#!/usr/bin/env python
"""
Copyright (c) 2006-2014 sqlmap developers (http://sqlmap.org/)
See the file 'doc/COPYING' for copying permission
"""
import logging
import sys
from lib.core.enums import CUSTOM_LOGGING
logging.addLevelName(CUSTOM_LOGGING.PAYLOAD, "PAYLOAD")
logging.addLevelName(CUSTOM_LOGGING.TRAFFIC_OUT, ... |
from openstack.message.v1 import _proxy
from openstack.message.v1 import claim
from openstack.message.v1 import message
from openstack.message.v1 import queue
from openstack.tests.unit import test_proxy_base
CLIENT_ID = '3381af92-2b9e-11e3-b191-71861300734c'
QUEUE_NAME = 'test_queue'
class TestMessageProxy(test_prox... |
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
import numpy as np
from msmbuilder.testing import eq
import scipy.sparse
from msmbuilder import MSMLib
def test_get_count_matrix_from_assignments_1():
assignments = np.zeros((10, 10),'int')
val = MS... |
#!/usr/bin/python
"""
GPS / ACCEL Logger V6
"""
import os
import sys
import threading
import time
import gps
import BaseHTTPServer
#import adxl345_shim as accel
import berryimu_shim as accel
HOST_NAME = ''
PORT_NUMBER = 80
class MyHandler(BaseHTTPServer.BaseHTTPRequestHandler):
def do_HEAD(s):
s.send_re... |
import json
from copy import deepcopy
from os import environ, getenv
from os.path import getmtime, isfile, join
from time import time
try:
from lockfile import LockFile
except:
from lockfile import FileLock as LockFile
from platformio import __version__
from platformio.exception import InvalidSettingName, In... |
"""Helper functions for community-finding algorithms."""
def is_partition(G, communities):
"""Return ``True`` if and only if ``communities`` is a partition of
the nodes of ``G``.
A partition of a universe set is a family of pairwise disjoint sets
whose union is the entire universe set.
``G`` is ... |
"""Support for the Uber API."""
import logging
from datetime import timedelta
import voluptuous as vol
import homeassistant.helpers.config_validation as cv
from homeassistant.components.sensor import PLATFORM_SCHEMA
from homeassistant.helpers.entity import Entity
from homeassistant.util import Throttle
_LOGGER = log... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
VERSION = (0, 2, 0)
__version__ = ".".join(map(str, VERSION))
__status__ = "Alpha"
__description__ = "Flexible & modular CMS powered by Flask and MongoDB"
__author__ = "Bruno Rocha <<EMAIL>>"
__email__ = "<EMAIL>"
__license__ = "MIT License"
__copyright__ = "Copyright 2014... |
# -*- coding: utf-8 -*-
# Improved by: BaSh - <bash.lnx AT gmail DOT com>
# Ported to Weechat 0.3.0 by: Sharn - <sharntehnub AT gmail DOT com)
# This Plugin Calls the libnotify bindings via python when somebody says your nickname, sends you a query, etc.
# To make it work, you may need to download: python-notify2 (and ... |
from __future__ import absolute_import
from __future__ import print_function
import sys
import tornado.web
import logging
from django import http
from django.conf import settings
from django.core.handlers.wsgi import WSGIRequest, get_script_name
from django.core.handlers import base
from django.core.urlresolvers impor... |
from io import StringIO
from django.contrib.sites.models import Site
from django.core.management import CommandError, call_command
from oscar.core.loading import get_model
from oscar.test import factories
from ecommerce.extensions.test.factories import create_order
from ecommerce.invoice.models import Invoice
from ec... |
from datetime import datetime
from django.forms import (
CharField, Form, MultipleChoiceField, MultiValueField, MultiWidget,
SelectMultiple, SplitDateTimeField, SplitDateTimeWidget, TextInput,
ValidationError,
)
from django.test import SimpleTestCase
beatles = (('J', 'John'), ('P', 'Paul'), ('G', 'George'... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('users', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='Community',
fields=[
... |
{
'name': 'Payment Follow-up Management',
'version': '1.0',
'category': 'Accounting & Finance',
'description': """
Module to automate letters for unpaid invoices, with multi-level recalls.
=========================================================================
You can define your multiple levels of r... |
"""
# INPUT: bibliospec sqlite files
# OUTPUT: extracts MS data and makes it R readable
"""
import sqlite3
import zlib
import sys
import numpy
import os
import math
import re
import string
def bibliospec2R(sqllitedb):
count=0
myquery = "SELECT numPeaks, peakMZ, peakIntensity, peptideSeq, precursorCharge, prec... |
#!/usr/bin/python
import logging
import os
import subprocess
import sys
log = logging.getLogger(__name__)
class OpenFileOrStdin(object):
"""File open context manager that knows '-' means to use stdin."""
def __init__(self, name, *args, **kwargs):
if name == '-':
self.f = sys.stdin
... |
"""
Main functions for link parsing
"""
from xml.parsers.expat import ParserCreate
from xml.parsers.expat import ExpatError
from ..checker.const import WARN_XML_PARSE_ERROR
class XmlTagUrlParser:
"""Parse XML files and find URLs in text content of a tag name."""
def __init__(self, tag):
"""Initialize... |
import pygame
from pygame.locals import *
from Constants import Constants
import os
class EventManager:
"Event Manager system"
def __init__(self,gamecontainer):
"Sets up the event manager"
self.gamecontainer=gamecontainer
self.events = {}
def add_event(self,object):
self.events[id(object)]=object
... |
"""
The program should take three arguments.
The first will be a day, the second will be month, and the third will be year.
Then, your program should compute the day of the week that date will fall on.
"""
import datetime
print "This program will tell you what day a particular date falls on."
# Enter a Day:
while Tru... |
from __future__ import division
import numpy as np
class DataPoint(object):
def __init__(self, R, U):
self.R = R
self.U = U
class Data(object):
def __init__(self):
self.pts = []
self.Rs = []
self.Us = []
self.bins = []
self.avgs = []
self.vars = []
def addPt(self, pt):
self.... |
from pyramid.response import Response
from pyramid.view import view_config
from sqlalchemy.exc import DBAPIError
from ..models import MyModel
@view_config(route_name='home', renderer='../templates/home.jinja2')
def my_view(request):
try:
query = request.dbsession.query(MyModel)
one = query.filte... |
import sys
from distutils.command.install import INSTALL_SCHEMES
from os.path import dirname, join, isfile, abspath
from setuptools import setup
from setuptools.command.install import install
from shutil import copy
for scheme in INSTALL_SCHEMES.values():
scheme['data'] = scheme['purelib']
setup_args = {
'c... |
from odoo import models
class WebsiteMenu(models.Model):
_inherit = "website.menu"
def unlink(self):
""" Override to synchronize event configuration fields with menu deletion.
This should be cleaned in upcoming versions. """
event_updates = {}
website_event_menus = self.en... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import constants as const
class Bitwise(object):
def __init__(self, bitboard):
self._bb = bitboard
def rev(self):
self._rev = ((self._bb & 0x5555555555555555) << 1) |\
((self._bb & 0xAAAAAAAAAAAAAAAA) >> 1)
self.... |
from __future__ import absolute_import
from __future__ import unicode_literals
import dnf.util
import dnf.yum.misc
import dnf.package
import dnf.query
import hawkey
import os
from dnf.pycomp import basestring
class SackVersion(object):
def __init__(self):
self._num = 0
self._chksum = dnf.yum.misc.C... |
import logging
from django import shortcuts
from django.urls import reverse
from django.utils.http import urlencode
from django.utils.text import format_lazy
from django.utils.translation import pgettext_lazy
from django.utils.translation import ugettext_lazy as _
from django.utils.translation import ungettext_lazy
f... |
"""
Unit tests for decorators.py.
"""
# pylint: disable=W0613
import os
import sys
import time
import traceback
import unittest
from pylib import constants
from pylib.device import decorators
from pylib.device import device_errors
from pylib.utils import reraiser_thread
# TODO(jbudorick) Remove once the DeviceUtils... |
"""
Django settings for funcao project.
Generated by 'django-admin startproject' using Django 1.8.
For more information on this file, see
https://docs.djangoproject.com/en/1.8/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.8/ref/settings/
"""
# Build paths i... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import os
import json
import pytest
from mock import ANY
from ansible.module_utils.network.fortios.fortios import FortiOSHandler
try:
from ansible.modules.network.fortios import fortios_wanopt_auth_group
except ImportError:
... |
# coding: utf-8
import socket
from .exceptions import ResponseIncomplete, ResponseMalformed
class Server(object):
timeout = 1.0
packets = {}
parsers = ()
formatters = ()
def __init__(self, ip, port, timeout=None):
self.timeout = timeout or self.timeout
self.ip = ip
self.... |
from pyanaconda import argument_parsing
from pyanaconda.core.configuration.anaconda import AnacondaConfiguration
from pyanaconda.core.kernel import KernelArguments
from pyanaconda.core.constants import DisplayModes
import unittest
class ArgparseTest(unittest.TestCase):
def _parseCmdline(self, argv, version="", bo... |
"""Built-in metrics.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import six
from tensorflow.python.keras._impl.keras import backend as K
from tensorflow.python.keras._impl.keras.losses import binary_crossentropy
from tensorflow.python.keras._impl.ke... |
"""
Tests for the signup views.
"""
from collections import namedtuple
from django.test import TestCase
from .. import views
MockUser = namedtuple('MockUser', ['is_staff'])
MockRequest = namedtuple('MockRequest', ['method', 'user'])
class TestIsStaffOrPostOnlyPermission(TestCase):
"""
Tests for the IsStaffOfP... |
# this module contains miscellaneous stuff which enventually could be moved
# into other places
from __future__ import absolute_import, division, print_function, unicode_literals
from collections import defaultdict
import os
from os.path import abspath, dirname, exists, isdir, isfile, join, relpath
import re
import s... |
"""Event tracker backend that saves events to a python logger."""
from __future__ import absolute_import
import logging
import json
from django.conf import settings
from track.backends import BaseBackend
from track.utils import DateTimeJSONEncoder
log = logging.getLogger('track.backends.logger')
application_log = ... |
from multiprocessing.pool import Pool
import numpy as np
from gingivere import SETTINGS
from gingivere.data import generate_mat_cvs
from gingivere.classifiers import make_simple_lr
from gingivere.utilities import TransformationPipeline
from tests.trainer import train_strategy
def build_data_for_cv(data):
X, pat... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.