code stringlengths 1 199k |
|---|
from django.core.management.base import BaseCommand
from django.utils import timezone
from mainsite.models import AccessTokenProxy, AccessTokenScope
class Command(BaseCommand):
def handle(self, *args, **options):
self.stdout.write('Splitting all scopes on tokens')
chunk_size = 5000
page = 0
... |
"""
Integration tests for submitting problem responses and getting grades.
"""
import json
import os
from textwrap import dedent
from django.conf import settings
from django.contrib.auth.models import User
from django.core.urlresolvers import reverse
from django.test.client import RequestFactory
from mock import patch
... |
import sys
import time
from datetime import datetime
from operator import itemgetter
from lxml import etree
from openerp import netsvc
from openerp.osv import fields, osv, orm
from openerp.tools.translate import _
import openerp.addons.decimal_precision as dp
from openerp import tools
class account_move_line(osv.osv):
... |
import datetime
import errno
import logging
import os
import os.path
import platform
import psutil
import random
import resource
import select
import signal
import socket
import subprocess
import sys
import threading
import time
import werkzeug.serving
try:
import fcntl
except ImportError:
pass
try:
from se... |
from weboob.capabilities.lyrics import ICapLyrics, SongLyrics
from weboob.tools.backend import BaseBackend
from .browser import ParolesmaniaBrowser
from urllib import quote_plus
__all__ = ['ParolesmaniaBackend']
class ParolesmaniaBackend(BaseBackend, ICapLyrics):
NAME = 'parolesmania'
MAINTAINER = u'Julien Veys... |
import os
from celery import Celery
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'settings')
from django.conf import settings
try:
from settings import celery_local as celery_settings
except ImportError:
from settings import celery as celery_settings
app = Celery('taiga')
app.config_from_object(celery_settin... |
import unittest
import numpy
from union_pooling.union_pooler import UnionPooler
REAL_DTYPE = numpy.float32
class UnionPoolerTest(unittest.TestCase):
def setUp(self):
self.unionPooler = UnionPooler(inputDimensions=5,
columnDimensions=5,
potentia... |
from SMESH_mechanic import *
filter = smesh.GetFilter(SMESH.FACE, SMESH.FT_AspectRatio, SMESH.FT_MoreThan, 1.5)
ids = mesh.GetIdsFromFilter(filter)
print "Number of faces with aspect ratio > 1.5:", len(ids)
filter.SetMesh( mesh.GetMesh() )
mesh2 = smesh.CopyMesh( filter, "AR > 1.5" )
print "Number of copied faces with ... |
"Definition of Windows structures"
from __future__ import absolute_import
__revision__ = "$Revision: 560 $"
from .win32defines import LF_FACESIZE, NMTTDISPINFOW_V1_SIZE, HDITEMW_V1_SIZE
import sys
import ctypes
from ctypes import \
c_int, c_uint, c_long, c_ulong, c_void_p, c_wchar, c_char, \
c_ubyte, c_ushort, ... |
import platform
import sys
import os
from spack import *
class Namd(MakefilePackage):
"""NAMDis a parallel molecular dynamics code designed for
high-performance simulation of large biomolecular systems."""
homepage = "http://www.ks.uiuc.edu/Research/namd/"
url = "file://{0}/NAMD_2.12_Source.tar.gz"... |
import argparse
from spack.cmd.common import print_module_placeholder_help
description = "add package to environment using dotkit"
section = "environment"
level = "long"
def setup_parser(subparser):
"""Parser is only constructed so that this prints a nice help
message with -h. """
subparser.add_argument(... |
import os
import sys
import glob
from copy import copy
from subprocess import Popen, PIPE
Import('env')
lib_env = env.Clone()
def call(cmd, silent=True):
stdin, stderr = Popen(cmd, shell=True, stdout=PIPE, stderr=PIPE).communicate()
if not stderr:
return stdin.strip()
elif not silent:
print ... |
import flask.views
from flask import request
TAM_PAGINA=5
def calculoPrimeraPag(cant):
"""
Setea los valores correspondientes a la primera pagina de un paginar,
recibe la cantidad de items, fases o proyectos que existen para dicho paginar
"""
if(cant!=0):#Si devolvio algo
t=cant/TAM_PAGINA
... |
"core.Pixmap tests"
from unittest import SkipTest
from testutils import *
from gfxprim.core import Pixmap
from gfxprim import gfx, core
def test_gfx_submodule_loads():
"gfx is present in a Pixmap"
c = Pixmap(1, 1, core.C.PIXEL_RGB888)
assert c.gfx
def test_gfx_submodule_has_C():
"gfx contains C"
c = Pixmap(1,... |
'''
Shows how to use BitmapManager to asynchronously load a Bitmap from a file.
Run this snippet providing a list of filenames of (high resolution) pictures:
$ ./asyncload.py /path/to/mypics/*.jpg anotherpic.png nonexistent.png
Press space to sequentially load the pictures. A rotating rectangle appears
during the time ... |
import re
from webkit import model
def combine_condition(conditions):
if conditions:
if len(conditions) == 1:
return conditions[0]
else:
return bracket_if_needed(' && '.join(map(bracket_if_needed, conditions)))
else:
return None
def bracket_if_needed(condition):
... |
import unittest
import run_tests # set sys.path
import tempfile
import os
from kobo.http import *
class TestPOSTTransport(unittest.TestCase):
def setUp(self):
self.postt = POSTTransport()
def test_get_content_type(self):
tf0 = tempfile.mkstemp()[1]
tf1 = tempfile.mkstemp(suffix=".txt")[1... |
import unittest
from charm.toolbox.symcrypto import SymmetricCryptoAbstraction,AuthenticatedCryptoAbstraction, MessageAuthenticator
from charm.toolbox.pairinggroup import PairingGroup,GT
from charm.core.math.pairing import hashPair as sha1
class SymmetricCryptoAbstractionTest(unittest.TestCase):
def testAESCBC(self... |
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('equinox_api', '0004_operation_description'),
]
operations = [
migrations.AddField(
model_name='application',
name='new_att',
... |
from FastBitSet import FastBitSet
import math
import mmh3
class FastBloomFilter(object):
mask32 = 0xffffffff
mask64 = 0xffffffffffffffff
mask128 = 0xffffffffffffffffffffffffffffffff
seeds = [2, 3, 5, 7, 11,
13, 17, 19, 23, 29,
31, 37, 41, 43, 47,
53, 59, 61, 67, 71,
... |
fn='/home/thomas/Dokumente/freecad_buch/D006_landxml/Survey.xml'
fn='/home/thomas/Dokumente/freecad_buch/D006_landxml/bratton farm-2.0.xml'
fn='/home/thomas/Dokumente/freecad_buch/D006_landxml/Portsmouth Heights.xml'
fn='/home/thomas/Dokumente/freecad_buch/D006_landxml/FreeCAD_Document.xml'
import geodat
import re
from... |
"""
CERMMorse : test_config
5/7/2017 : 11:32 PM
Author : James L. Key
"""
from unittest import TestCase
from readconfig import Config
__author__ = 'James L. Key'
__project__ = 'CERMMorse'
class TestConfig(TestCase):
def setUp(self):
self.conf = Config(configpath='../data/config.json')
self.conf.getc... |
from openerp import models, api, _
from openerp.exceptions import UserError
class ExportMoveExport(models.TransientModel):
_name = 'export.move.export'
_description = 'Export Moves'
@api.multi
def create_export_file(self):
context = dict(self._context or {})
moves = self.env['export.move... |
__author__ = 'beau'
import serial
ser = serial.Serial('/dev/tty.usbmodem1422',9600, timeout=1)
import time
import sys
def get_angle():
print "requesting angle"
start = time.time()
ser.write('nofddfp\n')
print "..."
reply = ser.readline()
deltaT = time.time()-start
print reply
print "roun... |
import re
import os.path
import glob
import kbindinggenerator.cmakeparser as cmakeparser
def ExtractInstallFiles(filename=None,input=None,variables=None):
if variables is None:
variables = {}
else:
variables = variables.copy()
install_list = []
if filename is not None:
variables[... |
import sys, os
from pythonparser import diagnostic
from ...language.environment import ProcessArgumentManager
from ...master.databases import DeviceDB, DatasetDB
from ...master.worker_db import DeviceManager, DatasetManager
from ..module import Module
from ..embedding import Stitcher
from ..targets import OR1KTarget
fr... |
from forgery_py import *
for x in range(20):
randPerson=name.first_name(),name.last_name(),personal.gender(),name.location(),address.phone()
randCV=lorem_ipsum.title(),lorem_ipsum.sentence()
randAddr=address.city(),address.state(),address.country(),address.continent()
randEmail=internet.email_address()
randCo... |
from twisted.web import server, resource
from Tribler.Core.Modules.restapi.util import convert_db_channel_to_json, convert_search_torrent_to_json, \
fix_unicode_dict
from Tribler.Core.simpledefs import (NTFY_CHANNELCAST, SIGNAL_CHANNEL, SIGNAL_ON_SEARCH_RESULTS, SIGNAL_TORRENT,
... |
"""Connectors"""
__copyright__ = "Copyright (C) 2014 Ivan D Vasin"
__docformat__ = "restructuredtext"
import abc as _abc
import re as _re
from ... import plain as _plain
from .. import _std as _std_http
_BASIC_USER_TOKENS = ('user', 'password')
class HttpBasicClerk(_std_http.HttpStandardClerk):
"""An authentication... |
"""Unit tests for the :func:`iris.analysis.maths.add` function."""
from __future__ import (absolute_import, division, print_function)
import iris.tests as tests
import operator
from iris.analysis.maths import add
from iris.tests.unit.analysis.maths import \
CubeArithmeticBroadcastingTestMixin, CubeArithmeticMasking... |
from collections import defaultdict
from matplotlib import pyplot as plt
from matplotlib.ticker import MultipleLocator
import numpy as np
from msaf.models import Marker
def summarize_alleles2( analytical_sets, temp_dir = None ):
""" return a tuple of (report, plot)
"""
allele_plots = {}
allele_reports =... |
from io.endeios.example.javascripts import ABean, TestInterface
from java.lang import Long
def myecho(a):
return a
def greet():
return "Hello Python"
class MyClass(TestInterface):
def __init__(self):
pass
def getBean(self):
retVal =ABean()
retVal.setName("python")
retVal.setNumber(101)
retVal.setReady... |
import androidhelper
import curses
droid = androidhelper.Android()
win=curses.initscr()
result="No result"
try:
win.box()
w,h=win.getmaxyx()
win.addstr(2,2,"Curses Test %sx%s" % (w,h))
win.addstr(10,10,"Hit a key")
win.getch()
finally:
curses.endwin()
print("Result=",result) |
import requests
import sys
import re
from BeautifulSoup import BeautifulSoup
target = 'http://192.168.1.33/DVWA'
user_list = '/usr/share/seclists/Usernames/top_shortlist.txt'
pass_list = '/usr/share/seclists/Passwords/rockyou.txt'
success = 'index.php'
def csrf_token():
try:
# Make the request to the URL
... |
import decimal
import random
a = []
for j in range(0, 10):
a.append(random.randrange(100))
print a |
import unittest
import itertools
class Solution:
def maxRotateFunction(self, A):
"""
:type A: List[int]
:rtype: int
"""
if not A:
return 0
n = len(A)
sum_ = sum(A)
f = sum(i * num for i, num in enumerate(A))
max_ = f
for num... |
from util import *
import random, string
from random import randint
import time
class KonačniAutomat(types.SimpleNamespace):
"""Automat koji prepoznaje regularni jezik."""
@classmethod
def iz_komponenti(klasa, stanja, abeceda, prijelaz, početno, završna):
"""Sipser page 35 definition 1.5 - konstrukcija iz petorke.... |
from django.conf.urls import url, include
from snippets import views
from rest_framework.routers import DefaultRouter
router = DefaultRouter()
router.register(r'snippets', views.SnippetViewSet)
router.register(r'users', views.UserViewSet)
urlpatterns = [
url(r'^', include(router.urls)),
url(r'^api-auth/... |
from onefile import *
def two():
print "at two\n",
def second():
print "at second\n",
if __name__ == '__main__':
two() |
import fechbase
class Records(fechbase.RecordsBase):
def __init__(self):
fechbase.RecordsBase.__init__(self)
self.fields = [
{'name': 'FORM TYPE', 'number': '1'},
{'name': 'FILER FEC CAND ID', 'number': '2'},
{'name': 'CANDIDATE NAME', 'number': '3'},
... |
from collections import deque
import gym
from gym import spaces
import numpy as np
from ray.rllib.utils.images import rgb2gray, resize
def is_atari(env):
if (
hasattr(env.observation_space, "shape")
and env.observation_space.shape is not None
and len(env.observation_space.shape) <= 2
):
... |
import numpy as np
import pandas as pd
import pytest
ROWID_ZERO_INDEXED_BACKENDS = ('omniscidb',)
@pytest.mark.parametrize(
'column',
[
'string_col',
'double_col',
'date_string_col',
pytest.param('timestamp_col', marks=pytest.mark.skip(reason='hangs')),
],
)
@pytest.mark.xfai... |
from functools import wraps
import os
from rqalpha.const import ORDER_TYPE, SIDE, POSITION_EFFECT
from .data_dict import TickDict, PositionDict, AccountDict, InstrumentDict, OrderDict, TradeDict, CommissionDict
from ..vnpy import *
from ..utils import make_order_book_id
ORDER_TYPE_MAPPING = {
ORDER_TYPE.MARKET: def... |
# Copyright 2015 The ChEMBL group.
"""Implementation of an S3-like storage server, using Pymongo, MongoDB and Tornado.
Useful to test features that will eventually run on S3, or if you want to
run something locally that was once running on S3.
We don't support all the features of S3, but it does work with the
standard... |
"""Tests for the debug events writer Python class."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from absl.testing import parameterized
import numpy as np
from tensorflow.core.protobuf import debug_event_pb2
from tensorflow.python.debug.lib import debug_... |
__author__ = 'Conscience'
from django.conf.urls import url
from django.contrib import admin
from . import views
urlpatterns = [
url(r'^$', views.post_list, name='post_list'),
url(r'^post/(?P<pk>[0-9]+)/$', views.post_detail, name='post_detail'),
url(r'^post/$', views.post_list, name='post_list'),
url(r'... |
from sqlalchemy import desc
from webob import exc
from murano.api.v1 import request_statistics
from murano.common import policy
from murano.common import utils
from murano.db import models
from murano.db import session as db_session
from murano.openstack.common.gettextutils import _ # noqa
from murano.openstack.common... |
"""
WSGI config for lot project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.11/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODU... |
data = open('output.dex', 'rb').read()
with open('output.txt', 'wb') as f:
f.write(str(map(ord, data))) |
"""The tests for local file camera component."""
import asyncio
from unittest import mock
from mock_open import MockOpen
from homeassistant.bootstrap import setup_component
from tests.common import mock_http_component
import logging
@asyncio.coroutine
def test_loading_file(hass, test_client):
"""Test that it loads ... |
"""A sample app that operates on GCS files with blobstore API's BlobReader."""
import cloudstorage
from google.appengine.api import app_identity
from google.appengine.ext import blobstore
import webapp2
class BlobreaderHandler(webapp2.RequestHandler):
def get(self):
# Get the default Cloud Storage Bucket na... |
import json
import logging
import os
import threading
import time
import requests
from azure.core.exceptions import ClientAuthenticationError
from azure.identity._exceptions import CredentialUnavailableError
try:
from urllib.parse import urlparse
except ImportError:
from urlparse import urlparse
logger = loggin... |
"""This module contains the RankerRoot model
"""
__authors__ = [
'"Lennard de Rijk" <ljvderijk@gmail.com>',
]
from google.appengine.ext import db
import soc.models.linkable
class RankerRoot(soc.models.linkable.Linkable):
"""Links the Root of a RankList tree to an owner and also
gives it an unique ID.
"""
#... |
'''
Parse links in html and css pages.
'''
import logging
import re
import hashlib
import urllib.parse
from functools import partial
import multidict
import html
from bs4 import BeautifulSoup
from . import stats
from .urls import URL
from . import facet
from . import config
LOGGER = logging.getLogger(__name__)
async de... |
from ut_arena.settings import * |
""" WebDAV upload method for dput.
Install to "/usr/share/dput/webdav.py".
"""
from __future__ import with_statement
import re
import os
import sys
import cgi
import netrc
import socket
import fnmatch
import getpass
import httplib
import urllib2
import urlparse
import unittest
from contextlib import closing
from em... |
import nova.conf
from nova.tests.functional.api_sample_tests import test_servers
CONF = nova.conf.CONF
class AvailabilityZoneJsonTest(test_servers.ServersSampleBase):
ADMIN_API = True
extension_name = "os-availability-zone"
def _get_flags(self):
f = super(AvailabilityZoneJsonTest, self)._get_flags()... |
import abc
import six
from taskflow.utils import reflection
class Flow(six.with_metaclass(abc.ABCMeta)):
"""The base abstract class of all flow implementations.
A flow is a structure that defines relationships between tasks. You can
add tasks and other flows (as subflows) to the flow, and the flow provides
... |
"""
CNN on mnist data using fluid api of paddlepaddle
"""
import paddle
import paddle.fluid as fluid
def mnist_cnn_model(img):
"""
Mnist cnn model
Args:
img(Varaible): the input image to be recognized
Returns:
Variable: the label prediction
"""
conv_pool_1 = fluid.nets.simple_img... |
from kubb_match.data.models import GridPosition, Round, Game
class BattleService(object):
def __init__(self):
pass
def create_games(self, positions):
games = []
nr = int(len(positions) / 5)
field = 1
for row in ('A', 'B', 'C', 'D', 'E'):
for x in range(1, nr +... |
from gittle import Gittle
repo = Gittle('.')
lastest = [
info['sha']
for info in repo.commit_info()[1:3]
]
print(repo.diff(*lastest, diff_type='classic'))
print("""
Last Diff
""")
print(list(repo.diff('HEAD'))) |
from setuptools import setup, find_packages
from dist_job_mgr.version import VERSION
setup(
name='dist_job_mgr',
version=VERSION,
author='genForma Corp',
author_email='code@genforma.com',
url='',
packages=find_packages(),
include_package_data=True,
zip_safe=False,
entry_points = {
... |
from pscheduler import json_validate
MAX_SCHEMA = 1
def spec_is_valid(json):
schema = {
"type": "object",
"properties": {
"schema": { "$ref": "#/pScheduler/Cardinal" },
"duration": { "$ref": "#/pScheduler/Duration" },
"host": { "$ref"... |
import os
import sys
sys.path.insert(0, os.path.abspath('../../'))
extensions = [
'sphinx.ext.autodoc',
'sphinx.ext.intersphinx',
'sphinx.ext.ifconfig',
'sphinx.ext.autosummary'
]
autosummary_generate = True
autodoc_default_flags = ['members', 'undoc-members']
def skip_member(app, what, name, obj, skip,... |
from datetime import date, datetime, time
from decimal import Decimal
from django.core.files import File
from django.core.files.storage import default_storage
from django.core.files.uploadedfile import SimpleUploadedFile
from django.test import TestCase
from django.utils.timezone import now
from i18nfield.strings impor... |
"""Run YCSB against MongoDB.
YCSB is a load generator for many 'cloud' databases. MongoDB is a NoSQL
database.
MongoDB homepage: http://www.mongodb.org/
YCSB homepage: https://github.com/brianfrankcooper/YCSB/wiki
"""
import functools
import random
import string
import time
from absl import flags
from perfkitbenchmarke... |
import pprint
import config
import json
import urllib
import requests
class Driver(object):
def __init__(self):
self.driver_type = self.__class__.__name__
# Get credentials from conf files for CMDB
pass
def get_driver_type(self):
return self.driver_type
def get_ci(self, c... |
import time
import string
import os
import os.path
from random import choice
import stratuslab.system.SystemFactory as SystemFactory
from stratuslab.installator.Installator import Installator
from stratuslab import Util
from stratuslab.Util import printError
class CouchbaseServer(Installator):
@staticmethod
def... |
"""Various base layers for the colorization transformer."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import functools
import math
import operator
import numpy as np
import tensorflow.compat.v2 as tf
from tensorflow.compat.v2.keras import layers
from co... |
from rest_framework import routers
from . import views
class SecretsRootView(routers.APIRootView):
"""
Secrets API root view
"""
def get_view_name(self):
return 'Secrets'
router = routers.DefaultRouter()
router.APIRootView = SecretsRootView
router.register(r'_choices', views.SecretsFieldChoicesV... |
import base64
import crypt
import hashlib
import random
import re
import string
import struct
import sys
import traceback
import xml.dom.minidom as minidom
import zlib
from azurelinuxagent.common.future import ustr
def parse_doc(xml_text):
"""
Parse xml document from string
"""
# The minidom lib has som... |
"""
minio.error
~~~~~~~~~~~~~~~~~~~
This module provides custom exception classes for Minio library
and API specific errors.
:copyright: (c) 2015, 2016, 2017 by Minio, Inc.
:license: Apache 2.0, see LICENSE for more details.
"""
from xml.etree import cElementTree
from xml.etree.cElementTree import ParseError
if hasattr... |
from django.db import models
from user.models import State
from django.utils.translation import ugettext as _
from pprint import pprint
class Party(models.Model):
short_name = models.CharField(max_length=10, default='***')
full_name = models.CharField(max_length=50, default='*****')
#logo = models.CharField(max_leng... |
import logging
import plistlib
from django.http import HttpResponse
from django.urls import reverse
from zentral.conf import settings
from zentral.utils.certificates import split_certificate_chain
from zentral.utils.payloads import generate_payload_uuid, get_payload_identifier
from zentral.utils.payloads import sign_pa... |
from google.cloud import servicecontrol_v1
async def sample_check():
# Create a client
client = servicecontrol_v1.ServiceControllerAsyncClient()
# Initialize request argument(s)
request = servicecontrol_v1.CheckRequest(
)
# Make the request
response = await client.check(request=request)
... |
"""
Parallel Hello World
"""
from mpi4py import MPI
import sys
size = MPI.COMM_WORLD.Get_size()
rank = MPI.COMM_WORLD.Get_rank()
name = MPI.Get_processor_name()
sys.stdout.write(
"Hello, World! I am process %d of %d on %s.\n"
% (rank, size, name)) |
"""Test the flow_management interface."""
import os
from grr.gui import gui_test_lib
from grr.gui import runtests_test
from grr.lib import action_mocks
from grr.lib import aff4
from grr.lib import flags
from grr.lib import flow
from grr.lib import hunts
from grr.lib import test_lib
from grr.lib.flows.general import fil... |
from madrona.features.forms import FeatureForm
from django import forms
from visualize.models import *
class BookmarkForm(FeatureForm):
class Meta(FeatureForm.Meta):
model = Bookmark |
"""自适应学习率衰减
tf.train.exponential_decay(learning_rate, global_step, decay_steps, decay_rate, staircase=False, name=None)
退化学习率,衰减学习率,将指数衰减应用于学习速率。
计算公式:decayed_learning_rate = learning_rate *
decay_rate ^ (global_step / decay_steps)
"""
import tensorflow as tf
import numpy as np
import matplotlib... |
from __future__ import print_function
import pygion
from pygion import task
@task
def main():
pygion.print_once("Hello, Legion!")
if __name__ == '__main__':
main() |
__all__ = [
'ClouDNSDNSDriver'
]
from libcloud.common.base import JsonResponse, ConnectionUserAndKey
from libcloud.dns.types import Provider, RecordType
from libcloud.dns.types import ZoneDoesNotExistError, RecordDoesNotExistError
from libcloud.dns.types import ZoneAlreadyExistsError
from libcloud.dns.base import D... |
from numpy import zeros
from gwlfe.Memoization import memoize
from gwlfe.MultiUse_Fxns.Runoff.RurQRunoff import RurQRunoff
from gwlfe.MultiUse_Fxns.Runoff.RurQRunoff import RurQRunoff_f
from gwlfe.Output.Loading.PConc import PConc
from gwlfe.Output.Loading.PConc import PConc_f
@memoize
def pRunoff(NYrs, DaysMonth, Init... |
from pysqlite2 import dbapi2 as sqlite3
from collections import Counter
from operator import itemgetter
from itertools import chain
from flask import Flask, Response, request, session, g, redirect, url_for, \
abort, render_template, flash, jsonify
from contextlib import closing
import re
import json
import sys
imp... |
from django.shortcuts import render
from django.http import HttpResponse
import json
def services(request):
return render(request, 'services/services.html', {}) |
import paddle.v2 as paddle
import paddle.v2.framework.layers as layers
import paddle.v2.framework.nets as nets
import paddle.v2.framework.core as core
import paddle.v2.framework.optimizer as optimizer
from paddle.v2.framework.framework import Program, g_program
from paddle.v2.framework.executor import Executor
import n... |
"""
The system for scheduling tasks and executing them in order.
Deals with dependencies, priorities, resources, etc.
The :py:class:`~luigi.worker.Worker` pulls tasks from the scheduler (usually over the REST interface) and executes them.
See :doc:`/central_scheduler` for more info.
"""
import collections
try:
impo... |
from copy import deepcopy
import pytest
from sovrin_node.test import waits
from stp_core.loop.eventually import eventually
from plenum.common.constants import VERSION
from sovrin_common.constants import REINSTALL
from sovrin_node.test.upgrade.helper import bumpedVersion, checkUpgradeScheduled, \
ensureUpgradeSent, ... |
"""Constants to hide XSD Datatypes used by Point Values and Properties
These help to describe the data in a feed so the receiving Thing can know what kind of data to expect
See also http://www.w3.org/TR/xmlschema-2/#built-in-datatypes
"""
from __future__ import unicode_literals
BASE64 = 'base64Binary'
'''Represents a s... |
import sys, string
import os.path
import unique
import export
import gene_associations
import traceback
import time
def filepath(filename):
fn = unique.filepath(filename)
return fn
def read_directory(sub_dir):
dir_list = unique.read_directory(sub_dir)
#add in code to prevent folder names from being incl... |
import GithubObject
import GitAuthor
import GitObject
class GitTag( GithubObject.GithubObject ):
@property
def message( self ):
self._completeIfNotSet( self._message )
return self._NoneIfNotSet( self._message )
@property
def object( self ):
self._completeIfNotSet( self._object )
... |
import logging
from taskflow.patterns import graph_flow
from taskflow import task
from pumphouse import events
from pumphouse import exceptions
from pumphouse import flows
from pumphouse.tasks import service as service_tasks
from pumphouse import task as pump_task
from pumphouse import utils
LOG = logging.getLogger(__n... |
"""Tests for tf_agents.networks.categorical_q_network."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import gin
import tensorflow as tf # pylint: disable=g-explicit-tensorflow-version-import
from tf_agents.networks import categorical_q_network
from tf_a... |
import logging
import os
import socket
from oslo_concurrency import processutils
from oslo_config import cfg
import oslo_i18n
import pbr.version
oslo_i18n.enable_lazy()
from keystone.common import environment
from keystone.common import utils
from keystone import config
from keystone.i18n import _
from keystone.opensta... |
from neutron_lib._i18n import _
from neutron_lib import exceptions
class VlanTransparencyDriverError(exceptions.NeutronException):
"""Vlan Transparency not supported by all mechanism drivers."""
message = _("Backend does not support VLAN Transparency.") |
import sys, csv, json, argparse, datetime
from collections import defaultdict
with open("../SETTINGS.json") as fp:
settings = json.loads(fp.read())
def cnt_num_attendant(eventinfo_path, staresult_path):
''' count the distribution of number of attendants '''
num_attendant = defaultdict(int)
total_num = 0... |
__author__ = "Simone Campagna"
__all__ = [
'TestInvoiceProgram',
]
import os
import datetime
import unittest
from invoice.database.db_types import Str, StrList, StrTuple, \
Int, IntList, IntTuple, \
Float, FloatList, FloatTuple, \
... |
import datetime
import json
import logging
import requests
from core.analytics import OneShotAnalytics
from core.errors import ObservableValidationError
from core.observables import Hostname, Email, Ip, Hash
class ThreatCrowdAPI(object):
"""Base class for querying the ThreatCrowd API."""
@staticmethod
def f... |
# Copyright (c) 2016 Nishant Das Patnaik.
#
# 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 agr... |
import numpy as np
import pytest
from syft.core.tensor.smpc.share_tensor import ShareTensor
@pytest.mark.smpc
def test_bit_extraction() -> None:
share = ShareTensor(rank=0, parties_info=[], ring_size=2**32)
data = np.array([[21, 32], [-54, 89]], dtype=np.int32)
share.child = data
exp_res1 = np.array([[F... |
from sys import maxsize
from nose_parameterized import parameterized
from numpy import (
arange,
datetime64,
)
from numpy.testing import (
assert_array_equal,
)
from pandas import (
DataFrame,
Timestamp,
)
from pandas.util.testing import assert_index_equal
from zipline.data.us_equity_pricing import ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.