code stringlengths 1 199k |
|---|
from openerp.osv import fields, osv, orm
from openerp.tools.translate import _
class res_users(orm.Model):
"""
Custom res_users object
Add a CAFAT ID for use in New Caledonia
It's for odoo user not partner
For partner you'll find the CAFAT ID in res.parner object
"""
_inherit = "res.users"
... |
import django_filters
from django.forms import TextInput
from django.urls import reverse
from django.utils.translation import gettext_lazy as _
from rest_framework import serializers
from base.models.entity_version import EntityVersion
class EntityVersionFilter(django_filters.FilterSet):
acronym = django_filters.Ch... |
import os
import numpy as np
import pytest
import mdtraj as md
from mdtraj.formats import HDF5TrajectoryFile, NetCDFTrajectoryFile
from mdtraj.reporters import HDF5Reporter, NetCDFReporter, DCDReporter
from mdtraj.testing import eq
try:
from simtk.unit import nanometers, kelvin, picoseconds, femtoseconds
from s... |
import pytest
from spack.main import SpackCommand
versions = SpackCommand('versions')
def test_safe_only_versions():
"""Only test the safe versions of a package.
(Using the deprecated command line argument)
"""
versions('--safe-only', 'zlib')
def test_safe_versions():
"""Only test the safe versio... |
from dumper import *
def dumpLiteral(d, value):
d.putSimpleCharArray(value["_chars"], value["_size"])
def qdump__Core__Id(d, value):
try:
name = d.parseAndEvaluate("Core::nameForId(%d)" % value["m_id"])
d.putSimpleCharArray(name)
except:
d.putValue(value["m_id"])
d.putPlainChildr... |
from basetest import BaseTest
import sys, tempfile, os, time
import unittest
import data
sys.path.insert(0, '..')
from zeroinstall.injector import model, gpg, trust
from zeroinstall.injector.namespaces import config_site
from zeroinstall.injector.iface_cache import PendingFeed
from zeroinstall.support import basedir
cl... |
from pyrtist.lib2d import Point, Tri
bbox1 = Point(0.0, 50.0); bbox2 = Point(100.0, 12.5838926174)
p1 = Point(3.15540458874, 46.942241204)
p2 = Point(3.23537580547, 42.1395946309)
p4 = Point(28.5119375629, 38.1285583893)
q1 = Point(73.1545885714, 21.8120805369)
q3 = Point(93.6244457143, 38.4228187919)
q5 = Point(66.413... |
"""
Pychan extension widgets.
Extension widgets are partly experimental, partly rarely used widgets
which are added here. They are by default not included in the widgets
registry and thus cannot be loaded from XML files. Use L{pychan.widgets.registerWidget}
to enable that.
Not the same care to keep the API stable will ... |
import sys
import requests
try:
url = sys.argv[1]
r = requests.get('http://%s' %url ,timeout=3)
except requests.exceptions.Timeout:
print 'url timeout\n%s' %url
sys.exit(2)
except:
print 'url error \n%s' %url
sys.exit(2)
url_status = r.status_code
if url_status == 200:
... |
import os
import shutil
from cerbero.config import Platform
from cerbero.utils import shell
CLEAN_ENV = os.environ.copy()
if CLEAN_ENV.has_key('LD_LIBRARY_PATH'):
CLEAN_ENV.pop('LD_LIBRARY_PATH')
GIT = 'git'
def init(git_dir):
'''
Initialize a git repository with 'git init'
@param git_dir: path of the g... |
"""Test of table output."""
from macaroon.playback import *
import utils
sequence = MacroSequence()
sequence.append(KeyComboAction("End"))
sequence.append(KeyComboAction("Up"))
sequence.append(KeyComboAction("<Shift>Right"))
sequence.append(KeyComboAction("Down"))
sequence.append(KeyComboAction("Return"))
sequence.appe... |
"""Pretty-print tabular data."""
from __future__ import print_function
from __future__ import unicode_literals
from collections import namedtuple
from platform import python_version_tuple
import re
import math
if python_version_tuple() >= ("3", "3", "0"):
from collections.abc import Iterable
else:
from collecti... |
{
"name": "Delivery Sequence",
"vesion": "12.0.1.0.0",
"author": "IT-Projects LLC, Ivan Yelizariev",
"license": "LGPL-3",
"category": "Custom",
"website": "https://yelizariev.github.io",
"depends": ["delivery"],
"data": ["views.xml"],
"installable": False,
} |
from setuptools import setup, Extension
import sys
import os
import psutil
def parallelCCompile(self, sources, output_dir=None, macros=None, include_dirs=None, debug=0, extra_preargs=None, extra_postargs=None, depends=None):
# those lines are copied from distutils.ccompiler.CCompiler directly
macros, objects, e... |
"""A module for handling and accessing both the in-memory, and on-disk,
representation of a set of routes as a set of segments. Where each segment
specifies its start and end stop ids, and other data (see
topology_shapefile_data_model.py for more."""
import sys
import csv
import re
import operator
import itertools
impo... |
"""Curses interface class."""
from __future__ import unicode_literals
import sys
from glances.compat import nativestr, u, itervalues, enable, disable
from glances.globals import MACOS, WINDOWS
from glances.logger import logger
from glances.events import glances_events
from glances.processes import glances_processes, so... |
import pytest
from numpy import isclose
from dolfin import (assemble, dx, Function, FunctionSpace, grad, inner, solve, TestFunction, TrialFunction,
UnitSquareMesh)
from rbnics.backends import LinearSolver as FactoryLinearSolver
from rbnics.backends.dolfin import LinearSolver as DolfinLinearSolver
fr... |
import re
from DelogX.utils.i18n import I18n
from DelogX.utils.path import Path
from DelogX.utils.plugin import Plugin
class DelogReadMore(Plugin):
i18n = None
def run(self):
conf = self.blog.default_conf
self.i18n = I18n(
Path.format_url(self.workspace, 'locale'), conf('local.locale... |
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('tickets', '0008_auto_20180730_2035'),
]
operations = [
migrations.AlterModelOptions(
name='ticket',
options={'default_permissions': ('add', 'change', 'delete', 'view')},
... |
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 model 'Category'
db.create_table(u'core_category', (
(u'id', self.gf('django.db... |
from msaf.models import dbsession, Sample, Marker, Batch
from msaf.lib.analytics import SampleSet
from itertools import cycle
import yaml
def load_yaml(yaml_text):
d = yaml.load( yaml_text )
instances = {}
for k in d:
if k == 'selector':
instances['selector'] = Selector.from_dict( d[k] )... |
"""This module contains an object that represents a Telegram Message Parse Modes."""
from typing import ClassVar
from telegram import constants
from telegram.utils.deprecate import set_new_attribute_deprecated
class ParseMode:
"""This object represents a Telegram Message Parse Modes."""
__slots__ = ('__dict__',... |
"""
Base version of package/tasks.py, created by version 0.3.0 of
package/root/dir> dk-tasklib install
(it should reside in the root directory of your package)
This file defines tasks for the Invoke tool: http://www.pyinvoke.org
Basic usage::
inv -l # list all available tasks
inv build -f ... |
from typing import Optional
from UM.Logger import Logger
from cura.CuraApplication import CuraApplication
from cura.PrinterOutput.Models.MaterialOutputModel import MaterialOutputModel
from .BaseCloudModel import BaseCloudModel
class CloudClusterPrinterConfigurationMaterial(BaseCloudModel):
## Creates a new material... |
import weakref
import logging
logger = logging.getLogger(__name__)
import core.cons as cons
from core.api import api
from core.config import conf
from qt import signals
OPTION_IP_RENEW_ACTIVE = "ip_renew_active"
OPTION_RENEW_SCRIPT_ACTIVE = "renew_script_active"
class IPRenewerGUI:
""""""
def __init__(self, par... |
"""
A script to convert the standard names information from the provided XML
file into a Python dictionary format.
Takes two arguments: the first is the XML file to process and the second
is the name of the file to write the Python dictionary file into.
By default, Iris will use the source XML file:
etc/cf-standard... |
"""Launcher of the Mikado pick step."""
import argparse
import re
import sys
import os
from typing import Union, Dict
from ._utils import check_log_settings_and_create_logger, _set_pick_mode
import marshmallow
from ..configuration import DaijinConfiguration, MikadoConfiguration
from ..exceptions import InvalidConfigura... |
import sys
def main():
files = sys.argv[1:]
suffixes = {}
for filename in files:
suff = getsuffix(filename)
suffixes.setdefault(suff, []).append(filename)
for suff, filenames in sorted(suffixes.items()):
print(repr(suff), len(filenames))
def getsuffix(filename):
name, sep, su... |
import sys
if sys.version_info[0] < 3:
print('CXXII exige Python 3 ou mais recente.')
sys.exit(1)
import os
import time
import datetime
import unicodedata
import urllib.request
import tempfile
import zipfile
import re
from xml.etree.ElementTree import ElementTree as CXXII_XML_Arvore
class CXXII_XML_Arquivo:
... |
from . import res_country |
"""
Test the Fieldsfile file loading plugin and FFHeader.
"""
from __future__ import (absolute_import, division, print_function)
from six.moves import zip
import iris.tests as tests
import collections
import mock
import numpy as np
import iris
import iris.fileformats.ff as ff
import iris.fileformats.pp as pp
_MockField... |
"""
Testing for the tree module (sklearn.tree).
"""
import numpy as np
from numpy.testing import assert_array_equal
from numpy.testing import assert_array_almost_equal
from numpy.testing import assert_almost_equal
from numpy.testing import assert_equal
from nose.tools import assert_raises
from nose.tools import assert_... |
def bytes_to_long(foo):
return 0
def long_to_bytes(foo):
return '\0' |
n = int(input())
st = [(-1, -2)]
s = 0
for i, h in enumerate(map(int, input().split() + [' -1'])):
if h > st[-1][1]:
st.append((i, h))
else:
while st[-1][1] >= h:
r = st.pop()
s = max(s, (i - r[0]) * r[1])
st.append((r[0], h))
print(s) |
from django.shortcuts import render
from django.core.urlresolvers import reverse
from django.contrib.auth.models import User
from django.contrib.auth import authenticate, login, logout, update_session_auth_hash
from django.core.exceptions import ObjectDoesNotExist
from django.core.cache import cache
from django.http im... |
# This script will count the number of tweets within an output.txt file
import re
output = open("output.txt", "r");
regex = re.compile("\n\n");
newlinenewline = regex.findall(output.read());
print len(newlinenewline); |
import h5py # HDF5 support
import os
import glob
import numpy as n
from scipy.interpolate import interp1d
import sys
from astropy.cosmology import FlatLambdaCDM
import astropy.units as u
cosmoMD = FlatLambdaCDM(H0=67.77*u.km/u.s/u.Mpc, Om0=0.307115, Ob0=0.048206)
status = 'update'
path_to_lc = sys.argv[1]
f = h5py.F... |
import operator
def pozicijaSprite(broj, x_velicina):
#vraca pixel na kojem se sprite nalazi
pixel = broj * (x_velicina + 1) #1 je prazan red izmedu spritova
return(pixel)
spriteSlova = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "s", ",", "'", "1", "2", "4", "8", "6", "3", ".", "5", "7", "9", "0", "M", "B", "I... |
"""
Mastermind without kivy - by Luis
merciless edited by hans
"""
import random
import re
class G():
valid_chars = '123456'
secret_len = 5
solved = '+' * secret_len
regex_str = "^[{0}]{{{1},{1}}}$".format(valid_chars, secret_len)
valid_input = re.compile(regex_str) # regular expression for ... |
from __future__ import print_function
import httplib2
import io
import os
import sys
import time
import dateutil.parser
from apiclient import discovery
from oauth2client import client
from oauth2client import tools
from oauth2client.file import Storage
from apiclient.http import MediaIoBaseDownload
import pprint
YEAR_O... |
"""
This script computes bounds on the privacy cost of training the
student model from noisy aggregation of labels predicted by teachers.
It should be used only after training the student (and therefore the
teachers as well). We however include the label files required to
reproduce key results from our paper (https://a... |
from nova import flags
from nova import log as logging
from nova import utils
from nova.network import linux_net
from nova.openstack.common import cfg
from ryu.app.client import OFPClient
LOG = logging.getLogger(__name__)
ryu_linux_net_opt = cfg.StrOpt('linuxnet_ovs_ryu_api_host',
default... |
from random import choice
from suds import *
from ws import *
import time
def load_kam(client, kam_name):
'''
Loads a KAM by name. This function will sleep until the KAM's
loadStatus is 'COMPLETE'.
'''
def call():
'''
Load the KAM and return result. Exit with error if 'loadStatus'
... |
"""
Weather component that handles meteorological data for your location.
For more details about this component, please refer to the documentation at
https://home-assistant.io/components/weather/
"""
import asyncio
import logging
from homeassistant.helpers.entity_component import EntityComponent
from homeassistant.help... |
import argparse
import parsl
from parsl.app.app import python_app
from parsl.tests.configs.local_threads import config
@python_app(cache=True)
def random_uuid(x, cache=True):
import uuid
return str(uuid.uuid4())
def test_python_memoization(n=2):
"""Testing python memoization disable
"""
x = random_u... |
import argparse
import logging
import os
import sys
from typing import List, Union
import numpy as np
from ludwig.api import LudwigModel
from ludwig.backend import ALL_BACKENDS, LOCAL, Backend
from ludwig.constants import FULL, TEST, TRAINING, VALIDATION
from ludwig.contrib import contrib_command
from ludwig.globals im... |
"""Formatter for Android contacts2.db database events."""
from plaso.lib import eventdata
class AndroidCallFormatter(eventdata.ConditionalEventFormatter):
"""Formatter for Android call history events."""
DATA_TYPE = 'android:event:call'
FORMAT_STRING_PIECES = [
u'{call_type}',
u'Number: {number}',
... |
"""Tensor utility functions."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import ops
from tensorflow.python.ops import array_ops
from tensorflow.python.op... |
import os
import unittest
import synapse
import synapse.lib.datfile as s_datfile
from synapse.tests.common import *
syndir = os.path.dirname(synapse.__file__)
class DatFileTest(SynTest):
def test_datfile_basic(self):
with s_datfile.openDatFile('synapse.tests/test.dat') as fd:
self.nn(fd)
... |
from django.test import TestCase
from django.core.urlresolvers import reverse
from working_waterfronts.working_waterfronts_api.models import Video
from django.contrib.auth.models import User
class EditVideoTestCase(TestCase):
"""
Test that the Edit Video page works as expected.
Things tested:
URLs r... |
from textwrap import dedent
import pytest
import salt.modules.pdbedit as pdbedit
from tests.support.mock import MagicMock, patch
@pytest.fixture(autouse=True)
def setup_loader(request):
setup_loader_modules = {pdbedit: {}}
with pytest.helpers.loader_mock(request, setup_loader_modules) as loader_mock:
yi... |
from nose.tools import *
from leela.client.sensors.linux import disk_usage
def test_disk_usage_sensor_is_stateless():
sensor = disk_usage.DiskUsage()
ok_([] != sensor.measure())
def test_disk_usage_sensor_produces_core_metrics():
sensor = disk_usage.DiskUsage()
events = [e.name() for e in sensor.measure... |
from enum import Enum
from math import *
__version__ = "0.3.0"
LIBCELLML_VERSION = "0.2.0"
STATE_COUNT = 4
VARIABLE_COUNT = 18
class VariableType(Enum):
VARIABLE_OF_INTEGRATION = 1
STATE = 2
CONSTANT = 3
COMPUTED_CONSTANT = 4
ALGEBRAIC = 5
EXTERNAL = 6
VOI_INFO = {"name": "time", "units": "milli... |
from setuptools import setup
from setuptools.command.test import test
class TestHook(test):
def run_tests(self):
import nose
nose.main(argv=['nosetests', 'tests/', '-v', '--logging-clear-handlers'])
setup(
name='lxml-asserts',
version='0.1.2',
description='Handy functions for testing lxm... |
"""
Initialization script for restapi for the application.
"""
from flask import Blueprint
from app.common.logging import setup_logging
api = Blueprint('api', __name__)
from . import views, errors |
from google.cloud import appengine_admin_v1
def sample_delete_instance():
# Create a client
client = appengine_admin_v1.InstancesClient()
# Initialize request argument(s)
request = appengine_admin_v1.DeleteInstanceRequest(
)
# Make the request
operation = client.delete_instance(request=reque... |
class HeapBuilder:
def __init__(self):
self._swaps = []
self._data = []
def ReadData(self):
n = int(input())
self._data = [int(s) for s in input().split()]
assert n == len(self._data)
def WriteResponse(self):
print(len(self._swaps))
for swap in self._swaps:
print(swap[0], swap[1]... |
"""Class that is responsible for building and assessing proposed.
bonding patterns.
"""
import operator
from typing import List, Optional
import numpy as np
from smu import dataset_pb2
from smu.parser import smu_utils_lib
class MatchingParameters:
"""A class to specify optional matching parameters for SmuMolecule.... |
"""Copyright 2008 Orbitz WorldWide
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 applicable law or agreed to in writing, software
di... |
import time
def current_millis():
return int(round(time.time() * 1000)) |
import mock
import openstack.common.context
from openstack.common.middleware import context
from openstack.common import test
class ContextMiddlewareTest(test.BaseTestCase):
def test_process_request(self):
req = mock.Mock()
app = mock.Mock()
options = mock.MagicMock()
ctx = mock.sent... |
import unittest
import config_test
from backupcmd.commands import backupCommands
class BackupCommandsTestCase(unittest.TestCase):
"""Test commands passed to main script"""
def test_hyphen_r_option(self):
print 'Pending BackupCommandsTestCase'
self.assertEqual(1,1) |
"""
Simulate DSR over a network of nodes.
Revision Info
=============
* $LastChangedBy: mandke $
* $LastChangedDate: 2011-10-26 21:51:40 -0500 (Wed, 26 Oct 2011) $
* $LastChangedRevision: 5314 $
:author: Ketan Mandke <kmandke@mail.utexas.edu>
:copyright:
Copyright 2009-2011 The University of Texas at Austin
Lic... |
class Customer:
def __init__(self, firstname, lastname, country, address, postcode, city, email, phone, password):
self.firstname = firstname
self.lastname = lastname
self.country = country
self.address = address
self.postcode = postcode
self.city= city
self.e... |
import copy
import datetime
import json
import logging
import subprocess
import sys
import warnings
from email.mime.text import MIMEText
from email.utils import formatdate
from smtplib import SMTP
from smtplib import SMTP_SSL
from smtplib import SMTPAuthenticationError
from smtplib import SMTPException
from socket impo... |
# coding=utf-8
def get(ar,index):
l=len(ar);
if index<0:
return ar[l+index];
else:
return ar[index];
def find(ar,filter):
for r in ar:
if filter(r):
return r;
return None;
def execute(ar,filter,action):
for r in ar:
if filter(r):
action(r);
unabled=[户型图存储方案,户型图存储,安居客户型列表,安居客评价,安居客楼盘详情,相册存储方案,安居客相册]... |
import datetime
import hashlib
import json
import logging as std_logging
import os
import urllib
from eventlet import greenthread
from time import strftime
from time import time
from requests import HTTPError
from oslo_config import cfg
from oslo_log import helpers as log_helpers
from oslo_log import log as logging
fro... |
"""
Predict labels using trained ML models. Use average probability ensemble.
"""
__author__ = 'bshang'
import numpy as np
import pandas as pd
from sklearn import preprocessing
from sklearn.externals import joblib
def convert_label_to_array(str_label):
str_label = str_label.split(' ')
return [int(x) for x in st... |
import re
from models.contact import Contact
def test_all_contacts_on_homepage(app, db):
if app.contact.count() == 0:
app.contact.add(Contact(first_name="Mister", last_name="Muster", mobile_phone="123", email_1="test@test.com"))
contacts_from_homepage = sorted(app.contact.get_contact_list(), key = Conta... |
"""Shared class to maintain Plex server instances."""
import logging
import ssl
import time
from urllib.parse import urlparse
from plexapi.client import PlexClient
from plexapi.exceptions import BadRequest, NotFound, Unauthorized
import plexapi.myplex
import plexapi.playqueue
import plexapi.server
from requests import ... |
"""Dense Prediction Cell class that can be evolved in semantic segmentation.
DensePredictionCell is used as a `layer` in semantic segmentation whose
architecture is determined by the `config`, a dictionary specifying
the architecture.
"""
from __future__ import absolute_import
from __future__ import division
from __fut... |
import asyncore, socket, logging, time, asynchat, os
from hdfs_space_common import get_tree_from_cache, get_child_node, TreeNode
FORMAT = '%(asctime)-15s: %(levelname)s %(module)s - %(funcName)s: %(message)s'
logging.basicConfig(format=FORMAT, level=logging.WARNING)
class ChatHandler(asynchat.async_chat):
def __init__... |
from nltk.tokenize import sent_tokenize,word_tokenize
from nltk.corpus import stopwords
from collections import defaultdict
from string import punctuation
from heapq import nlargest
import re
"""
Modified from http://glowingpython.blogspot.co.uk/2014/09/text-summarization-with-nltk.html
"""
class FrequencySummarizer:
... |
"""A fast, lightweight IPv4/IPv6 manipulation library in Python.
This library is used to create/poke/manipulate IPv4 and IPv6 addresses
and networks.
"""
__version__ = 'trunk'
import struct
class AddressValueError(ValueError):
"""A Value Error related to the address."""
class NetmaskValueError(ValueError):
"""A... |
directory = ''
text_file = directory + 'billtext_org.json'
labels_file = directory + 'train.json'
output_dir = '/Users/katya/datasets/congress_bills_2/'
import sys
def skip_ahead_n_quotes(line, char_counter, maximum):
quote_counter = 0
while quote_counter < maximum:
if line[char_counter:char... |
"""Create a Python package of the Linux guest environment."""
import glob
import sys
import setuptools
install_requires = ['setuptools']
if sys.version_info < (3, 0):
install_requires += ['boto']
if sys.version_info >= (3, 7):
install_requires += ['distro']
setuptools.setup(
author='Google Compute Engine Team',... |
from webapp.web import Application
from handlers.index import IndexHandler
from handlers.register import RegisterHandler
from handlers.user import UserHandler
from handlers.signin import SigninHandler
from handlers.signout import SignoutHandler
from handlers.upload import UploadHandler
from handlers.avatar import Avata... |
from __future__ import print_function
import argparse
from os import path, environ
from subprocess import check_output, CalledProcessError
from sys import stderr
parser = argparse.ArgumentParser()
parser.add_argument('--repository', help='maven repository id')
parser.add_argument('--url', help='maven repository url')
p... |
import datetime
import faulthandler
import logging
import os
import signal
import sys
import threading
import traceback
from contextlib import contextmanager
from typing import Callable, Iterator, Optional
import setproctitle
from pants.base.exiter import Exiter
from pants.util.dirutil import safe_mkdir, safe_open
from... |
"""
Add compatibility for gevent and multiprocessing.
Source based on project GIPC 0.6.0
https://bitbucket.org/jgehrcke/gipc/
"""
import os, sys, signal, multiprocessing, multiprocessing.process, multiprocessing.reduction
gevent=None
geventEvent=None
def _tryGevent():
global gevent, geventEvent
if gevent and geve... |
import pytest
import math
import io
import time
import base64
import hashlib
from http import client
from unittest import mock
import aiohttpretty
from waterbutler.core import streams
from waterbutler.core import metadata
from waterbutler.core import exceptions
from waterbutler.core.path import WaterButlerPath
from wat... |
__author__ = 'mark'
"""
User Profile Extension based on One-to-One fields code in Django Docs here:
https://docs.djangoproject.com/en/1.7/topics/auth/customizing/
"""
from django.db import models
from django.contrib.auth.models import User
from uuid import uuid4
class Member(models.Model):
user = models.OneToOneFie... |
from threading import Timer
from oslo_log import log as logging
from networking_vsphere._i18n import _LI
from networking_vsphere.utils.rpc_translator import update_rules
from neutron.agent import securitygroups_rpc
LOG = logging.getLogger(__name__)
class DVSSecurityGroupRpc(securitygroups_rpc.SecurityGroupAgentRpc):
... |
"""
main.py
The entry point for the book reader application.
"""
__version_info__ = (0, 0, 1)
__version__ = '.'.join(map(str, __version_info__))
__author__ = "c.guenther@mac.com"
import time
import sqlite3
import pdb
import signal
import sys, os
import rfid
import config
import RPi.GPIO as GPIO
from player import Playe... |
from ..user_namespaces import UserNamespaces
from ...parsers.cmdline import CmdLine
from ...parsers.grub_conf import Grub2Config
from ...tests import context_wrap
ENABLE_TOK_A = '''
user_namespaces.enable=1
'''.strip() # noqa
ENABLE_TOK_B = '''
user-namespaces.enable=1
'''.strip() # noqa
CMDLINE = '''
BOOT_IMAGE=/vml... |
import mock
from solum.api import auth
from solum.api.handlers import assembly_handler
from solum.common import exception
from solum.common import repo_utils
from solum.objects import assembly
from solum.openstack.common.fixture import config
from solum.tests import base
from solum.tests import fakes
from solum.tests i... |
"""
Copyright 2013 OpERA
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 applicable law or agreed to in writing, software
... |
'''
Created on 2015年3月12日
@author: wanhao01
'''
import os
class SpiderFileUtils(object):
'''
deal with file related operations.
'''
def __save_page(self, data, url, outputdir):
'''
save the page content with the specific url to the local path.
'''
if(not os.path.exists(ou... |
"""Configment interface
>>> class TestCfg(Configment):
... CONFIGSPEC_SOURCE = '''
... [abc]
... x = integer(default=3)
... '''
>>> cfg = TestCfg()
>>> cfg["abc"]["x"]
3
>>>
"""
import os
import validate
import six
from .configobj_wrap import ConfigObjWrap
from .meta_configment import MetaConfigment
fr... |
"""Example training a memory neural net on the bAbI dataset.
References Keras and is based off of https://keras.io/examples/babi_memnn/.
"""
from __future__ import print_function
from tensorflow.keras.models import Sequential, Model, load_model
from tensorflow.keras.layers import Embedding
from tensorflow.keras.layers ... |
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import division
"""
TR-55 Model Implementation
A mapping between variable/parameter names found in the TR-55 document
and variables used in this program are as follows:
* `precip` is referred to as P in the report
* `runoff`... |
'''
Kurgan AI Web Application Security Analyzer.
http://www.kurgan.com.br/
Author: Glaudson Ocampos - <glaudson@vortexai.com.br>
Created in May, 11th 2016.
'''
import db.db as db
import config as cf
class WebServer(object):
banner = None
os = None
server = None
framework = None
version = None
op... |
from django.db import models
from django.utils.translation import ugettext_lazy as _
class MeetingType(object):
def __init__(self,code,descr):
self.code = code
self.description = descr
def __str__(self):
return '%s'%self.description
def __unicode__(self):
return self.descript... |
import mock
from oslo_serialization import jsonutils
from magnum.conductor import k8s_monitor
from magnum.conductor import mesos_monitor
from magnum.conductor import monitors
from magnum.conductor import swarm_monitor
from magnum import objects
from magnum.tests import base
from magnum.tests.unit.db import utils
class ... |
import copy
from deckhand.db.sqlalchemy import api as db_api
from deckhand.tests import test_utils
from deckhand.tests.unit.db import base
class TestRevisionDiffing(base.TestDbBase):
def _verify_buckets_status(self, revision_id, comparison_revision_id,
expected):
# Verify that... |
"""Unit tests to cover CampaignTargetService."""
__author__ = 'api.sgrinberg@gmail.com (Stan Grinberg)'
import os
import sys
sys.path.insert(0, os.path.join('..', '..', '..'))
import unittest
from adspygoogle.common import Utils
from tests.adspygoogle.adwords import HTTP_PROXY
from tests.adspygoogle.adwords import SERV... |
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 'BadgeByCourse.title_en'
db.add_column('badges_badgebycourse', 'title_en',
self.gf('django.db.mode... |
import numpy as np
import matplotlib.pyplot as plt
def readmesh(fname):
"""
input
-----
fname: string
gmsh file name
output
------
V: array
vertices
E: array
element ids
"""
import gmsh
mesh = gmsh.Mesh()
mesh.read_msh(fname... |
CAMERA_MODE_PHOTO2 = 100
CAMERA_MODE_PHOTO = 0
CAMERA_MODE_FACE_BEAUTY = 1
CAMERA_MODE_PANORAMA = 2
CAMERA_MODE_SELF_WIDEVIEW = 3
CAMERA_MODE_SCENE_FRAME = 4
CAMERA_MODE_GESTURE_SHOT = 5
CAMERA_MODE_LIVE_PHOTO = 6
CAMERA_MODE_VIDEO = 7
CAMERA_MODE_PROFESSIONAL = 8
CAMERA_MODE_NIGHTSHOT = 9
CAMERA_MODE_PIP = 10
CAMERA_M... |
"""
This module, problem_019.py, solves the nineteenth project euler problem.
"""
from project_euler_problems.problem import Problem
from datetime import date
'''
You are given the following information, but you may prefer to do some research for yourself.
1 Jan 1900 was a Monday.
Thirty days has September,
April, June... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.