code stringlengths 1 199k |
|---|
import traceback
from ckan.lib.helpers import json
from ckanext.harvest.model import HarvestObject, HarvestObjectExtra
from ckanext.harvest.harvesters import HarvesterBase
from ckanext.geocat.utils import search_utils, csw_processor, ogdch_map_utils, csw_mapping # noqa
from ckanext.geocat.utils.vocabulary_utils import... |
{
'name': 'l10n_ar_account_check_sale',
'version': '1.0',
'summary': 'Venta de cheques de terceros',
'description': """
Cheques
==================================
Venta de cheques de terceros.
""",
'author': 'OPENPYME S.R.L.',
'website': 'http://www.openpyme.com.ar',
'category': 'Acc... |
from ddd.logic.learning_unit.builder.effective_class_identity_builder import EffectiveClassIdentityBuilder
from ddd.logic.learning_unit.commands import GetEffectiveClassCommand
from ddd.logic.learning_unit.domain.model.effective_class import EffectiveClass
from ddd.logic.learning_unit.repository.i_effective_class impor... |
import logging
from lxml import etree
from pkg_resources import resource_string
from xmodule.raw_module import RawDescriptor
from .x_module import XModule
from xblock.core import Integer, Scope, String, List, Float, Boolean
from xmodule.open_ended_grading_classes.combined_open_ended_modulev1 import CombinedOpenEndedV1M... |
from copy import deepcopy
from xml.sax.saxutils import escape
from lxml import etree as ElementTree
from odoo import SUPERUSER_ID, api
def _merge_views(env, xmlids):
old_view_ids = env["ir.ui.view"].search(
[("key", "in", xmlids), ("active", "=", True)]
)
# Get only the edited version of the views (... |
'''Test cases for QtMultimediaWidgets'''
import unittest
from helper import UsesQApplication
from PySide2.QtMultimediaWidgets import QGraphicsVideoItem, QVideoWidget
from PySide2.QtWidgets import QGraphicsScene, QGraphicsView, QVBoxLayout, QWidget
from PySide2.QtCore import QTimer
class MyWidget(QWidget):
def __ini... |
'''Simplified reimplementation of the gpioset tool in Python.'''
import gpiod
import sys
if __name__ == '__main__':
if len(sys.argv) < 3:
raise TypeError('usage: gpioset.py <gpiochip> <offset1>=<value1> ...')
with gpiod.Chip(sys.argv[1]) as chip:
offsets = []
values = []
for arg ... |
"""LDAP protocol proxy server"""
from twisted.internet import reactor, defer
from ldaptor.protocols.ldap import ldapserver, ldapconnector, ldapclient
from ldaptor.protocols import pureldap
class Proxy(ldapserver.BaseLDAPServer):
protocol = ldapclient.LDAPClient
client = None
waitingConnect = []
unbound ... |
import sys
import os
import subprocess as ssubprocess
_p = None
def start_syslog():
global _p
with open(os.devnull, 'w') as devnull:
_p = ssubprocess.Popen(
['logger', '-p', 'daemon.notice', '-t', 'sshuttle'],
stdin=ssubprocess.PIPE,
stdout=devnull,
stderr... |
import urllib2
import re
JIRA_URL='https://bugreports.qt-project.org/browse'
class JIRA:
__instance__ = None
# Helper class
class Bug:
CREATOR = 'QTCREATORBUG'
SIMULATOR = 'QTSIM'
SDK = 'QTSDK'
QT = 'QTBUG'
QT_QUICKCOMPONENTS = 'QTCOMPONENTS'
# constructor of JIRA... |
from sys import platform, exec_prefix
from distutils.core import setup, Extension
if platform == "win32":
libmaxent_name = 'libmaxent'
extra_compile_args = [
"-DWIN32",
"-DPYTHON_MODULE",
"-DHAVE_FORTRAN=1",
"-DBOOST_DISABLE_THREADS",
"-DBOOS... |
import unittest
import re
import time
import sys
import liblo
def approx(a, b, e = 0.0002):
return abs(a - b) < e
def matchHost(host, regex):
r = re.compile(regex)
return r.match(host) != None
class Arguments:
def __init__(self, path, args, types, src, data):
self.path = path
self.args =... |
'''
Often used utility functions
Copyright 2020 by Massimo Del Fedele
'''
import sys
import uno
from com.sun.star.beans import PropertyValue
from datetime import date
import calendar
import PyPDF2
'''
ALCUNE COSE UTILI
La finestra che contiene il documento (o componente) corrente:
desktop.CurrentFrame.ContainerWind... |
import os, sys
def open_in_browser(link):
browser = os.environ.get('BROWSER', 'firefox')
child = os.fork()
if child == 0:
# We are the child
try:
os.spawnlp(os.P_NOWAIT, browser, browser, link)
os._exit(0)
except Exception, ex:
print >>sys.stderr, "Error", ex
os._exit(1)
os.waitpid(child, 0) |
inp = 0
outp = 1
parameters = dict() #parametriseerbare cell
properties = {'Device ID': ' 0x01', 'Channel [0/1]': ' 0', 'name': 'epos_areadBlk'} #voor netlisten
iconSource = 'AD'
views = {'icon':iconSource} |
import json
import maps
import traceback
from requests import get
from requests import post
from requests import put
from tendrl.commons.utils import log_utils as logger
from tendrl.monitoring_integration.grafana import constants
from tendrl.monitoring_integration.grafana import exceptions
from tendrl.monitoring_integr... |
from spack import *
import glob
import os.path
class Xbraid(MakefilePackage):
"""XBraid: Parallel time integration with Multigrid"""
homepage = "https://computing.llnl.gov/projects/parallel-time-integration-multigrid/software"
url = "https://github.com/XBraid/xbraid/archive/v2.2.0.tar.gz"
version('... |
import os
import six
from gi.repository import BlockDev as blockdev
from ..devicelibs import mdraid, raid
from .. import errors
from .. import util
from ..flags import flags
from ..storage_log import log_method_call
from .. import udev
from ..size import Size
import logging
log = logging.getLogger("blivet")
from .stora... |
""" Data filter converting CSTBox v2 event logs to v3 format.
Usage: ./cbx-2to3.py < /path/to/input/file > /path/to/output/file
"""
__author__ = 'Eric Pascual - CSTB (eric.pascual@cstb.fr)'
import fileinput
import json
for line in fileinput.input():
ts, var_type, var_name, value, data = line.split('\t')
# next ... |
from typing import Callable, Any
from ..model import MetaEvent, Event
from ..exceptions import PropertyStatechartError
__all__ = ['InternalEventListener', 'PropertyStatechartListener']
class InternalEventListener:
"""
Listener that filters and propagates internal events as external events.
"""
def __ini... |
'''
Created on Jan 6, 2018
@author: consultit
'''
from panda3d.core import Filename
import sys, os
from subprocess import call
currdir = os.path.abspath(sys.path[0])
builddir = Filename.from_os_specific(os.path.join(currdir, '/ely/')).get_fullpath()
elydir = Filename.fromOsSpecific(os.path.join(currdir, '/ely/')).getFu... |
""" Barcode Creation (PDF417)
"""
import os
basedir = os.path.split(__file__)[0]
bcdelib = os.path.join(basedir, 'psbcdelib.ps')
class Barcode(object):
__lib__ = open(bcdelib, 'r').read()
@property
def ps(self):
raise NotImplementedError
@property
def eps(self):
raise NotImplementedE... |
import pytest
from forte.solvers import solver_factory, HF
def test_df_rhf():
"""Test DF-RHF on HF."""
ref_energy = -100.04775218911111
# define a molecule
xyz = """
H 0.0 0.0 0.0
F 0.0 0.0 1.0
"""
# create a molecular model
input = solver_factory(molecule=xyz, basis='cc-pVTZ', int_t... |
import time
import sys
def sizeof_fmt(num, unit='B'):
# source: http://stackoverflow.com/questions/1094841/reusable-library-to-get-human-readable-version-of-file-size
for uprexif in ['', 'Ki', 'Mi', 'Gi', 'Ti', 'Pi', 'Ei', 'Zi']:
if abs(num) < 1024.0:
return "{:3.2f} {}{}".format(num, uprexi... |
from ctypes import*
import math
lib = cdll.LoadLibrary("Z:\\Documents\Projects\\SWMMOpenMIComponent\\Source\\SWMMOpenMIComponent\\bin\\Debug\\SWMMComponent.dll")
print(lib)
print("\n")
finp = b"Z:\\Documents\\Projects\\SWMMOpenMIComponent\\Source\\SWMMOpenMINoGlobalsPythonTest\\test.inp"
frpt = b"Z:\\Documents\\Projec... |
import pytest
import importlib
from mpi4py import MPI
from spectralDNS import config, get_solver, solve
from TGMHD import initialize, regression_test, pi
comm = MPI.COMM_WORLD
if comm.Get_size() >= 4:
params = ('uniform_slab', 'nonuniform_slab',
'uniform_pencil', 'nonuniform_pencil')
else:
params ... |
"""
Sample a specific geometry or set of geometries.
"""
import numpy as np
import nomad.core.glbl as glbl
import nomad.core.trajectory as trajectory
import nomad.core.log as log
def set_initial_coords(wfn):
"""Takes initial position and momentum from geometry specified in input"""
coords = glbl.properties['ini... |
"""
:copyright:
Wenjie Lei (lei@princeton.edu), 2016
:license:
GNU General Public License, Version 3
(http://www.gnu.org/copyleft/gpl.html)
"""
from __future__ import (absolute_import, division, print_function) # NOQA
from .adjoint_source import calculate_adjsrc_on_stream # NOQA
from .adjoint_... |
from common.db_sum import _metric_meta_db
'''get the data from table by name'''
def get_data_by_name(name, status=[1], other=0):
result = []
where = ''
if status:
status = ",".join([str(x) for x in status])
where += ' and status in ({}) '.format(status)
if other:
where += ' and i... |
from rapidsms.tests.scripted import TestScript
from apps.form.models import *
from apps.reporters.models import *
import apps.reporters.app as reporter_app
import apps.supply.app as supply_app
import apps.form.app as form_app
import apps.default.app as default_app
from app import App
from django.core.management.command... |
'''
This file is part of GEAR_mc.
GEAR_mc is a fork of Jeremie Passerin's GEAR project.
GEAR is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at y... |
from test_methods import TestBaseFeedlyClass |
"""
Created on 2013-12-16
@author: readon
@copyright: reserved
@note: CustomWidget example for mvp
"""
from gi.repository import Gtk
from gi.repository import GObject
class CustomEntry(Gtk.Entry):
"""
custom widget inherit from gtkentry.
"""
def __init__(self):
Gtk.Entry.__init__(self)
p... |
import hashlib
import io
import struct
BLOCK_LENGTH = 1024 * 1024
try:
file_types = (file, io.IOBase)
except NameError:
file_types = (io.IOBase,)
def read_int(stream, length):
try:
return struct.unpack('<I', stream.read(length))[0]
except Exception:
return None
class HashedBlockIO(io.Byt... |
from odoo import models, fields, api
class AccessGroups(models.Model):
_inherit = 'muk_security.access_groups'
#----------------------------------------------------------
# Database
#----------------------------------------------------------
directories = fields.Many2many(
comodel_name='muk_... |
"""
-----------------------------------------------------------------------------
This source file is part of OSTIS (Open Semantic Technology for Intelligent Systems)
For the latest info, see http://www.ostis.net
Copyright (c) 2010 OSTIS
OSTIS is free software: you can redistribute it and/or modify
it under the terms... |
import logging
from odoo import api, conf
from odoo.tests.common import HttpCase, tagged
_logger = logging.getLogger(__name__)
@tagged("post_install", "-at_install")
class TestProductTmplImage(HttpCase):
def _get_original_image_url(self, px=1024):
return "https://upload.wikimedia.org/wikipedia/commons/thumb... |
from optparse import OptionParser
import sys
class CLI(object):
color = {
"PINK": "",
"BLUE": "",
"CYAN": "",
"GREEN": "",
"YELLOW": "",
"RED": "",
"END": "",
}
@staticmethod
def show_colors():
CLI.color = {
"PINK": "\033[35m",
... |
from django.db import models
class Channel(models.Model):
channel_id = models.CharField(max_length=50, unique=True)
channel_name = models.CharField(max_length=50, null=True, blank=True)
rtmp_url = models.CharField(max_length=100, null=True, blank=True)
active = models.IntegerField(null=True, blank=True)... |
from __future__ import annotations
from decimal import Decimal
from typing import (
Any,
Mapping,
Sequence,
)
import uuid
from pprint import pprint
import pytest
from ai.backend.common.docker import ImageRef
from ai.backend.common.types import (
AccessKey, AgentId, KernelId,
ResourceSlot, SessionTyp... |
"""Statistics analyzer for HotShot."""
import profile
import pstats
import hotshot.log
from hotshot.log import ENTER, EXIT
def load(filename):
return StatsLoader(filename).load()
class StatsLoader:
def __init__(self, logfn):
self._logfn = logfn
self._code = {}
self._stack = []
se... |
__all__ = [
'Charset',
'add_alias',
'add_charset',
'add_codec']
import codecs
import email.base64mime
import email.quoprimime
from email import errors
from email.encoders import encode_7or8bit
QP = 1
BASE64 = 2
SHORTEST = 3
MISC_LEN = 7
DEFAULT_CHARSET = 'us-ascii'
CHARSETS = {'iso-8859-1': (
QP, QP... |
import sys
from ivy import hooks, site, templates
try:
import jinja2
except ImportError:
jinja2 = None
env = None
if jinja2:
# Initialize our Jinja environment on the 'init' event hook.
@hooks.register('init')
def init():
# Initialize a template loader.
settings = {
'load... |
import random
def turn(board, symbol):
while 1:
x = random.choice(range(8))
y = random.choice(range(8))
if getboard(board,x,y) == '#': return (x,y) |
import re
import json
import xml.etree.ElementTree
from .common import InfoExtractor
from ..utils import (
ExtractorError,
find_xpath_attr,
unified_strdate,
determine_ext,
get_element_by_id,
compat_str,
)
class ArteTvIE(InfoExtractor):
_VIDEOS_URL = r'(?:http://)?videos.arte.tv/(?P<lang>fr|d... |
import sys
line = sys.stdin.readline() # skip the header
line = sys.stdin.readline()
all = {}
while line:
v = line.split()
if v[0] not in all:
all[v[0]] = set()
all[v[0]].add(v[1])
line = sys.stdin.readline()
s = [k for (_, k) in sorted([(len(v), k) for (k,v) in all.items()])]
print ' '.join(rev... |
"""TestSuite"""
import sys
from . import case
from . import util
__unittest = True
def _call_if_exists(parent, attr):
func = getattr(parent, attr, lambda : None)
func()
class BaseTestSuite(object):
"""A simple test suite that doesn't provide class or module shared fixtures.
"""
def __init__(self, te... |
from google.analytics import data_v1beta
async def sample_batch_run_pivot_reports():
# Create a client
client = data_v1beta.BetaAnalyticsDataAsyncClient()
# Initialize request argument(s)
request = data_v1beta.BatchRunPivotReportsRequest(
)
# Make the request
response = await client.batch_ru... |
"""
This module, debugging.py, will contain code related to debugging (such as printing error messages).
"""
class MyException(Exception):
"""
Just something useful to have to throw some of my own custom exception.
"""
pass
class ParameterException(Exception):
"""
A custom exception for when a function receives b... |
"""Tests for the kraken sensor platform."""
from datetime import timedelta
from unittest.mock import patch
from pykrakenapi.pykrakenapi import KrakenAPIError
from homeassistant.components.kraken.const import (
CONF_TRACKED_ASSET_PAIRS,
DEFAULT_SCAN_INTERVAL,
DEFAULT_TRACKED_ASSET_PAIR,
DOMAIN,
)
from ho... |
"""
pluginconf.d configuration file - Files
=======================================
Shared mappers for parsing and extracting data from
``/etc/yum/pluginconf.d/*.conf`` files. Parsers contained
in this module are:
PluginConfD - files ``/etc/yum/pluginconf.d/*.conf``
---------------------------------------------------
P... |
from cobra.core.loading import get_model
from cobra.core import json
class UserConfig(object):
default_config = {
'guide.task.participant': '1',
'guide.document.share': '1',
'guide.customer.share': '1',
'guide.workflow.operation': '1',
'guide.workflow.createform': '1',
... |
""" Example code about how to run raw_file_io
python3 -m vispek.examples.run_raw_file_io \
--in_path /Users/huaminli/Downloads/data \
--out_path /Users/huaminli/Desktop/vispek/data
"""
import argparse
from vispek.lib.io.raw_file_io import RawFileIO
def run_file_io(args):
my_file_io = RawFileIO(args.... |
import datetime
from sqlalchemy import UniqueConstraint
from sqlalchemy.dialects.postgresql import JSONB
from pns.app import app, db
class SerializationMixin():
"""serialization mixin for sqlalchemy model object
"""
def to_dict(self, *exceptions, **extra_payload):
"""get dict representation of the o... |
import ditagen.dita
from ditagen.dtdgen import Particle as Particle
from ditagen.dtdgen import Choice as Choice
from ditagen.dtdgen import Name as Name
from ditagen.dtdgen import Seq as Seq
from ditagen.dtdgen import Attribute as Attribute
from ditagen.dtdgen import Param as Param
from ditagen.dtdgen import ParameterEn... |
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('webcore', '0016_profile_emails'),
]
operations = [
migrations.RemoveField(
model_name='profile',
name='emails',
),
] |
from distutils.core import setup
PKGLIST = ['gearman_geodis']
setup(name='gearman-geodis',
version='1.0.0',
description='Geolocation Gearman worker powered by Geodis',
author_email='engineering@shazamteam.com',
license='Apache License, Version 2.0',
packages=PKGLIST,
scripts=['gearma... |
from distutils.core import setup
from src import __version__
setup(
name="irma.common",
version=__version__,
author="Quarkslab",
author_email="irma@quarkslab.com",
description="The common component of the IRMA software",
packages=["irma.common",
"irma.common.base",
"i... |
import hashlib
import random
from rest_framework import serializers
from sita.users.models import User
from sita.subscriptions.models import Subscription
from sita.utils.refresh_token import create_token
from hashlib import md5
from datetime import datetime, timedelta
import pytz
class LoginSerializer(serializers.Seria... |
import cProfile
from scipy.stats import norm
def profile(func):
def profiled_func(*args, **kwargs):
p = cProfile.Profile()
try:
p.enable()
result = func(*args, **kwargs)
p.disable()
return result
finally:
p.print_stats()
return ... |
import sys
import numpy as np
from normalization import tokenize
from helpers import ahash
class KerasVectorizer():
'''
Convert list of documents to numpy array for input into Keras model
'''
def __init__(self, n_features=100000, maxlen=None, maxper=100, hash_function=ahash):
self.maxlen = m... |
from ansible.module_utils.basic import AnsibleModule
import git
import itertools
import multiprocessing
import os
import signal
import time
DOCUMENTATION = """
---
module: git_requirements
short_description: Module to run a multithreaded git clone
options:
repo_info:
description:
- List of repo information ... |
import configparser
import io
import os
import subprocess
from rally.common import logging
from rally.utils import encodeutils
LOG = logging.getLogger(__name__)
def check_output(*args, **kwargs):
"""Run command with arguments and return its output.
If the exit code was non-zero it raises a CalledProcessError. T... |
import pytest
import gen.template
from gen.template import (For, Replacement, Switch, Tokenizer, UnsetParameter,
parse_str)
just_text = "foo"
more_complex_text = "foo {"
def get_tokens(str):
return Tokenizer(str).tokens
def test_lex():
assert(get_tokens("foo") == [("blob", "foo"), ("eo... |
"""Flask Blueprint adding login functionality to our app. Note that we expect
gluten model and db config to be handled elsewhere
"""
import sys
import traceback
from functools import partial, wraps
from flask import redirect, request, flash, session, abort, g, url_for
from flask.globals import LocalProxy, _lookup_app_o... |
from .tables import (
BatchCreateRowsRequest,
BatchCreateRowsResponse,
BatchDeleteRowsRequest,
BatchUpdateRowsRequest,
BatchUpdateRowsResponse,
ColumnDescription,
CreateRowRequest,
DeleteRowRequest,
GetRowRequest,
GetTableRequest,
GetWorkspaceRequest,
LabeledItem,
Lis... |
import json
import re
import tg
import pkg_resources
import pylons
pylons.c = pylons.tmpl_context
pylons.g = pylons.app_globals
from pylons import c
from ming.orm import ThreadLocalORMSession
from datadiff.tools import assert_equal
from allura import model as M
from allura.lib import helpers as h
from allura.tests impo... |
from oslo_config import cfg
from oslo_utils import importutils
import webob
from neutron._i18n import _
from neutron.api import extensions
from neutron.api.v2 import attributes
from neutron.api.v2 import base
from neutron.api.v2 import resource
from neutron.common import constants as const
from neutron.common import ex... |
from adt.util.prog import Prog
from adt.util.literal import Literal
from adt.util.expr import Expr
from adt.util.unary_op import Unary_op
from adt.util.binary_op import Binary_op
from adt.util.block import Block
from adt.util.context import Context
from adt.util.instr import Instr
from adt.types.bool import Bool
from a... |
import random
import time
import mock
from mox3 import mox
from os_xenapi.client import XenAPI
from nova.compute import utils as compute_utils
from nova import context
from nova import exception
from nova.tests.unit.virt.xenapi import stubs
from nova.virt.xenapi import driver as xenapi_conn
from nova.virt.xenapi import... |
"""
This module defines the Connection class.
"""
from __future__ import unicode_literals
from __future__ import print_function
from future import standard_library
standard_library.install_aliases()
from builtins import object
import requests
import logging
class Connection(object):
""" Creates a connection to Spac... |
import Utils
from Utils import printe
class CommandBuilder(object):
def __init__(self, *command_args):
self.command_args = list(command_args)
def append(self, *args):
for arg in args:
if isinstance(arg, str):
self.command_args += [arg]
elif isinstance(arg,... |
import copy
import os
import re
import socket
import sys
import tempfile
from datetime import datetime
from subprocess import CalledProcessError
from subprocess import check_output, STDOUT
import termios
import json
import logging
from pprint import pformat
import yaml
from deepdiff import DeepDiff
LOCAL_IP_ENV = "MY_I... |
python manage.py collectstatic
python manage.py runserver --nostatic
urlpatterns += patterns('',
(r'^static/suit/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.DJANGO_SUIT_TEMPLATE}),
)
urlpatterns += patterns('',
(r'^static/admin/(?P<path>.*)$', 'django.views.static.serve', {'document_... |
from __future__ import absolute_import
from importlib import import_module
import logging
import os
import sys
import click
from colorlog import ColoredFormatter
logger = logging.getLogger(__name__)
def setup_logging(): # pragma: no cover
root_logger = logging.getLogger()
root_logger.setLevel(logging.INFO)
... |
import json
import tempfile
import fixtures
from lxml import etree
from oslo_config import cfg
import requests
import testtools
from testtools import content as test_content
from testtools import matchers
import urllib.parse as urlparse
from os_collect_config import cfn
from os_collect_config import collect
from os_col... |
import streamcorpus as sc
import cuttsum.events
import cuttsum.corpora
from cuttsum.trecdata import SCChunkResource
from cuttsum.pipeline import ArticlesResource, DedupedArticlesResource
import os
import pandas as pd
from datetime import datetime
from collections import defaultdict
import matplotlib.pylab as plt
plt.st... |
import netaddr
import testtools
from tempest.api.compute import base
from tempest.common.utils import data_utils
from tempest.common.utils.linux import remote_client
from tempest.common import waiters
from tempest import config
from tempest import test
CONF = config.CONF
class ServersTestJSON(base.BaseV2ComputeTest):
... |
"""Tests for hparams_lib."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from classifaedes import hparams_lib
import tensorflow.compat.v1 as tf
class HparamsLibTest(tf.test.TestCase):
def testIndentedSerialize(self):
"""Tests that our slightly custo... |
import config
print 'Status: 302 Found'
print 'Location: http://' + config.custom_url
print '' |
from paypalrestsdk import BillingAgreement
import logging
BILLING_AGREEMENT_ID = "I-HT38K76XPMGJ"
try:
billing_agreement = BillingAgreement.find(BILLING_AGREEMENT_ID)
print("Billing Agreement [%s] has state %s" % (billing_agreement.id, billing_agreement.state))
suspend_note = {
"note": "Suspending t... |
"""Unit tests for the utility functions used by the placement API."""
import fixtures
from oslo_middleware import request_id
import webob
from nova.api.openstack.placement import microversion
from nova.api.openstack.placement import util
from nova import objects
from nova import test
from nova.tests import uuidsentinel... |
from .test_antivirus import AbstractTests
import modules.antivirus.avg.avg as module
import modules.antivirus.base as base
from mock import patch
from pathlib import Path
class TestAvg(AbstractTests.TestAntivirus):
name = "AVG AntiVirus Free (Linux)"
scan_path = Path("/usr/bin/avgscan")
scan_args = ('--heur... |
import unittest
import mock
class TestQuery(unittest.TestCase):
_PROJECT = 'PROJECT'
@staticmethod
def _get_target_class():
from google.cloud.datastore.query import Query
return Query
def _make_one(self, *args, **kw):
return self._get_target_class()(*args, **kw)
def _make_cli... |
from ._query import query |
import re
import sys
import socket
import libvirt
import argparse
import traceback
import jsonpickle
import subprocess
from xml.etree import ElementTree
VERSION = 'check_virsh_domains v1.0'
DOMAIN_STATES = {
0: 'None',
1: 'Running',
2: 'Blocked on resource',
3: 'Paused by user',
4: 'Being shut down'... |
import keystonemiddleware.audit as audit_middleware
from oslo_config import cfg
import oslo_middleware.cors as cors_middleware
import pecan
from ironic.api import config
from ironic.api.controllers import base
from ironic.api import hooks
from ironic.api import middleware
from ironic.api.middleware import auth_token
fr... |
import os
from oslo_policy import opts
from oslo_service import wsgi
from manila.common import config
CONF = config.CONF
def set_defaults(conf):
_safe_set_of_opts(conf, 'verbose', True)
_safe_set_of_opts(conf, 'state_path', os.path.abspath(
os.path.join(os.path.dirname(__file__),
'.... |
import contextlib
import copy
import os
import mock
from cinder import exception
from cinder.image import image_utils
from cinder import test
from cinder.volume.drivers import smbfs
class SmbFsTestCase(test.TestCase):
_FAKE_SHARE = '//1.2.3.4/share1'
_FAKE_MNT_BASE = '/mnt'
_FAKE_VOLUME_NAME = 'volume-4f711... |
"""Tests for tink.python.tink._keyset_reader."""
from typing import cast
from absl.testing import absltest
from tink.proto import tink_pb2
import tink
from tink import core
class JsonKeysetReaderTest(absltest.TestCase):
def test_read(self):
json_keyset = """
{
"primaryKeyId": 42,
"key"... |
import math
print("Digite os termos da equacao ax2+bx+c")
a = float(input("Digite o valor de A:\n"))
if(a==0):
print("Nao e uma equacao de segundo grau")
else:
b = float(input("Valor de B:\n"))
c = float(input("Valor de C:\n"))
delta = (math.pow(b,2) - (4*a*c))
if(delta<0):
print("A equacao ... |
"""
Copyright 2015 SYSTRAN Software, Inc. 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://www.apache.org/licenses/LICENSE-2.0
Unless required by ap... |
def load_GPS_EXIF(fname, python = True):
# Load sub-functions ...
from .load_GPS_EXIF1 import load_GPS_EXIF1
from .load_GPS_EXIF2 import load_GPS_EXIF2
# Check what the user wants ...
if python:
# Will use the Python module "exifread" ...
return load_GPS_EXIF1(fname)
else:
... |
'''
Copyright 2013 George Caley
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 writin... |
import inspect
import json
import os
import random
import subprocess
import time
import requests
import ast
import paramiko
import rancher
from rancher import ApiError
from lib.aws import AmazonWebServices
DEFAULT_TIMEOUT = 120
DEFAULT_MULTI_CLUSTER_APP_TIMEOUT = 300
CATTLE_TEST_URL = os.environ.get('CATTLE_TEST_URL', ... |
__author__ = 'mpetyx'
from tastypie.authorization import DjangoAuthorization
from .models import OpeniQuestion
from OPENiapp.APIS.OpeniGenericResource import GenericResource
from OPENiapp.APIS.OPENiAuthorization import Authorization
from OPENiapp.APIS.OPENiAuthentication import Authentication
class QuestionResource(Gen... |
"""
Views for managing Images and Snapshots.
"""
import logging
from django.utils.translation import ugettext_lazy as _
from horizon import api
from horizon import exceptions
from horizon import tables
from horizon import tabs
from .images.tables import ImagesTable
from .snapshots.tables import SnapshotsTable
from .vol... |
from cinder import context
from cinder import exception
from cinder.openstack.common import log as logging
from cinder import test
from cinder.volume.drivers.dell import dell_storagecenter_api
import mock
from requests import models
import uuid
LOG = logging.getLogger(__name__)
@mock.patch.object(dell_storagecenter_api... |
import click
@click.command('config', short_help='Display remote client config')
@click.pass_obj
def cli(obj):
"""Display client config downloaded from API server."""
for k, v in obj.items():
if isinstance(v, list):
v = ', '.join(v)
click.echo(f'{k:20}: {v}') |
import random
import sys
"""class schema:
files=[]
def __init__(self):
pass
def addFile(self,file):
self.files.append(file)
def setForeignKey(self,primaryFile,theOtherOne):
pass"""
class JoinReq:
def __init__(self,R,S,m,n,fing):
self.cost=0
self.first_req=True
self.cost = 0
tC,self.t1=R.getFirst(m)
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.