code stringlengths 1 199k |
|---|
import migrate
import sqlalchemy as sql
from sqlalchemy import orm
from keystone.common import sql as ks_sql
from keystone.common.sql import migration_helpers
from keystone import config
from keystone.openstack.common import log
LOG = log.getLogger(__name__)
CONF = config.CONF
def upgrade(migrate_engine):
meta = sq... |
import argparse
import json
import os
import csv
import sys
import re
import numpy as np
import random
from random import seed, shuffle
import eventlet
eventlet.sleep() # workaround for eventlet bug 0.21.0
requests = eventlet.import_patched('requests.__init__')
import requests
import glob
import time
import traceback
... |
"""nGraph TensorFlow installation test
"""
from __future__ import print_function
import tensorflow as tf
import ngraph_bridge
if __name__ == '__main__':
print("TensorFlow version: ", tf.version.GIT_VERSION, tf.version.VERSION) |
'''
The pkgbuild state is the front of Salt package building backend. It
automatically builds DEB and RPM packages from specified sources
.. versionadded:: 2015.8.0
.. code-block:: yaml
salt_2015.5.2:
pkgbuild.built:
- runas: thatch
- results:
- salt-2015.5.2-2.el7.centos.noarch.rpm
... |
"""siscore dataset."""
from tensorflow_datasets.image_classification.siscore.siscore import Siscore |
from keras.models import Sequential
from keras.layers import LSTM, Dense
import numpy as np
data_dim = 16
timesteps = 8
num_classes = 10
model = Sequential()
model.add(LSTM(32, return_sequences=True, input_shape=(timesteps, data_dim))) # returns a sequence of vectors of dimension 32
model.add(LSTM(32, return_sequences=... |
from __future__ import unicode_literals
from django.db import migrations
from resolwe.flow.utils import iterate_fields
def update_dependency_kinds(apps, schema_editor):
"""Update historical dependency kinds as they may be wrong."""
DataDependency = apps.get_model('flow', 'DataDependency')
for dependency in ... |
"""Tests for dopamine.agents.rainbow.sum_tree."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import random
from dopamine.replay_memory import sum_tree
import tensorflow as tf
class SumTreeTest(tf.test.TestCase):
def setUp(self):
super(SumTreeTest, ... |
import flask
import numpy as np
import os
import requests
import sys
from cv2 import cv2 as cv
from socket import AF_INET, SOCK_DGRAM, INADDR_ANY, IPPROTO_IP, IP_ADD_MEMBERSHIP, SOL_SOCKET, SO_REUSEADDR, socket, inet_aton, error as socket_error
import struct
from threading import Thread
import imagehash
from PIL import... |
import struct
import sys
import zlib
def main(argv):
if len(argv) != 5:
print("Usage: %s <output file> <system command> <libhwui!ReadStreaEndError> <linker64!_dl_popen>" % argv[0])
return
BPP = 4
COLORS = 38
OUTPUT_FILE = argv[1]
COMMAND = bytearray(argv[2], encoding='ascii')
ADDR_ReadStreaEndError ... |
from __future__ import unicode_literals
from django.db import models, migrations
from django.conf import settings
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name='Entr... |
import logging
from oslo.config import cfg
from designate.network_api.base import NetworkAPI
LOG = logging.getLogger(__name__)
cfg.CONF.register_opts([
cfg.StrOpt('network_api', default='neutron', help='Which API to use.')
])
def get_network_api(network_api_driver):
LOG.debug("Loading network_api driver: %s" % ... |
import hashlib
from datetime import datetime
from flask import request
from werkzeug.security import generate_password_hash, check_password_hash
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer
from flask import current_app
from flask_login import UserMixin, AnonymousUserMixin
from . import db, lo... |
from __future__ import unicode_literals
from django.urls import reverse
from django.db import models
class Team(models.Model):
teamid = models.AutoField(primary_key=True)
title = models.CharField(max_length=100)
def __str__(self):
return self.title
class Meta:
managed = False
d... |
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('core', '0020_auto_20150509_0315'),
]
operations = [
migrations.RenameField(
model_name='security',
old_name='group',
... |
from .tags import comment
from .tags import comment_bookmark
from .tags import comment_like
from .tags import search
from .tags import topic_favorite
from .tags import topic_notification
from .tags import topic_private
from .tags.utils import gravatar
from .tags.utils import messages
from .tags.utils import paginator
f... |
from subprocess import call
from mininet.util import irange
def configure_downlink(net, tsa_host):
ue_ip = tsa_host.host.IP()
call(["ovs-ofctl", 'add-flow', tsa_host.tsa_switch.name,
"idle_timeout=0,priority=33001,"
"dl_type=0x800,nw_dst={ip},actions=output:{port}".format(ip=ue_ip, port=tsa_... |
import logging
import os
import shutil
from unittest import TestCase
from allennlp.common.checks import log_pytorch_version_info
class AllenNlpTestCase(TestCase): # pylint: disable=too-many-public-methods
"""
A custom subclass of :class:`~unittest.TestCase` that disables some of the
more verbose AllenNLP l... |
import abc
import typing
import pkg_resources
import google.auth # type: ignore
from google.api_core import gapic_v1 # type: ignore
from google.api_core import retry as retries # type: ignore
from google.auth import credentials as ga_credentials # type: ignore
from google.ads.googleads.v8.resources.types import sho... |
from django.conf.urls import patterns, url
from . import views
urlpatterns = patterns('',
url(r'^/?$', views.results, name='search'),
) |
"""Support for UPnP/IGD Sensors."""
import logging
from homeassistant.core import callback
from homeassistant.helpers.dispatcher import async_dispatcher_connect
from homeassistant.helpers.entity import Entity
from homeassistant.helpers.typing import HomeAssistantType
import homeassistant.util.dt as dt_util
from .const ... |
import unittest
import pysam
import copy
from scripts.seq_classes import locus, segment, allele
class test_loci(unittest.TestCase):
def setUp(self):
self.solution ={'A':allele("A"),
'T':allele("T"),
'C':allele("C"),
'G':allele("G"),
... |
from cherrypy.test import test
test.prefer_parent_path()
import os
curdir = os.path.join(os.getcwd(), os.path.dirname(__file__))
has_space_filepath = os.path.join(curdir, 'static', 'has space.html')
import threading
import cherrypy
def setup_server():
if not os.path.exists(has_space_filepath):
file(has_spac... |
"""
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 __future__ import division, print_function, unicode_literals
__doc__="""
Creates kern strings for all kerning groups in user-defined categories and adds them to the Sample Strings. Group kerning only, glyphs without groups are ignored.
"""
import vanilla, sampleText, kernanalysis
CASE = (None, "Uppercase", "Lowerc... |
"""Module to compute commutators, with optimizations for specific systems."""
from __future__ import absolute_import
from future.utils import itervalues
import numpy
from openfermion.ops import FermionOperator
from openfermion.utils._operator_utils import normal_ordered
def commutator(operator_a, operator_b):
"""Co... |
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
dataset_train = pd.read_csv('Google_Stock_Price_Train.csv')
training_set = dataset_train.iloc[:, 1:2].values
from sklearn.preprocessing import MinMaxScaler
sc = MinMaxScaler(feature_range = (0, 1))
training_set_scaled = sc.fit_transform(training_set... |
import warnings
from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union
from google.api_core import gapic_v1
from google.api_core import grpc_helpers_async
from google.api_core import operations_v1
from google.auth import credentials as ga_credentials # type: ignore
from google.auth.transport.gr... |
import sys
from django.db import migrations, models
import django.db.models.deletion
def cache_cable_peers(apps, schema_editor):
ContentType = apps.get_model('contenttypes', 'ContentType')
Cable = apps.get_model('dcim', 'Cable')
CircuitTermination = apps.get_model('circuits', 'CircuitTermination')
if 't... |
from SignalProcessor import Signal
from os.path import join,split
from glob import glob
MAIN_DIR = '../'
WAVE_FOLDER = MAIN_DIR + 'wav/'
SINGLE_FOLDER = WAVE_FOLDER + 'single/'
COOKED_FOLDER = WAVE_FOLDER + 'single-cooked/'
def cook():
gain = [1.0,0.9,0.8,0.7,0.6,0.5,0.4,0.3,0.2,0.1]
for wavfilename in glob(joi... |
import sys
decnum = 0
binstring = sys.argv[1]
j = 1
for i in reversed(binstring):
decnum = decnum + j * int(i)
j = j * 2
print decnum |
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('products', '0028_auto_20200119_1557'),
]
operations = [
migrations.AddField(
model_name='productcategory',
name='meta_category',
field=models.BooleanField(de... |
import os
import shlex
class Clues:
DEFAULT_FILENAME = os.getcwd() + os.sep + 'subjectivity_clues' + os.sep + 'subjclueslen1-HLTEMNLP05.tff'
PRIORPOLARITY = {
'positive': 1,
'negative': -1,
'both': 0,
'neutral': 0
}
TYPE = {
'strongsubj': 2,
'weaksubj': 1
... |
input = """
number_of_moves(15).
largest_disc(4).
%------ Initial state
move(0,4321,0,0).
% ------ Goal state
query(X,Y,Z) :- move(J,X,Y,Z).
query(0,0,4321)?
%#maxint=4321.
"""
output = """
number_of_moves(15).
largest_disc(4).
%------ Initial state
move(0,4321,0,0).
% ------ Goal state
query(X,Y,Z) :- move(J,X,Y,Z).
q... |
"""Resolwe custom serializer fields."""
from collections import OrderedDict
from django.core.exceptions import ObjectDoesNotExist
from django.utils.encoding import smart_text
from rest_framework import exceptions, relations
from resolwe.permissions.models import Permission
class DictRelatedField(relations.RelatedField)... |
'''
Created on Jul 9, 2015
@author: Itai
'''
from infra.actionbot import Locator
from infra.base_page import BasePageObject
import tests.marks as m
class LoginPage(BasePageObject):
'''
classdocs
'''
_USERNAME_TB_BY = Locator.id("username")
_PASSWORD_TB_BY = Locator.id("password")
_REGISTER_LNK_B... |
from pants.base.payload import Payload
from pants.build_graph.target import Target
from pants.contrib.go.targets.go_local_source import GoLocalSource
from pants.contrib.go.targets.go_target import GoTarget
class GoThriftLibrary(Target):
"""A Go library generated from Thrift IDL files."""
def __init__(self, addr... |
import os
import tempfile
import unittest
import logging
from pyidf import ValidationLevel
import pyidf
from pyidf.idf import IDF
from pyidf.coils import CoilHeatingElectric
log = logging.getLogger(__name__)
class TestCoilHeatingElectric(unittest.TestCase):
def setUp(self):
self.fd, self.path = tempfile.mks... |
import os
from hs_build_tools.nose import eq_,ok_
from hashstore.tests import TestSetup
import hashstore.utils.fio as fio
test = TestSetup(__name__,ensure_empty=True)
log = test.log
fio.ensure_directory(test.dir)
def test_docs():
import doctest
r = doctest.testmod(fio)
ok_(r.attempted > 0, 'There is no doct... |
from __future__ import division, print_function, unicode_literals
__doc__="""
Finds and Replace in Custom Parameters of selected instances of the current font or project file.
"""
import vanilla
from Foundation import NSUserDefaults, NSString
class FindAndReplaceInInstanceParameters( object ):
def __init__( self ):
... |
from google.cloud import aiplatform_v1
async def sample_delete_hyperparameter_tuning_job():
# Create a client
client = aiplatform_v1.JobServiceAsyncClient()
# Initialize request argument(s)
request = aiplatform_v1.DeleteHyperparameterTuningJobRequest(
name="name_value",
)
# Make the requ... |
import hashlib, urllib2, optparse, random, sys
r = '\033[31m'
g = '\033[32m'
y = '\033[33m'
b = '\033[34m'
m = '\033[35m'
c = '\033[36m'
w = '\033[37m'
rr = '\033[39m'
class DrupalHash:
def __init__(self, stored_hash, password):
self.itoa64 = './0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'
... |
import json, argparse, importlib
from os.path import join, dirname
from ibm_watson import AssistantV2
from ibm_cloud_sdk_core.authenticators import IAMAuthenticator
privcontext=None
assistantService=None
def loadAndInit(confFile=None):
# Credentials are read from a file
with open(confFile) as confFile:
... |
from trac.ticket import Milestone
from bhsearch.search_resources.base import BaseIndexer
from bhsearch.search_resources.milestone_search import MilestoneIndexer
class MilestoneSearchModel(BaseIndexer):
def get_entries_for_index(self):
for milestone in Milestone.select(self.env, include_completed=True):
... |
"""Functions to work with a detection model."""
import collections
from pycoral.adapters import common
Object = collections.namedtuple('Object', ['id', 'score', 'bbox'])
"""Represents a detected object.
.. py:attribute:: id
The object's class id.
.. py:attribute:: score
The object's prediction score.
... |
__author__ = 'User'
from model.group import Group
class GroupHelper:
def __init__(self, app):
self.app = app
def open_groups_page(self):
wd = self.app.wd
if not (wd.current_url.endswith("/group.php") and len(wd.find_elements_by_name("new")) > 0):
wd.find_element_by_link_text(... |
import subprocess
import re
import os
class LinkState(object):
def __init__(self,ip):
self.ip = ip
self.getLinkState(self.ip)
# 获取链路状态
def getLinkState(self,ip):
#运行ping程序
p = subprocess.Popen(["ping.exe", ip],
stdin = subprocess.PIPE,
stdout = subpr... |
import unittest2
class FuelException(Exception):
"""Base Exception
To correctly use this class, inherit from it and define
a 'message' property. That message will get printf'd
with the keyword arguments provided to the constructor.
"""
message = "An unknown exception occurred"
def __init__(s... |
"""
OpenStack Client interface. Handles the REST calls and responses.
"""
import logging
import time
try:
import simplejson as json
except ImportError:
import json
import requests
from helloclient.openstack.common.apiclient import exceptions
from helloclient.openstack.common import importutils
_logger = logging... |
"""
Management class for VM-related functions (spawn, reboot, etc).
"""
import functools
import itertools
import time
from eventlet import greenthread
import netaddr
from oslo.config import cfg
from nova import block_device
from nova.compute import api as compute
from nova.compute import instance_types
from nova.comput... |
"""
All exceptions for QA testing framwork.
"""
__all__ = ['TestFailError', 'TestIncompleteError', 'TestSuiteAbort', 'TestRunnerError',
'ConfigError', 'ModelError', 'ModelAttributeError',
'NoImplementationError', 'InvalidObjectError', 'InvalidTestError',
'TestImplementationError',
'Repor... |
"""Tests for the ironic driver."""
from ironicclient import exc as ironic_exception
import mock
from oslo_config import cfg
from oslo_serialization import jsonutils
from oslo_utils import uuidutils
import six
from nova.api.metadata import base as instance_metadata
from nova.compute import power_state as nova_states
fro... |
'''
Module: code_set.py
Desc: stateful arib teletext decoder
Author: John O'Neil
Email: oneil.john@gmail.com
DATE: Sat, March 16th 2014
handling for code sets in japanese closed captions
'''
from arib_exceptions import UnimplimentedError
import read
DEBUG = False
class Gaiji(object):
#after ARIB std docs pg 54 onward... |
class SessionHelper:
def __init__(self, app):
self.app = app
def login(self, username, password):
wd = self.app.wd
self.app.open_home_page()
wd.find_element_by_name("username").click()
wd.find_element_by_name("username").clear()
wd.find_element_by_name("username")... |
from django.conf.urls import url
from atlas.production_request.views import *
app_name='production_request'
urlpatterns = [
url(r'^prepare_slice/$', prepare_slice,name='prepare_slice'),
url(r'^steps_for_requests/$', get_steps_api,name='get_steps_api'),
url(r'^save_slice/$', save_slice,name='save_slice'),
... |
"""Base classes for pytest."""
import pytest
import app
@pytest.fixture
def testapp():
"""Provide the rover service."""
return app |
from collections import defaultdict
from datetime import date, datetime
from ggrc.extensions import get_extension_modules
from ggrc.models import Notification, NotificationConfig
from ggrc.utils import merge_dict
from ggrc import db
from sqlalchemy import and_
class NotificationServices():
def __init__(self):
sel... |
from helper import unittest, PillowTestCase, hopper
from PIL import Image
import io
class TestFileBmp(PillowTestCase):
def roundtrip(self, im):
outfile = self.tempfile("temp.bmp")
im.save(outfile, 'BMP')
reloaded = Image.open(outfile)
reloaded.load()
self.assertEqual(im.mode,... |
import java, csv, sys, datetime, os, re
from hec.script import MessageBox
from hec.heclib.dss import HecDss
from hec.heclib.util import HecTime
from hec.io import TimeSeriesContainer
from optparse import OptionParser
sys.path.append("./simplejson-2.5.2")
import simplejson as json
try :
try :
print 'Jython v... |
'''
IPMI Torture
------------
Use several threads in `op-test` to poke IPMI concurrently in a number
of "safe" ways, and see when the BMC explodes.
'''
import unittest
import time
import threading
import OpTestConfiguration
from common.OpTestSystem import OpSystemState
from common.OpTestConstants import OpTestConstants... |
from tempest.api.volume import base
from tempest.common.utils import data_utils
from tempest import config
from tempest import test
CONF = config.CONF
class SnapshotsActionsV2Test(base.BaseVolumeAdminTest):
@classmethod
def skip_checks(cls):
super(SnapshotsActionsV2Test, cls).skip_checks()
if no... |
"""
Model classes that map instance Ip to dns record.
"""
from trove.db import get_db_api
from trove.common import exception
from trove.common.models import ModelBase
from trove.openstack.common import log as logging
from trove.openstack.common.gettextutils import _
LOG = logging.getLogger(__name__)
def persisted_model... |
'''
A script for cleaning up (sub)directories in a directory tree which do not contain files matching a given content type pattern, e.g. media files such as "*.mp3" or "*.mpg" by default.
s
@author: Todd Shore
@copyright: 2014 Todd Shore. Licensed for distribution under the Apache License 2.0: See the files "NOTICE" an... |
import re
from JumpScale import j
class RegexTemplates_FindLines:
"""
regexexamples which find lines
"""
# TODO: for all methods do input checking (id:20)
def findCommentlines(self):
return "^( *#).*"
def findClasslines(self):
return "^class .*"
def findDeflines(self):
... |
from datetime import timedelta
from django.test import TestCase
from django.utils import timezone
from django.contrib.auth.models import User
from main.models import Session
from donations.models import TopList
from donations.support import add_donation, output_for_top
class SimpleTopDonations(TestCase):
def setUp(... |
'''
ÈÎÎñ
Ç붨ÒåÒ»¸ö greet() º¯Êý£¬Ëü°üº¬Ò»¸öĬÈϲÎÊý£¬Èç¹ûûÓд«È룬´òÓ¡ 'Hello, world.'£¬Èç¹û´«È룬´òÓ¡ 'Hello, xxx.'
'''
def greet(str1='world'):
print 'Hello,',str1+'.'
greet()
greet('Bart')
'''
¶¨ÒåĬÈϲÎÊý
¶¨Ò庯ÊýµÄʱºò£¬»¹¿ÉÒÔÓÐĬÈϲÎÊý¡£
ÀýÈçPython×Ô´øµÄ int() º¯Êý£¬Æäʵ¾ÍÓÐÁ½¸ö²ÎÊý£¬ÎÒÃǼȿÉÒÔ´«Ò»¸ö²ÎÊý£¬Ó... |
"""
.. module: lemur.roles.models
:platform: unix
:synopsis: This module contains all of the models need to create a role within Lemur
:copyright: (c) 2018 by Netflix Inc., see AUTHORS for more
:license: Apache, see LICENSE for more details.
.. moduleauthor:: Kevin Glisson <kglisson@netflix.com>
"""
fro... |
import os
import logging
import logging.config
import ConfigParser
this_dir = os.path.dirname(__file__)
logging.config.fileConfig(os.path.join(this_dir, 'logging.conf'))
from pyhdb.exceptions import *
from pyhdb.connection import Connection
from pyhdb.protocol.lobs import Blob, Clob, NClob
apilevel = "2.0"
threadsafety... |
from django.conf.urls import url
from django.views.generic import RedirectView
from outreach import views
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^mindset/$', views.mindset, name='mindset'),
url(r'^edit_mindset_modules/$',
views.update_mindset_modules,
name='update_minds... |
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('dicom_visio', '0003_dicom'),
]
operations = [
migrations.AddField(
model_name='mdatum',
name='dicom',
field=models.Fo... |
from kore.plugins.exceptions import PluginNotFoundError
class PluginsProvider(object):
def __init__(self, iterator):
self.iterator = iterator
self._plugins_cache = None
def get(self, name):
try:
return self.plugins[name]
except KeyError:
raise PluginNotFou... |
"""
Vericred API
Vericred's API allows you to search for Health Plans that a specific doctor
accepts.
Visit our [Developer Portal](https://developers.vericred.com) to
create an account.
Once you have created an account, you can create one Application for
Production and another for our Sandbox (select the approp... |
from core.models import Group
from rest_framework import serializers
from api.v2.serializers.fields.base import UUIDHyperlinkedIdentityField
from api.v2.serializers.summaries import UserSummarySerializer
class GroupSerializer(serializers.HyperlinkedModelSerializer):
url = UUIDHyperlinkedIdentityField(
view_... |
from __future__ import absolute_import, unicode_literals
from datetime import timedelta
from django.conf import settings
CSRF_FAILURE_VIEW = settings.CSRF_FAILURE_VIEW
EXPIRATION_TIMEDELTA = getattr(
settings, 'S3UPLOAD_EXPIRATION_TIMEDELTA', timedelta(minutes=30))
SET_CONTENT_TYPE = getattr(settings, 'S3UPLOAD_SET... |
"""
Offer time listening automation rules.
For more details about this automation rule, please refer to the documentation
at https://home-assistant.io/docs/automation/trigger/#time-trigger
"""
import asyncio
import logging
import voluptuous as vol
from homeassistant.core import callback
from homeassistant.const import ... |
"""Tests for tensorflow.ops.gradients."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import warnings
import numpy as np
from tensorflow.python.framework import constant_op
from tensorflow.python.framework import dtypes
from tensorflow.python.framework im... |
import random
import time
def isSorted(numbers):
length = len(numbers)
for num, item in enumerate(numbers):
if (num + 1) == length:
return True
elif item > numbers[num + 1]:
return False
def taco(numbers):
length = len(numbers)
index = random.randint(0,(length-1))... |
"""Tests for the keychain object."""
import unittest
from dfvfs.credentials import keychain
from dfvfs.lib import definitions
from dfvfs.path import factory
from tests import test_lib as shared_test_lib
class KeychainTest(shared_test_lib.BaseTestCase):
"""Class to test the keychain object."""
def testCredentialGetS... |
import copy
import json
from flask import Flask, make_response, request
from flask.ext.cors import CORS
from subprocess import call
app = Flask(__name__)
app.debug = True
CORS(app)
e_lines = {}
@app.route('/SCA_ETH_FDFr_EC/findByState', methods=['GET'])
def get_elines_by_state():
resp = make_response(json.dumps(e_l... |
"""Define core operations for xarray objects.
"""
import numpy as np
try:
import dask.array as da
except ImportError:
pass
def dask_rolling_wrapper(moving_func, a, window, min_count=None, axis=-1):
'''wrapper to apply bottleneck moving window funcs on dask arrays'''
# inputs for ghost
if axis < 0:
... |
"""
Local filesystem backend for attachments.
"""
import hashlib
import os
import os.path
try:
import urlparse
except ImportError:
from urllib import parse as urlparse
import flask
from scoreboard import main
app = main.get_app()
def attachment_dir(create=False):
"""Return path and optionally create attachm... |
import os
import unittest
import unittest.mock as mock
from django.conf import settings
from django.db.migrations import Migration
from django_migration_linter import (
IgnoreMigration,
MigrationLinter,
analyse_sql_statements,
get_migration_abspath,
)
class OperationsIgnoreMigration(Migration):
oper... |
from io import StringIO
from unittest import TestCase
from py2neo.collections import PropertyDict
from py2neo.cypher import Record
from py2neo.data import Subgraph, Walkable, Node, Relationship, Path, walk
from py2neo.export import Table
KNOWS = Relationship.type("KNOWS")
LIKES = Relationship.type("LIKES")
DISLIKES = R... |
import template
class Page(template.StandardPage):
def get(self):
template.StandardPage.render_page(self, 'register.html', {}) |
class Solution:
def checkPerfectNumber(self, num):
"""
:type num: int
:rtype: bool
"""
if not num:
return False
divisors = []
for i in range(1, num):
if num % i == 0:
divisors.append(i)
return sum(divisors) == nu... |
import tempfile
from unittest.mock import Mock, patch
from tests.base import SpaceTest
from .base import LibModelTest
from lib.model import query
import lib.model as model
from lib.engine import SpaceEngine
class TestLibModelQuery(LibModelTest):
def setUp(self):
self.expected_exports = [query.ModelQueryMixi... |
import time
import fixtures
from keystoneclient.auth.identity import v3 as identity_v3
from keystoneclient import session
from neutronclient.neutron import client as neutron_client
from novaclient import client as nova_client
from novaclient import exceptions as nova_exc
from oslo_utils import uuidutils
from saharaclie... |
"""
This module is the test command of bowl.
Created on 11 August 2014
@author: Charlie Lewis
"""
import os
class test(object):
"""
This class is responsible for the test command of the cli.
"""
@classmethod
def main(self, args):
print args
if args.f:
pass
else:
... |
from models.group import Group
from models.contact import Contact
def test_remove_contact_from_group(app, db, orm):
# check if there is any contact-group in 'address_in_groups' table
relations = len(db.get_relations_list())
# if there is no contacts in group create group and contact in group
if relation... |
from django.db import models
from base.models import CRUDModel
from user.models import UserModel
from locus.models import AddressModel
from django.utils.translation import ugettext as _
import logging
class CategoryModel(CRUDModel):
name = models.CharField(max_length=30)
details = models.CharField(max_length=50... |
import random
import string
from flanker.addresslib import address
from mock import patch
from nose.tools import assert_equal, assert_not_equal
from nose.tools import nottest
from ... import skip_if_asked
DOMAIN = '@hotmail.com'
SAMPLE_MX = 'mx0.hotmail.com'
@nottest
def mock_exchanger_lookup(arg, metrics=False):
m... |
import sys
from time import sleep
from Tiscamera.list_formats import select_format
from Tiscamera.list_formats import list_formats, get_frame_rate_list
import gi
gi.require_version("Tcam", "0.1")
gi.require_version("Gst", "1.0")
from gi.repository import Tcam, Gst, GLib
from threading import Thread
import cv2
import nu... |
"""Contains utility functions for interacting with the Android build system."""
import os
import re
import subprocess
import errors
import logger
def GetTop():
"""Returns the full pathname of the "top" of the Android development tree.
Assumes build environment has been properly configured by envsetup &
lunch/choo... |
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 'CarouselPluginModel'
db.create_table(u'cmsplugin_javascript_carouselpluginmodel', (
... |
import subprocess
class AuthenticationParserError(Exception):
"""
Error while parsing a token.
Args:
- line(int, optional): line where the error occurred.
"""
def __init__(self, line=-1):
self.line = line
Exception.__init__(self, "Error while parsing a token at line %d." % line)
class Authentication:
"""
... |
"""
Display functions for PSFs and OTFs.
Copyright (c) 2021, David Hoffman
"""
import typing
import matplotlib as mpl
import matplotlib.font_manager as fm
import matplotlib.patches as patches
import matplotlib.patheffects as path_effects
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import ImageGrid
impo... |
class Plugin(object):
def __init__(self, row):
self.id = row[0]
self.uploaded = row[1]
self.name = row[2]
self.path = row[3]
self.major_version = row[4]
self.minor_version = row[5]
self.maintenance_version = row[6] |
from .. core import Component, implements, ExtensionPoint
from . api import (
IndexAPI,
IndexAPIConfigurationProvider,
IndexPipelineConfig,
IndexAPIProvider,
)
class IndexPipelineProvider(Component):
""" This implementation of :py:class:`docido_sdk.index.IndexAPIProvider`
provides pipelines of :... |
import glob
for path in glob.glob("x-*"):
print("found %s" % path) |
"""
This demo implements FastText[1] for sentence classification. This demo should be run in eager mode and
can be slower than the corresponding demo in graph mode.
FastText is a simple model for text classification with performance often close
to state-of-the-art, and is useful as a solid baseline.
There are some impo... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.