code stringlengths 1 199k |
|---|
import os
import re
import shlex
import subprocess
from SCons.Scanner import FindPathDirs
from SCons.Script import Action, Builder
def exists(env):
return env.Detect('cython')
def generate(env):
env.Tool('python')
env.SetDefault(CYTHONPATH=[])
env['BUILDERS']['Cython'] = Builder(
action=Action(
... |
from PyQt4.Qt import *
from Base import *
import AgentView
class ViewController(QObject):
"""
The bridge between view signals and the business logic.
"""
def __init__(self, parent = None):
QObject.__init__(self, parent)
def addView(self, view):
self.connect(QApplication.instance(), SIGNAL('testermanServerUpdat... |
"""
common XBMC Module
Copyright (C) 2011 t0mm0
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... |
import os
from sys import platform, exit, stderr
if platform == 'mac':
import MacOS
def time():
return MacOS.GetTicks() / 60.0
timekind = "real"
elif hasattr(os, 'times'):
def time():
t = os.times()
return t[0] + t[1]
timekind = "cpu"
else:
stderr.write(
"Don't know how to get time on platform %s\n" % rep... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import binascii
import json
import os
import time
import uuid
from contextlib import closing
from datetime import datetime
import pytest
from vdsm.common import concurrent
from vdsm.storage import managedvolumed... |
"""Test cds dojson album records."""
from __future__ import absolute_import
from invenio.testsuite import InvenioTestCase, make_test_suite, run_test_suite
CDS_ALBUM = """
<record>
<controlfield tag="001">2054964</controlfield>
<controlfield tag="003">SzGeCERN</controlfield>
<controlfield tag="005">20150928110024.... |
from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns(
'',
url(
r'^api/v1/',
include(
'liberator.urls',
)
),
url(
r'^api/v1/',
include(
'limbo.urls',
)
)... |
import os
import re
from os.path import abspath, dirname, isdir, join
PROJ_PATH = dirname(dirname(abspath(__file__)))
BOOK_PATH = os.path.join(PROJ_PATH, 'Book')
DIR_RE = re.compile(r'^(\d+)-(\S+)$')
FILE_RE = re.compile(r'^(\d+)\.(\d+)(?:\.(\d+))?_(\S+)\.cpp$')
SECTION_NAMES = {
(1, 1): 'Array Transformations',
... |
from ....const import GRAMPS_LOCALE as glocale
_ = glocale.translation.gettext
from .._matchesfilterbase import MatchesFilterBase
class MatchesFilter(MatchesFilterBase):
"""Rule that checks against another filter"""
name = _('Repositories matching the <filter>')
description = _("Matches repositories ... |
import server
from atlas import Operation, Entity
class StatusDeletable(server.Thing):
def status_property_update(self):
if self.get_prop_float('status') <= 0:
return Operation("delete", Entity(self.id), to=self) |
'''
cheguevara XBMC Addon
Copyright (C) 2014 lambda
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.
... |
'''
Mail handler for logging.
'''
import logging
import logging.handlers
import inspect
import os
import socket
import traceback
psutil = None
try:
import psutil
except (OSError, ImportError):
# We run into issues when trying to import psutil from inside mod_wsgi on
# rhel7. If we hit that here, then just ... |
"""
@author: AAron Walters
@license: GNU General Public License 2.0 or later
@contact: awalters@volatilesystems.com
@organization: Volatile Systems
Alias for all address spaces
"""
from rekall import registry
from rekall import utils
class Zeroer(object):
def __init__(self):
self.store = ... |
from __future__ import print_function
from Experiment import ImalseExperiment
from ImalsePureSimExperiment import ImalsePureSimExperiment
try:
from ImalseNetnsExperiment import ImalseNetnsExperiment
except:
print('NetnsExperiment cannot be imported') |
import ntpath
import time
import urllib.parse
import urllib.request
import xml.dom.minidom as xdmd
import trackma.utils as utils
from trackma.tracker import tracker
NOT_RUNNING = 0
ACTIVE = 1
CLAIMED = 2
PLAYING = 3
PAUSED = 4
IDLE = 5
class PlexTracker(tracker.TrackerBase):
name = 'Tracker (Plex)'
def __init__... |
import bpy
import os
import math
ops = bpy.ops
wm = ops.wm
objects = bpy.data.objects
context = bpy.context
scene = context.scene
build_dir = bpy.path.abspath("//") + "build"
obj_list = []
for obj in objects:
obj_name = obj.name
if obj_name.startswith("terrain") and not obj_name.endswith("_physics"):
ob... |
from m5.util import orderdict
from slicc.symbols.Symbol import Symbol
from slicc.symbols.Var import Var
import slicc.generate.html as html
import re
python_class_map = {
"int": "Int",
"NodeID": "Int",
"uint32_t" : "UInt32",
"std::string": "... |
from django.db import models
from django.utils.functional import cached_property
from pootle.core.exceptions import MissingPluginError, NotConfiguredError
from pootle_project.models import Project
from pootle_store.constants import POOTLE_WINS, SOURCE_WINS
from pootle_store.models import Store
from .delegate import fs_... |
import xcb.xproto
from window import Window
from window import XROOT
from atom import Atom
def dispatch(e):
NotifyModes = {
0: 'Normal', 1: 'Grab', 2: 'Ungrab', 3: 'WhileGrabbed'
}
NotifyDetails = {
0: 'Ancestor', 1: 'Virtual', 2: 'Inferior', 3: 'Nonlinear',
4: 'NonlinearVirtual', 5:... |
"""
This module acts like a laser.
Qudi 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.
Qudi is distributed in the hope that it will be usefu... |
import ez_setup
ez_setup.use_setuptools()
from setuptools import setup, find_packages
import sys
import askbot
setup(
name = "askbot",
version = askbot.get_version(),#remember to manually set this correctly
description = 'Question and Answer forum, like StackOverflow, written in python and Django',
pack... |
"""
file: tic_tac_toe.py
author: Jonathan Virgil O'Brien
Date: 9/1/13
Description: This python code draws a tic-tac-toe board with a 'valid' game
sequence. It draws the required image through reused functions
for the X's and O's, the grid is completed in one function. First
... |
from datetime import datetime, timedelta
from collections import OrderedDict
import calendar
import sys
from ecmwfapi import ECMWFDataServer
import time
from dateutil.relativedelta import *
start_time = time.time()
server = ECMWFDataServer()
def retrieve_interim(strtDate,endDate,latNorth,latSouth,lonEast,lonWest,grd,er... |
"""
plainbox.impl.exporter.test_html
================================
Test definitions for plainbox.impl.exporter.html module
"""
from io import StringIO
from string import Template
from unittest import TestCase
import io
from lxml import etree as ET
from pkg_resources import resource_filename
from pkg_resources import... |
"""
Module implementing the project browser helper base for Mercurial extension
interfaces.
"""
from __future__ import unicode_literals
from PyQt5.QtCore import QObject
class HgExtensionProjectBrowserHelper(QObject):
"""
Class implementing the project browser helper base for Mercurial extension
interfaces.
... |
type = "passive"
def handler(fit, ship, context):
fit.ship.boostItemAttr("capacitorCapacity", ship.getModifiedItemAttr("eliteBonusElectronicAttackShip2"),
skill="Electronic Attack Ships") |
"""A rule which always matches."""
from __future__ import absolute_import, print_function, unicode_literals
__metaclass__ = type
__all__ = [
'Truth',
]
from zope.interface import implementer
from mailman.core.i18n import _
from mailman.interfaces.rules import IRule
@implementer(IRule)
class Truth:
"""Look f... |
'''
Simple quaternion object for use with quaternion integrators.
'''
import numpy as np
class Quaternion(object):
def __init__(self, entries):
''' Constructor, takes 4 entries = s, p1, p2, p3 as a numpy array. '''
self.entries = entries
self.s = np.array(entries[0])
self.p = np.array(entries[1:4])
... |
import urlparse,urllib2,urllib,re
import os, sys
from core import logger
from core import config
from core import scrapertools
from core.item import Item
from core import servertools
from core import httptools
host ="http://www.playpornx.net/list-movies/"
def mainlist (item):
itemlist =[]
itemlist.append( Item(... |
import gtk
import os
import logging
from chirp import chirp_common, settings
from chirp.ui import miscwidgets, common
LOG = logging.getLogger(__name__)
POL = ["NN", "NR", "RN", "RR"]
class ValueEditor:
"""Base class"""
def __init__(self, features, memory, errfn, name, data=None):
self._features = featur... |
"""
Class Pattern to represent a pattern found by AD
"""
__author__ = 'Gorka Azkune'
__copyright__ = "Copyright 2017, City4Age project"
__credits__ = ["Rubén Mulero", "Aitor Almeida", "Gorka Azkune", "David Buján"]
__license__ = "GPL"
__version__ = "0.1"
__maintainer__ = "Gorka Azkune"
__email__ = "gorka.azkune@deusto.... |
"""
This file is part of openexp.
openexp 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.
openexp is distributed in the hope that it will be ... |
"""Create snaps from conda packages.
This plugin uses the common plugin keywords as well as those for "sources".
For more information check the 'plugins' topic for the former and the
'sources' topic for the latter.
Additionally, this plugin uses the following plugin-specific keywords:
- conda-packages
(list o... |
"""Provide an optimisation decorator and other utilities."""
MAX_CACHE_SIZE = 100000
def cache_results(func):
"""Decorator to store results for given inputs.
func is the decorated function.
A maximum of MAX_CACHE_SIZE arg-value pairs are stored.
"""
cache = {}
def wrap_func(*args, **kwargs):
... |
"""
This module provides functions to convert
NetworkX graphs to and from other formats.
The preferred way of converting data to a NetworkX graph
is through the graph constuctor. The constructor calls
the to_networkx_graph() function which attempts to guess the
input type and convert it automatically.
Examples
-------... |
from . import overview, master, detail |
import sys
flag = sys.argv[1][0]
threshold = int(sys.argv[1][1:])
for line in sys.stdin:
try:
if line[0] == "#":
print line.strip()
continue
cols = line.strip().split("\t")
info = cols[7]
for infoVal in info.split(";"):
name,value = infoVal.split("... |
import numpy as np
import bpy
from bpy.props import FloatProperty, EnumProperty, BoolProperty, IntProperty
from sverchok.node_tree import SverchCustomTreeNode
from sverchok.data_structure import updateNode, zip_long_repeat, ensure_nesting_level
from sverchok.utils.field.vector import SvVectorField
from sverchok.utils.c... |
"""
The C3 algorithm is used to linearize multiple inheritance hierarchies
in Python and other languages (MRO = Method Resolution Order). The code
in this doc string is by Samuele Pedroni and Michele Simionato and taken
from the official Python web site, here:
http://www.python.org/download/releases/2.3/mro/
For cyl... |
"""
Copyright (c) 2012-2020 RockStor, Inc. <http://rockstor.com>
This file is part of RockStor.
RockStor 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,
or (at your option) any lat... |
import os
import shlex
import logging
from ..plugin import PluginProcess, PluginException
class ConsoleApplication(PluginProcess):
def __init__(self, quokka):
super(ConsoleApplication, self).__init__()
self.quokka = quokka
def start(self):
binary = self.quokka.plugin.kargs.get('binary')
... |
import unittest2 as unittest
import tempfile
import os
from PIL import Image, ImageDraw
from nupic.engine import Network
from nupic.vision.regions.ImageSensor import ImageSensor
class ImageKNNTest(unittest.TestCase):
"""
This test is a simple end to end test. It creates a simple network with an
ImageSensor and a ... |
from typing import Set
from base.ddd.utils.business_validator import MultipleBusinessExceptions
from ddd.logic.learning_unit.domain.model.effective_class import EffectiveClass
from ddd.logic.learning_unit.domain.service.i_student_enrollments import \
IStudentEnrollmentsTranslator
from ddd.logic.learning_unit.domain... |
from django.db import migrations
from oscar.core.loading import get_model
from ecommerce.core.constants import ENROLLMENT_CODE_PRODUCT_CLASS_NAME
ProductAttribute = get_model("catalogue", "ProductAttribute")
ProductClass = get_model("catalogue", "ProductClass")
def create_idverifyreq_attribute(apps, schema_editor):
... |
"""
Copyright 2013-2014 Olivier Cortès <oc@1flow.io>
This file is part of the 1flow project.
1flow is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of
the License, or... |
import openerp
from openerp import tools
from openerp.osv import osv, fields
class mood(osv.osv):
_name = 'mood'
_descrition = 'Moods'
def _get_image(self, cr, uid, ids, name, args, context=None):
result = dict.fromkeys(ids, False)
for obj in self.browse(cr, uid, ids, context=context):
... |
from openerp.osv import fields, osv
class cdo_thietke_baomau(osv.osv):
_inherit = "cdo_thietke.baomau"
_columns = {
'multi_images': fields.text('Ảnh khảo sát'),
}
cdo_thietke_baomau() |
from pyrobot.robot.khepera import *
from pyrobot.system.share import ask
def INIT():
retval = ask("Please enter the Hemisson Data",
(("Port", "6665"),
("Baud", 115200)))
if retval["ok"]:
# For serial connected Hemisson:
return KheperaRobot(port = retval["Port"]... |
from __future__ import unicode_literals
import webnotes
from controllers.trends import get_columns,get_data
def execute(filters=None):
if not filters: filters ={}
data = []
conditions = get_columns(filters, "Purchase Order")
data = get_data(filters, conditions)
return conditions["columns"], data |
import os
import sys
import unittest
sys.path.insert(0, ".")
from coalib.output.printers.LogPrinter import LogPrinter
from coalib.output.printers.ConsolePrinter import ConsolePrinter
from coalib.collecting.Collectors import (collect_files,
collect_dirs,
... |
'''**********************************************************************
Copyright (C) 2009-2015 The Freeciv-web project
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either... |
"""
Copyright 2012-2014 Olivier Cortès <oc@1flow.io>
This file is part of the 1flow project.
1flow is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of
the License, or... |
from openquake.hazardlib.mfd import EvenlyDiscretizedMFD
from openquake.hazardlib.tests.mfd.base_test import BaseMFDTestCase
class EvenlyDiscretizedMFDMFDConstraintsTestCase(BaseMFDTestCase):
def test_empty_occurrence_rates(self):
exc = self.assert_mfd_error(
EvenlyDiscretizedMFD,
mi... |
"""
**Project Name:** MakeHuman
**Product Home Page:** http://www.makehuman.org/
**Code Home Page:** https://bitbucket.org/MakeHuman/makehuman/
**Authors:** Marc Flerackers
**Copyright(c):** MakeHuman Team 2001-2014
**Licensing:** AGPL3 (http://www.makehuman.org/doc/node/the_makehuman_app... |
import random
from django import forms as django_forms
from django.utils.translation import ugettext_lazy as _
from .base import BaseVotingSystem, BaseTally
from agora_site.misc.utils import *
from agora_site.agora_core.models.voting_systems.base import (
parse_voting_methods, get_voting_system_by_id, base_question... |
"""Contains code specific to the various machine provider backends""" |
import attr
from base.models.enums.learning_unit_year_periodicity import PeriodicityEnum
from ddd.logic.learning_unit.business_types import *
from ddd.logic.learning_unit.commands import CreatePartimCommand
from ddd.logic.learning_unit.domain.model._remarks import Remarks
from ddd.logic.learning_unit.domain.validator.v... |
from Acquisition import aq_get
from bika.lims import bikaMessageFactory as _
from bika.lims.utils import t
from bika.lims.interfaces import IDisplayListVocabulary, ICustomPubPref
from bika.lims.utils import to_utf8
from Products.Archetypes.public import DisplayList
from Products.CMFCore.utils import getToolByName
from ... |
import pytz
from openerp import _, api, fields, models
from openerp.exceptions import UserError
class event_type(models.Model):
""" Event Type """
_name = 'event.type'
_description = 'Event Type'
name = fields.Char('Event Type', required=True)
default_reply_to = fields.Char('Reply To')
default_r... |
from django.contrib import messages
from django.contrib.auth import authenticate, login, logout
from django.http import HttpResponseRedirect
from django.shortcuts import render, redirect
from django.urls import reverse_lazy
from django.views.generic import CreateView
from core.forms.registration_form import Registratio... |
"""
This script handles building all applications and tests for one board and also
execute tests if they are available.
An incremental build can selected using `--incremental` to not rerun successful
compilation and tests. But then it should be run on a fixed version of the
repository as no verification is done if resu... |
Import ('plugin_base')
Import ('env')
prefix = env['PREFIX']
plugin_env = plugin_base.Clone()
ogr_src = Split(
"""
ogr_converter.cpp
ogr_datasource.cpp
ogr_featureset.cpp
ogr_index_featureset.cpp
"""
)
plugin_env['LIBS'] = [env['PLUGINS']['ogr']['lib']]
plugin_env['LIBS'].append('map... |
from __future__ import print_function
import numpy as np
import msmbuilder.cluster
import mdtraj as md
import mdtraj.testing
import scipy.spatial.distance
X1 = 0.3 * np.random.RandomState(0).randn(1000, 10).astype(np.double)
X2 = 0.3 * np.random.RandomState(1).randn(1000, 10).astype(np.float32)
trj = md.load(md.testing... |
from __future__ import print_function
import pytz
import datetime
import unittest
from pprint import pprint
from lxml import etree
from base64 import b64encode
from decimal import Decimal as D
from spyne import Application, rpc, mrpc, Service, ByteArray, Array, \
ComplexModel, SelfReference, XmlData, XmlAttribute, ... |
if getSystems() == []:
print "No System loaded! aborting..:"
system = getSystem(0)
ff = getMolecularStructure().getForceField()
ff.setup(system)
ssm = SnapShotManager()
mds = CanonicalMD()
mds.setup(ff, ssm)
mds.setTimeStep(0.001)
mds.setReferenceTemperature(0)
time = 0
starttemperature = 0
endtemperature = 600
tempe... |
"""User defined samples."""
import numpy as np
from equadratures.sampling_methods.sampling_template import Sampling
class Userdefined(Sampling):
"""
The class defines a Sampling object. It serves as a template for all sampling methodologies.
:param list parameters: A list of parameters, where each element o... |
"""Implements ProcessPoolExecutor.
The follow diagram and text describe the data-flow through the system:
|======================= In-process =====================|== Out-of-process ==|
+----------+ +----------+ +--------+ +-----------+ +---------+
| | => | Work Ids | => | | => | C... |
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()
mobileTe... |
from circle import Circle
def test_radius():
c = Circle (4)
assert c.radius == 4
def test_diameter():
c = Circle (5)
assert c.diameter == 10
def change_radius():
c = Circle (5)
c.radius = 2
assert c.diameter == 4 |
"""Voluptuous schemas for the KNX integration."""
import voluptuous as vol
from xknx.devices.climate import SetpointShiftMode
from xknx.io import DEFAULT_MCAST_PORT
from homeassistant.const import (
CONF_ADDRESS,
CONF_DEVICE_CLASS,
CONF_ENTITY_ID,
CONF_HOST,
CONF_NAME,
CONF_PORT,
CONF_TYPE,
... |
"""
Vultr Driver
"""
import time
import json
import base64
from functools import update_wrapper
from typing import Optional, List, Dict, Union, Any
from libcloud.common.base import ConnectionKey, JsonResponse
from libcloud.common.types import InvalidCredsError
from libcloud.common.types import LibcloudError
from libclo... |
import json
import os
import shutil
import sys
import unittest
import numpy as np
import pandas as pd
from systemds.context import SystemDSContext
class TestTransformEncode(unittest.TestCase):
sds: SystemDSContext = None
HOMES_PATH = "../../test/resources/datasets/homes/homes.csv"
HOMES_SCHEMA = '"int,strin... |
import os
import subprocess
import textwrap
BASEDIR = os.path.split(os.path.realpath(__file__))[0] + "/../../"
if __name__ == "__main__":
os.chdir(BASEDIR)
opt_file = open("cinder/opts.py", 'w')
opt_dict = {}
dir_trees_list = []
REGISTER_OPTS_STR = "CONF.register_opts("
REGISTER_OPT_STR = "CONF.... |
from django.contrib import admin
from .models import Comment, Review
admin.site.register(Comment)
admin.site.register(Review) |
"""Support for Toon thermostat."""
from __future__ import annotations
from typing import Any
from toonapi import (
ACTIVE_STATE_AWAY,
ACTIVE_STATE_COMFORT,
ACTIVE_STATE_HOME,
ACTIVE_STATE_SLEEP,
)
from homeassistant.components.climate import ClimateEntity
from homeassistant.components.climate.const impo... |
"""Client for interacting with the Google Cloud Translate API."""
import six
from google.cloud._helpers import _to_bytes
from google.cloud.client import Client as BaseClient
from google.cloud.translate.connection import Connection
ENGLISH_ISO_639 = 'en'
"""ISO 639-1 language code for English."""
BASE = 'base'
"""Base t... |
"""Support for monitoring a GreenEye Monitor energy monitor."""
import logging
from greeneye import Monitors
import voluptuous as vol
from homeassistant.const import (
CONF_NAME,
CONF_PORT,
CONF_SENSOR_TYPE,
CONF_SENSORS,
CONF_TEMPERATURE_UNIT,
EVENT_HOMEASSISTANT_STOP,
TIME_HOURS,
TIME_... |
"""Support for interacting with Spotify Connect."""
from __future__ import annotations
from asyncio import run_coroutine_threadsafe
import datetime as dt
from datetime import timedelta
import logging
from typing import Any, Callable
import requests
from spotipy import Spotify, SpotifyException
from yarl import URL
from... |
"""A driver for VLAN-based setups using a single switch (possibly stacked)
See the documentation for the haas.drivers package for a description of this
module's interface.
An example config:
[general]
driver = simple_vlan
[driver simple_vlan]
switch = {"switch": "dell", "ip": "192.168.0.2", "user": "foo", "pass": "bar"... |
__author__ = 'Afshin'
from django.conf.urls import patterns,include, url
urlpatterns = patterns('vendor.views',
url(r'^add', 'add_product', name='add_product'),
url(r'^edit', 'edit_product', name='edit_product'),
) |
import argparse
import struct
import os
import sys
parser = argparse.ArgumentParser(description='Generate an efivars boot entry file')
parser.add_argument('interface', help='Current linux interface name to boot from')
parser.add_argument('outfile', help='The file to write, e.g. /sys/firmware/efi/efivars/Boot0007-8be4df... |
import logging
import netaddr
from django.conf import settings # noqa
from django.core.urlresolvers import reverse # noqa
from django.core import validators
from django.forms import ValidationError # noqa
from django.utils.translation import ugettext_lazy as _ # noqa
from horizon import exceptions
from horizon impo... |
"""Tests for the bucket_mover_service.py file"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import unittest
import mock
from google.cloud import exceptions
from retrying import RetryError
from gcs_bucket_mover import bucket_details
from gcs_bucket_mover ... |
"""Determining whether files are being measured/reported or not."""
import importlib.util
import inspect
import itertools
import os
import platform
import re
import sys
import sysconfig
import traceback
from coverage import env
from coverage.disposition import FileDisposition, disposition_init
from coverage.exceptions ... |
"""
The central management of Ryu applications.
- Load Ryu applications
- Provide `contexts` to Ryu applications
- Route messages among Ryu applications
"""
import inspect
import itertools
import logging
import sys
import os
import gc
from ryu import cfg
from ryu import utils
from ryu.app import wsgi
from ryu.controlle... |
import copy
from nova.api.validation import parameter_types
from nova.api.validation.parameter_types import multi_params
from nova.objects import instance
legacy_block_device_mapping = {
'type': 'object',
'properties': {
'virtual_name': {
'type': 'string', 'maxLength': 255,
},
... |
import os
import sys
import time
import paddle.fluid as fluid
def train(prefix):
if fluid.core.is_compiled_with_xpu():
selected_devices = os.getenv("FLAGS_selected_xpus")
else:
selected_devices = os.getenv("FLAGS_selected_gpus")
trainer_id = int(os.getenv("PADDLE_TRAINER_ID"))
worker_end... |
"""Common classes and entities in Github """
import json
import urllib
import requests
from bs4 import BeautifulSoup
from hal.internet.utils import add_params_to_url
from hal.wrappers.errors import none_returns
GITHUB_URL = "https://github.com"
API_URL = "https://api.github.com/" # Github api url
GITHUB_TOKEN = None
G... |
import copy
import mock
import urllib.parse as urlparse
from oslo_db.exception import DBDuplicateEntry
from oslo_utils.fixture import uuidsentinel
from oslo_utils import timeutils
from nova import exception
from nova.objects import console_auth_token as token_obj
from nova.tests.unit import fake_console_auth_token as f... |
from django.db import models
from server.models import *
class Catalog(models.Model):
machine_group = models.ForeignKey(MachineGroup)
content = models.TextField()
name = models.CharField(max_length=253)
sha256hash = models.CharField(max_length=64)
class Meta:
ordering = ['name', 'machine_gro... |
"""
Integrates with OPA to compile Rego queries into SQL.
Example
-------
The example below codifes the following policy (in English):
* Users can read their own posts
* Super users can do anything
Posts can be listed (e.g., GET /posts) or read individually (e.g., GET /posts/1234).
package example
allow... |
"""Controllers for the Oppia collection learner view."""
from core.controllers import base
from core.domain import collection_services
from core.domain import config_domain
from core.domain import exp_services
from core.domain import rights_manager
from core.platform import models
import utils
(user_models,) = models.R... |
"""Implementation of image ops."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
from tensorflow.python.framework import constant_op
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import ops
from tensorflo... |
''' from wikipedia: dx/dt = sigma*(y-x) ; dy/dt = x*(rho-z)-y dz/dt = x*y-beta*z ; '''
import numpy as np
def initialize(self,runInfoDict,inputFiles):
self.sigma = 10.0
self.rho = 28.0
self.beta = 8.0/3.0
return
def run(self,Input):
max_time = 1.0
t_step = 0.001
numberTimeSteps = int(max_time/t_step... |
from oslo_utils import timeutils
import six
class CooldownMixin(object):
'''
Utility class to encapsulate Cooldown related logic which is shared
between AutoScalingGroup and ScalingPolicy
'''
def _cooldown_inprogress(self):
inprogress = False
try:
# Negative values don't ... |
"""Build documentation from quattor sources."""
import os
import sys
import re
import codecs
from multiprocessing import Pool
from vsc.utils import fancylogger
from sourcehandler import get_source_files
from rsthandler import generate_rst_from_repository
from config import build_repository_map
logger = fancylogger.getL... |
from trt_layer_auto_scan_test import TrtLayerAutoScanTest, SkipReasons
from program_config import TensorConfig, ProgramConfig
import numpy as np
import paddle.inference as paddle_infer
from functools import partial
from typing import Optional, List, Callable, Dict, Any, Set
import unittest
class TrtConvertSkipLayernorm... |
"""Config flow for HomeKit integration."""
from __future__ import annotations
import asyncio
import random
import re
import string
import voluptuous as vol
from homeassistant import config_entries
from homeassistant.components import device_automation
from homeassistant.components.camera import DOMAIN as CAMERA_DOMAIN
... |
from django.urls import reverse
from django.utils.translation import ugettext_lazy as _
from horizon import exceptions
from horizon import forms
from horizon import messages
from openstack_dashboard import api
class EvacuateHostForm(forms.SelfHandlingForm):
current_host = forms.CharField(label=_("Current Host"),
... |
"""results_key to query
Revision ID: 7e3ddad2a00b
Revises: b46fa1b0b39e
Create Date: 2016-10-14 11:17:54.995156
"""
revision = '7e3ddad2a00b'
down_revision = 'b46fa1b0b39e'
from alembic import op
import sqlalchemy as sa
def upgrade():
op.add_column('query', sa.Column('results_key', sa.String(length=64), nullable=Tr... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.