content stringlengths 4 20k |
|---|
import logging
import os
import re
import pyauto_functional # Must be imported before pyauto
import pyauto
import test_utils
class PluginsTest(pyauto.PyUITest):
"""TestCase for Plugins."""
def Debug(self):
"""Test method for experimentation.
This method will not run automatically.
"""
import p... |
# -*- coding: utf-8 -*-
"""The LUKS Drive Encryption path specification implementation."""
from dfvfs.lib import definitions
from dfvfs.path import factory
from dfvfs.path import path_spec
class LUKSDEPathSpec(path_spec.PathSpec):
"""LUKSDE path specification.
Attributes:
password (str): password.
"""
... |
from lxml import etree
from .box import *
from .table import *
__all__ = ('HTMLParser',)
def pumper(html_generator):
"""
Pulls HTML from source generator,
feeds it to the parser and yields
DOM elements.
"""
source = html_generator()
parser = etree.HTMLPullParser(
events=('start', ... |
"""
Tests for states.py.
"""
from __init__ import DocutilsTestSupport
def suite():
s = DocutilsTestSupport.ParserTestSuite()
s.generateTests(totest)
return s
totest = {}
totest['line_blocks'] = [
["""\
| This is a line block.
| Line breaks are *preserved*.
| This is a second line block.
| This is a th... |
#!/usr/bin/env python2
# read a tag secured with the well known keys
import sys, MFRC522, printdat
nfc = MFRC522.MFRC522()
#key = [0xFF,0xFF,0xFF,0xFF,0xFF,0xFF]
key = [0x6B,0x65,0x79,0x20,0x61,0x00] # key a
#key = [0x6B,0x65,0x79,0x20,0x62,0x00] # key b
keyid = nfc.PICC_AUTHENT1A
#keyid = nfc.PICC_AUTH... |
from __future__ import absolute_import, print_function, unicode_literals
import os
import json
import six
try:
# Py3k
from html.parser import HTMLParser
except ImportError:
# Py2.7
from HTMLParser import HTMLParser
from pelican import signals
from pelican.readers import MarkdownReader, HTMLReader, Ba... |
import os
from shutil import copyfile
def isNumber(c):
try:
int(c)
return True
except ValueError:
return False
def lengthof(data, extractor):
totallength = 0
for c in data:
d, times = extractor.readChar(c)
datalength = len(d)
if datalength > 1:
totallength += lengthof(d,extractor) *... |
r"""TensorFlow Eager Execution Example: Linear Regression.
This example shows how to use TensorFlow Eager Execution to fit a simple linear
regression model using some synthesized data. Specifically, it illustrates how
to define the forward path of the linear model and the loss function, as well
as how to obtain the gr... |
"""
Support for creating a service which runs a web server.
"""
import os
# Twisted Imports
from twisted.web import server, static, twcgi, script, demo, distrib, trp, wsgi
from twisted.internet import interfaces, reactor
from twisted.python import usage, reflect, threadpool
from twisted.spread import pb
from twisted.... |
{
'author': 'ADHOC SA',
'website': 'www.adhoc.com.ar',
'category': 'Accounting & Finance',
'data': [
'views/account_view.xml',
'views/account_withholding_view.xml',
'views/account_voucher_view.xml',
'security/security.xml',
# 'security/ir.model.access.csv'
],... |
_TOKEN_BEGIN = "/**"
_TOKEN_MID = " * "
_TOKEN_END = " */\n"
_TOKEN_END_LEN = len(_TOKEN_END)
def _comment(text):
'''
Returns the given text as a multi-lined Javascript block comment.
'''
if text is None or text == "":
return ""
output = [_TOKEN_BEGIN]
lines = text.strip().split('\n')
... |
__author__ = '<EMAIL> (David Byttow)'
import module_test_runner
import opensocial_tests.orkut_test
import opensocial_tests.myspace_test
import opensocial_tests.partuza_test
import opensocial_tests.oauth_test
import opensocial_tests.google_sandbox_test
def RunSystemTests():
test_runner = module_test_runner.ModuleTe... |
import os
import sublime
import linecache
from .core.documents import is_at_word, get_position
from .core.panels import ensure_panel
from .core.protocol import Request, Point
from .core.registry import LspTextCommand, windows
from .core.settings import PLUGIN_NAME, settings
from .core.typing import List, Dict, Optiona... |
from setuptools import setup, find_packages
def read(fpath):
with open(fpath, 'r') as f:
return f.read()
def requirements(fpath):
return list(filter(bool, read(fpath).split('\n')))
def version(fpath):
return read(fpath).strip()
setup(
name = 'fmap',
version = version('version.txt'),
... |
import os.path
import pytest
import spack.container
@pytest.mark.parametrize('image,spack_version,expected', [
('ubuntu:18.04', 'develop', ('spack/ubuntu-bionic', 'latest')),
('ubuntu:18.04', '0.14.0', ('spack/ubuntu-bionic', '0.14.0')),
])
def test_build_info(image, spack_version, expected):
output = s... |
"""Provides distutils command classes for the GRPC Python setup process."""
from __future__ import print_function
import distutils
import glob
import os
import os.path
import platform
import re
import shutil
import subprocess
import sys
import traceback
import setuptools
from setuptools.command import build_ext
from... |
# -*- coding: utf-8 -*-
from Plasma import *
from PlasmaTypes import *
from bisect import *
import time
import datetime
xMasSuprisesdl = 'Event12'
xMasKranzsdl = 'Event14'
class codxMas(ptResponder):
def __init__(self):
ptResponder.__init__(self)
self.id = 8501007
self.version = 1
d... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals, print_function
import os
import pathspec
from pathlib2 import PurePath, Path
from gcdt.gcdt_logging import getLogger
log = getLogger(__name__)
# based on: https://github.com/finklabs/botodeploy/blob/master/botodeploy/utils_static.py
def glob_files(... |
import redis
import json
import base64
import time
class AlarmQueue():
def __init__(self,redis_server, alarm_queue = "QUEUES:CLOUD_ALARM_QUEUE", action_queue = "QUEUES:SPRINKLER:PAST_ACTIONS"):
self.redis = redis_server
self.alarm_queue = alarm_queue
self.action_queue = action_queue
def sto... |
#!/usr/bin/env python
# encoding=utf-8
"""
爬取豆瓣电影TOP250 - 完整示例代码
我们已经得到的信息有如下:
1.每页有25条电影,共有10页。
2.电影列表在页面上的位置为一个class属性为grid_view的ol标签中。
3.每条电影信息放在这个ol标签的一个li标签里。
"""
import codecs
import requests
from bs4 import BeautifulSoup
DOWNLOAD_URL = 'http://movie.douban.com/top250/'
def download_page(url):
"""
... |
'''
Inline XBRL Document Set plug-in.
Supports opening manifest file that identifies inline documents of a document set.
Saves extracted instance document.
(Does not currently support multiple target instance documents in a document set.)
(c) Copyright 2013 Mark V Systems Limited, All rights reserved.
'''
from arel... |
from odoo import api, models, _
from odoo.exceptions import UserError
class PosInvoiceReport(models.AbstractModel):
_name = 'report.point_of_sale.report_invoice'
_description = 'Point of Sale Invoice Report'
@api.model
def _get_report_values(self, docids, data=None):
PosOrder = self.env['pos.... |
#!/usr/bin/env python
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import argparse
import json
import os
import random
import numpy as np
import ray
from ray.tune import Trainable, run, sample_from
from ray.tune.schedulers import AsyncHyperBandSchedule... |
# -*- coding: utf-8 -*-
import click
import sys
from . import quickstart
from IPython.terminal.interactiveshell import TerminalInteractiveShell
IMPORTS = [
'from utils import conf',
'from fixtures.pytest_store import store',
'from utils.appliance.implementations.ui import navigate_to',
'from utils imp... |
# Sudoku
# A backtracking solution to everybody's favorite puzzle
# Programming Praxis Exercise 4
# http://programmingpraxis.com/2009/02/19/sudoku/
from copy import deepcopy
from itertools import product
# A cell is a tuple of (row, column) coordinates
# cells and peers are calculated just once, and stored
# in two ... |
from django.core.management.base import BaseCommand
from corehq.apps.accounting.models import Currency
from corehq.apps.smsbillables.utils import log_smsbillables_info
from corehq.messaging.smsbackends.tropo.models import SQLTropoBackend
from corehq.apps.sms.models import INCOMING, OUTGOING
from corehq.apps.smsbillabl... |
__author__ = 'Allan Saddi <<EMAIL>>'
__version__ = '$Revision: 2111 $'
import select
import struct
import socket
import errno
__all__ = ['SCGIApp']
def encodeNetstring(s):
return ''.join([str(len(s)), ':', s, ','])
class SCGIApp(object):
def __init__(self, connect=None, host=None, port=None,
... |
from yargy.visitor import Visitor
from yargy.dot import (
style,
DotTransformator,
BLUE,
ORANGE,
RED,
PURPLE,
GREEN,
DARKGRAY
)
from yargy.predicates import is_predicate
from .constructors import (
is_rule,
Production,
EmptyProduction,
Rule,
OrRule,
OptionalRule,... |
""" PyroScope - Pylons Middleware Initialization.
Copyright (c) 2009 The PyroScope Project <<EMAIL>>
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 2 of the License, ... |
from django.forms import ModelForm
from issues.models import Issue, Project, Note, Commit, IssueViewed, Tag
from django.contrib.auth.models import User
class IssueForm(ModelForm):
def __init__(self, *args, **kwargs):
super(IssueForm, self).__init__(*args, **kwargs)
self.fields['assigned_to'].choi... |
# -*- coding: utf-8 -*-
from uamobile import cidr
class UserAgent(object):
"""
Base class representing HTTTP user agent.
"""
def __init__(self, environ, context):
try:
self.useragent = environ['HTTP_USER_AGENT']
except KeyError, e:
self.useragent = ''
se... |
# -*- coding: utf-8 -*-
import json
import operator
import re
_OPERATORS = [
('|', operator.or_),
('^', operator.xor),
('&', operator.and_),
('>>', operator.rshift),
('<<', operator.lshift),
('-', operator.sub),
('+', operator.add),
('%', operator.mod),
('/', opera... |
import json
import sys
import autonetkit.log as log
from autonetkit.collection.utils import get_results
import pkg_resources
import autonetkit.collection.process as ank_process
import autonetkit.ank_messaging as ank_messaging
import autonetkit
import pkg_resources
parse_template = pkg_resources.resource_filename("auto... |
import jinja2
import os
import webapp2
from google.appengine.api import users
from google.appengine.ext import ndb
# We set a parent key on the 'Greetings' to ensure that they are all in the same
# entity group. Queries across the single entity group will be consistent.
# However, the write rate should be ... |
"""empty message
Revision ID: abdd036166bd
Revises:
Create Date: 2017-06-07 15:55:49.719940
"""
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import postgresql
# revision identifiers, used by Alembic.
revision = 'abdd036166bd'
down_revision = None
branch_labels = None
depends_on = None
d... |
from django.test import TestCase
from teams.models import Team, WaitList
from users.models import User
from django.utils import timezone
from django.core.exceptions import ValidationError
class WaitList_test(TestCase):
def setUp(self):
self.user_email = "<EMAIL>"
self.user_password = "12345678"
... |
#!/usr/bin/env python
# coding=utf-8
"""
A sample application for tagging categories on commands.
It also demonstrates the effects of decorator order when it comes to argparse errors occurring.
"""
import functools
import cmd2
from cmd2 import (
COMMAND_NAME,
)
def my_decorator(f):
@functools.wraps(f)
d... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
import traceback
import os
import threading
import time
import subprocess
import re
descriptors = list()
Desc_Skel = {}
_Worker_Thread = None
_Lock = threading.Lock() # synchronization lock
Debug = False
def dprint(f, *v):
if Debug:
print >>sys.s... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import re
import copy
import os
from django.conf import settings
from django.contrib.auth import get_user_model
import mistune
from .utils.emoji import emojis
User = get_user_model()
class InlineGrammar(mistune.InlineGrammar):
emoji = re.comp... |
import numpy as np
import scipy as sp
from recirq.hfvqe.util import (generate_permutations, swap_forward,
generate_fswap_pairs, generate_fswap_unitaries)
def test_swap_forward():
list_to_swap = list(range(6))
test_swapped_list = swap_forward(list_to_swap, starting_index=0)
a... |
import ibis
import os
import pytest
MAPD_HOST = os.environ.get('IBIS_TEST_MAPD_HOST', 'localhost')
MAPD_PORT = int(os.environ.get('IBIS_TEST_MAPD_PORT', 9091))
MAPD_USER = os.environ.get('IBIS_TEST_MAPD_USER', 'mapd')
MAPD_PASS = os.environ.get('IBIS_TEST_MAPD_PASSWORD', 'HyperInteractive')
MAPD_DB = os.environ.get('... |
"""Implementation of compile_html based on textile."""
import codecs
import os
try:
from textile import textile
except ImportError:
textile = None # NOQA
from nikola.plugin_categories import PageCompiler
class CompileTextile(PageCompiler):
"""Compile textile into HTML."""
name = "textile"
de... |
import re
from django.conf import settings
from django.core.exceptions import ObjectDoesNotExist
from django.core.urlresolvers import resolve
from bilanci.views import HomeTemporaryView, PageNotFoundTemplateView, BilancioDettaglioView, BilancioNotFoundView, \
BilancioIndicatoriView, BilancioComposizioneView, Compos... |
from django.http import HttpResponse
from django.template import Context, loader
from models import *
import json
def create_id(counter):
return 'i_binding_%d' % (counter,)
def rpi_displays(request, rpi_mac):
read_display_cls = ReadDisplay.__subclasses__()
write_display_cls = WriteDisplay.__subclasses__()... |
import fixtures
import logging
import os
import stat
import tempfile
import unittest.mock
import snapcraft
from snapcraft import repo
from snapcraft import tests
class UbuntuTestCase(tests.TestCase):
def setUp(self):
super().setUp()
fake_logger = fixtures.FakeLogger(level=logging.ERROR)
... |
# -*- coding: utf-8 -*-
"""
Created on Tue Jan 13 18:22:38 2015
@author: Ehsan
"""
# -*- coding: utf-8 -*-
"""
Created on Tue Jan 13 15:02:15 2015
@author: Ehsan
"""
import pandas as pd
import numpy as np
#config
year = "2011"
traffic_file = "DATA/VOL_" + year + ".csv"
# weather
station = "newyork"
weather_file... |
import logging
import random
from google.appengine.api import memcache
from mlabns.db import model
from mlabns.util import constants
# Default value if datastore contains no record for a given experiment.
# This object should not be returned directly, but you can make a copy
# with a custom name by calling default_r... |
from setuptools import setup
from os import path
from codecs import open
from setuptools.command.install import install
here = path.abspath(path.dirname(__file__))
with open(path.join(here, 'README.rst'), encoding='utf-8') as f:
long_description = f.read()
setup(
name = 'ScalPy',
version = '0.2.0',
i... |
from spack import *
class RPsych(RPackage):
"""A general purpose toolbox for personality, psychometric theory and
experimental psychology. Functions are primarily for multivariate
analysis and scale construction using factor analysis, principal
component analysis, cluster analysis and reliabi... |
from copy import deepcopy
from nupic.research.frameworks.pytorch.model_utils import get_parent_module
def clone_model(model, keep_params=None, keep_hooks=True):
"""
Clones a model by creating a deepcopy and then for each param either
1) cloning it from the original to the copied model
2) pass... |
"""Defines utility functions."""
import tensorflow as tf
def assign_moving_average_vars(model, ema_model, optimizer):
"""Assigns moving average variables to the model using moving average.
Args:
model: An original model.
ema_model: A model using moving average.
optimizer: An optimizer which stores m... |
from couchpotato.core.event import addEvent, fireEvent
from couchpotato.core.helpers.variable import tryFloat, mergeDicts, md5, \
possibleTitles, getTitle
from couchpotato.core.logger import CPLog
from couchpotato.core.plugins.base import Plugin
from couchpotato.environment import Env
from urlparse import urlparse
... |
"""
This module contains the Login Server. This server will only
manage the authentication (and not the authorization) of the
users. To this end, it defines that there are two interfaces:
* One for those systems that can be checked with typical credentials (e.g.,
using a username a password). Examples of this wou... |
import sys
import fnmatch
import os
import unittest
try:
from pylint import epylint as lint
except ImportError:
sys.stderr.write("Could not import pylint module - lint based testing will be skipped\n")
lint = None
class LintTestCase(unittest.TestCase):
"""This class is a test case for linting."""
... |
"""Tests for SSL support."""
import os
import socket
import sys
import unittest
try:
from ssl import CertificateError
except ImportError:
# Backport.
from pymongo.ssl_match_hostname import CertificateError
sys.path[0:0] = [""]
from urllib import quote_plus
from nose.plugins.skip import SkipTest
from p... |
from msrest.pipeline import ClientRawResponse
from .. import models
class BoolModel(object):
"""BoolModel operations.
:param client: Client for service requests.
:param config: Configuration of service client.
:param serializer: An object model serializer.
:param deserializer: An objec model des... |
# -*- coding: utf-8 -*-
from south.utils import datetime_utils as datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding field 'BuildEnvironment.sourcedir'
db.add_column(u'bldcontrol_bu... |
import webuntis
import mock
from webuntis.utils.third_party import json
from .. import WebUntisTestCase, BytesIO
class BasicUsage(WebUntisTestCase):
def test_parse_result(self):
x = webuntis.utils.remote._parse_result
a = {'id': 2}
b = {'id': 3}
self.assertRaisesRegex(webuntis.err... |
import gtk
from gtk import gdk
from gettext import gettext as _
from fnmatch import fnmatch
import brushmanager
from pixbuflist import PixbufList
import widgets
import spinbox
OVERWRITE_THIS = 1
OVERWRITE_ALL = 2
DONT_OVERWRITE_THIS = 3
DONT_OVERWRITE_ANYTHING = 4
CANCEL = 5
def confirm(widget, question):
window... |
from __future__ import unicode_literals
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
if not ("django.contrib.sites" in settings.INSTALLED_APPS):
raise ImproperlyConfigured("django.contrib.sites is required")
# The maximum allowed length for field values.
FIELD_MAX_LE... |
import glob
import os
from qgis.core import QgsApplication
from command import command, complete_with
from PyQt4.QtCore import QUrl
from PyQt4.QtGui import QDesktopServices
folder = os.path.join(QgsApplication.qgisSettingsDirPath(), "python",
"commandbar")
def packages(argname, data):
retu... |
from __future__ import absolute_import, division, print_function
from builtins import (ascii, bytes, chr, dict, filter, hex, input,
int, map, next, oct, open, pow, range, round,
str, super, zip)
import pytest
import yaml
with open('tests/vars/logstash.vars', 'r') as f:
t... |
import os
import numpy as np
from ase import Atom, Atoms
from gpaw import GPAW, FermiDirac
from gpaw.utilities.dos import raw_orbital_LDOS, raw_wignerseitz_LDOS, RawLDOS
from gpaw.test import equal
import gpaw.mpi as mpi
import numpy as np
comms = [mpi.world.new_communicator(np.array([r])) for r in range(mpi.size)]
co... |
# -*- coding: utf-8 -*-
from django.conf.urls import url, include
from rest_framework import routers
import oauth2_provider.views as oauth2_views
from .viewsets import EventViewSet, SongViewSet, CompetitionViewSet, CompoViewSet, ProgrammeEventViewSet,\
SponsorViewSet, MessageViewSet, IRCMessageViewSet, StoreItemVi... |
"""
To try bandicoot without installing it, add the bandicoot toolbox
to your Python path with:
>>> import sys
>>> sys.path.append("../")
"""
from bandicoot.helper.group import grouping
import bandicoot as bc
# Loading a User
U = bc.read_csv('ego', 'data/', 'data/antennas.csv')
#######################
# Export vi... |
from odoo import api, fields, models
from ..constants import (
ESTADOS_CNAB,
SITUACAO_PAGAMENTO,
BR_CODES_PAYMENT_ORDER,
)
class AccountMoveLine(models.Model):
_name = 'account.move.line'
_inherit = [_name, 'l10n_br_cnab.change.methods']
# As linhas de cobrança precisam ser criadas conforme s... |
#!/usr/bin/env python
from argparse import ArgumentParser
from datetime import datetime
import logging
import sys
from time import sleep
from chaos import MonkeyRunner
from jujupy import (
client_from_config,
)
from utility import configure_logging
__metaclass__ = type
def run_while_healthy_or_timeout(monkey):... |
import sys
from services.spawn import MobileTemplate
from services.spawn import WeaponTemplate
from resources.datatables import WeaponType
from resources.datatables import Difficulty
from resources.datatables import Options
from java.util import Vector
def addTemplate(core):
mobileTemplate = MobileTemplate()
mobi... |
from enum import Enum
class SkuName(Enum):
basic = "Basic"
standard = "Standard"
class SkuTier(Enum):
basic = "Basic"
standard = "Standard"
class AccessRights(Enum):
manage = "Manage"
send = "Send"
listen = "Listen"
class KeyType(Enum):
primary_key = "PrimaryKey"
secondar... |
import os
from lavaCheck.generic import *
class CheckTmpDir(Check):
def pre(self):
try:
tmpdir=os.environ["TMPDIR"]
except KeyError:
tmpdir="/tmp"
self.log.debug("TMPDIR not defined, defaulting to: %s" % tmpdir)
if not os.path.isdir(tmpdir):
raise NodeSoftFailError("TMPDIR: %s is not a directory." % ... |
# coding:utf-8
import os
import time
import pwd
import grp
import subprocess
import unittest
import uuid
import resource
from six.moves import queue
from captain_comeback.index import CgroupIndex
from captain_comeback.cgroup import Cgroup
from captain_comeback.restart.messages import RestartRequestedMessage
CG_PAREN... |
import bpy
from bpy.props import BoolProperty, IntProperty, StringProperty
from sverchok.node_tree import SverchCustomTreeNode
from sverchok.data_structure import (changable_sockets, repeat_last, updateNode)
import numpy as np
# SvListItemNode
# Allows a list of indexes, with both negative and positive index and repea... |
#!/usr/bin/env python
import os,pwd
import ConfigParser,argparse
# This is too small to require any class here, but it was easier to pull it from worker.py
def intonlystring(string):
# takes a string, and returns a string only containing integers.
# referenced https://stackoverflow.com/questions/5843518/ but modifie... |
import argparse
import concurrent.futures
import daemon
import json
import pandas as pd
import pickle
import psutil
import time
import types
import uuid
from tornado.ioloop import IOLoop
from queue import Queue
from tornado.web import Application, RequestHandler
from .common.logging import log
from .common.tools import... |
from naman.core.models import Machine
from forms import MachineForm
from django.shortcuts import render_to_response, get_object_or_404, redirect
from django.template import RequestContext
from naman.core.tools.views import paginator
from django.core.urlresolvers import reverse
from django.db.models import Q
from django... |
"""Tests for tensorflow.kernels.logging_ops."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import string
import sys
import tempfile
from tensorflow.python.eager import context
from tensorflow.python.eager import function
from tensorflow.pyth... |
import math
import sys
import unittest
from pyspark import serializers
from pyspark.serializers import *
from pyspark.serializers import CloudPickleSerializer, CompressedSerializer, \
AutoBatchedSerializer, BatchedSerializer, AutoSerializer, NoOpSerializer, PairDeserializer, \
FlattenedValuesSerializer, Cartes... |
from __future__ import (absolute_import, division, print_function)
import inspect
import itertools
import os
import sys
import warnings
import six
import cartopy.tests
def walk_module(mod_name, exclude_folders=None):
"""
Recursively walks the given module name.
Returns:
A generator of::
... |
'''Diff class for GitHub pull requests.
The main feature of note is that this fetches files from GitHub lazily when
a_path and b_path are accessed. This allows large PRs to be loaded quickly
--more quickly than GitHub's UI does it!
'''
import os
import tempfile
import sys
from webdiff.util import memoize
from webdif... |
# -*- coding: utf-8 -*-
#
# Originally modified from Vincent Ting's code
import time
import hashlib
import requests
import logging
_FAKE_HEADERS = {
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
'Accept-Charset': 'GBK,utf-8;q=0.7,*;q=0.3',
'Accept-Encoding': 'gzip,deflate,s... |
from __future__ import print_function
import argparse
import os
import sys
import tempfile
from mako import template as mako_template
import yaml
from sahara.openstack.common import fileutils
from sahara.tests.scenario import validation
TEST_TEMPLATE_PATH = 'sahara/tests/scenario/testcase.py.mako'
def set_default... |
import json
import re
from oslo_log import log as logging
import paramiko
import time
LOG = logging.getLogger(__name__)
DEFAULT_PORT = 29418
GERRIT_URI_PREFIX = r'^gerrit:\/\/'
PAGE_LIMIT = 100
REQUEST_COUNT_LIMIT = 20
SSH_ERRORS_LIMIT = 10
class RcsException(Exception):
pass
class Rcs(object):
def __ini... |
from urllib import unquote
from amgut.lib.mail import send_email
from amgut.handlers.base_handlers import BaseHandler
from amgut.connections import ag_data
from amgut import text_locale
class ChangePassVerifyHandler(BaseHandler):
def get(self):
email = self.get_argument('email', None)
if email i... |
from matplotlib.backends.qt_compat import QtCore, QtGui, QtWidgets
class UiSubplotTool(QtWidgets.QDialog):
def __init__(self, *args, **kwargs):
super(UiSubplotTool, self).__init__(*args, **kwargs)
self.setObjectName("SubplotTool")
self._widgets = {}
layout = QtWidgets.QHBoxLayout... |
"""Tests for the Device Registry."""
import asyncio
from unittest.mock import patch
import asynctest
import pytest
from homeassistant.core import callback
from homeassistant.helpers import device_registry
from tests.common import mock_device_registry, flush_store
@pytest.fixture
def registry(hass):
"""Return an... |
import invoice
import analytic |
# -*- 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):
# Adding field 'Criterion.label'
db.add_column('assessment_criterion', 'label',
self.g... |
# Your program must decode the encoded message from the Chuck Norris encoding
# project.
# It is strongly recommended to have done the Chuck Norris project.
# Link -> https://www.codingame.com/training/easy/chuck-norris
# Here are some reminders about the Chuck Norris encoding method:
# - The encoded message... |
"""
Some codes from https://github.com/Newmu/dcgan_code
"""
from __future__ import division
import math
import json
import random
import scipy.misc
import numpy as np
from time import gmtime, strftime
# -----------------------------
# new added functions for pix2pix
def load_data(image_path, image_size, input_c_dim, ... |
from netforce.model import Model, fields, get_model
from netforce.access import get_active_company, get_active_user, check_permission_other
class BarcodeReceiveMFG(Model):
_name = "barcode.receive.mfg"
_transient = True
_fields = {
"location_to_id": fields.Many2One("stock.location", "To Location",... |
# -*- coding: utf-8 -*-
"""
jinja2.testsuite.api
~~~~~~~~~~~~~~~~~~~~
Tests the public API and related stuff.
:copyright: (c) 2010 by the Jinja Team.
:license: BSD, see LICENSE for more details.
"""
import os
import tempfile
import shutil
import pytest
from jinja2 import Environment, Undefined, D... |
__version__ = "0.1.1"
"""fastq_sniffer.py
Usage: fastq_sniffer.py [ --subset N ] <fastq_file>
"Sniff" FASTQ file to try and determine likely format and quality encoding.
"""
#######################################################################
# Import modules that this module depends on
########################... |
'''update TortoiseHg status cache'''
from mercurial import hg
from tortoisehg.util import paths, shlib
import os
def cachefilepath(repo):
return repo.join("thgstatus")
def run(_ui, *pats, **opts):
if opts.get('all'):
roots = []
base = os.getcwd()
for f in os.listdir(base):
... |
""" Django admin pages for student app """
from django import forms
from django.contrib.auth.models import User
from ratelimitbackend import admin
from xmodule.modulestore.django import modulestore
from opaque_keys import InvalidKeyError
from opaque_keys.edx.keys import CourseKey
from config_models.admin import Config... |
from msrest.serialization import Model
class UserIdentityFragment(Model):
"""Identity attributes of a lab user.
:param principal_name: Set to the principal name / UPN of the client JWT
making the request.
:type principal_name: str
:param principal_id: Set to the principal Id of the client JWT ma... |
import os
import logging
import numpy as np
from PIL import Image
from .util import download, checksum, archive_extract, checkpoint
log = logging.getLogger(__name__)
_URLS = {
'original': (
'http://vis-www.cs.umass.edu/lfw/lfw.tgz',
'a17d05bd522c52d84eca14327a23d494',
# Checksum from webs... |
"""Tests for extra tabs added to the navbar."""
__author__ = 'John Orr (<EMAIL>)'
from controllers import sites
from models import courses
from models import resources_display
from models import models
from modules.i18n_dashboard.i18n_dashboard import ResourceBundleDAO
from modules.i18n_dashboard.i18n_dashboard impor... |
#!/usr/bin/python
"""Parses and loads RGI questions from excel into MongoDB"""
from xlrd import open_workbook
from sys import argv
from parser import parse
from loader import mongo_load
from loader import status_check
import json
# from pprint import pprint
# from utils import write_json
ERROR_MSGS = {
'valid_n... |
"""Implement the API for document management."""
from __future__ import absolute_import, print_function
from collections import namedtuple
import jsonpointer
import six
from fs.opener import opener
from fs.utils import copyfile, movefile
class Document(namedtuple('Document', ('record', 'pointer'))):
"""Represe... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
from django.conf import settings
class Migration(migrations.Migration):
dependencies = [
('audit_trail', '0007_auto_20150422_0548'),
]
operations = [
migrations.AlterModelOptions(
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.