code stringlengths 1 199k |
|---|
import json
import mock
from django.core.urlresolvers import reverse
from django.db import OperationalError
from django.test import TestCase
class LandingViewTests(TestCase):
def test_landing_page_renders(self):
response = self.client.get(reverse('home-landing'))
self.assertEqual(response.status_cod... |
import pytest
from pages.home import HomePage
@pytest.mark.nondestructive
def test_navigation(base_url, selenium):
locale = 'de'
page = HomePage(selenium, base_url, locale).open()
firefox_page = page.navigation.open_firefox(locale)
assert firefox_page.seed_url in selenium.current_url
page.open()
... |
from django_pglocks import advisory_lock
def detail_route(methods=['get'], **kwargs):
"""
Used to mark a method on a ViewSet that should be routed for detail requests.
"""
def decorator(func):
func.bind_to_methods = methods
func.detail = True
func.permission_classes = kwargs.get(... |
from leap.bitmask.mail.outgoing.service import OutgoingMail
from mock import patch
from twisted.mail.smtp import User
from twisted.trial import unittest
from mockito import mock, when, verify, any, unstub
from pixelated.adapter.services.mail_sender import MailSender, MailSenderException
from pixelated.adapter.model.mai... |
import abc
import math
import numpy as np
import torch
import torch.nn as nn
def rezeroWeights(m):
"""
Function used to update the weights after each epoch.
Call using :meth:`torch.nn.Module.apply` after each epoch if required
For example: ``m.apply(rezeroWeights)``
:param m: SparseWeightsBase module
"""
... |
from . import models
from . import wizards
from . import controllers |
import tornado, tornado.ioloop, tornado.web
import os, uuid, glob, shutil
import fontforge, re, zipfile
exts = '.woff', '.ttf', '.otf', '.svg', '.eot'
class Upload(tornado.web.RequestHandler):
@staticmethod
def css_generator(root, name, fullname):
cssfile = root + '/' + name + '/' + name + ".css"
template = "@fon... |
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import division
import hashlib
import re
from django.conf import settings
from django.core.mail import send_mail
from django.core.exceptions import (ValidationError, MultipleObjectsReturned,
... |
from flask import request
from webargs import Arg
from werkzeug.exceptions import Forbidden
from werkzeug.useragents import UserAgent
from skylines.api import auth
def register(app):
"""
:param flask.Flask app: a Flask app
"""
from .errors import register as register_error_handlers
from .airports im... |
"""
Forum Leaderboard XBlock
Shows the top threads for a given discussion ID by vote.
"""
from .leaderboard import LeaderboardXBlock
from xblock.core import XBlock
from xblock.exceptions import JsonHandlerError
from xblock.fields import Scope, String
from xblock.validation import ValidationMessage
try:
import lms.l... |
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('representatives', '0017_auto_20160623_2201'),
]
operations = [
migrations.AlterField(
model_name='group',
name='name',
... |
db.define_table('street',
Field('id', 'id'),
Field('name', 'string', length=250, unique=True),
migrate=migrate)
db.define_table('street_map',
Field('id', 'id'),
Field('street_id', 'integer'),
Field('house_number_from', 'integer'),
Field('house_number_to', 'integer'),
Field('city', 'strin... |
try:
from opencog.atomspace import TruthValue, confidence_to_count, types as t
except ImportError:
from atomspace_remote import TruthValue, types as t, confidence_to_count, types as t
import formulas
from tree import *
import math
def evaluation_link_template(predicate = None, arguments = None):
if predicat... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
def get_robot_base_position(robot):
"""Gets the base position of robot."""
# TODO(b/151975607): Clean this after robot interface migration.
if hasattr(robot, "GetBasePosition"):
return robot.GetBasePos... |
VERSION = "1.0.6" |
"""Render the user panel and process all user messages.
This module patches the :class:`controller.MSGHandler`
class, adding the
:meth:`controller.MSGHandler.send_user_not_loaded_error`,
:meth:`controller.MSGHandler.send_room_not_loaded_error` and
:meth:`controller.MSGHandler.logout_and_close` methods.
"""
from functoo... |
from __future__ import unicode_literals
LANG = "en_US" # can be en_US, fr_FR, ...
ANDROID_ID = None # "38c6523ac43ef9e1"
GOOGLE_LOGIN = None # 'someone@gmail.com'
GOOGLE_PASSWORD = None # 'yourpassword'
AUTH_TOKEN = None # "yyyyyyyyy"
if ANDROID_ID == NONE
or all([each == None for each in [G... |
from superdesk.resource import Resource
from superdesk.services import BaseService
import os.path
import re
import json
try:
import settings
except ImportError:
# settings doesn't exist during tests
settings = None
import logging
logger = logging.getLogger(__name__)
GITHUB_TAG_HREF = 'https://github.com/sup... |
import unittest
from peacock.Input.ExecutableInfo import ExecutableInfo
from peacock.utils import Testing
class Tests(Testing.PeacockTester):
def checkFile(self, output, gold_file, write_output=False):
if write_output:
with open("tmp_out.txt", "w") as f:
f.write(output)
w... |
from uuid import UUID
from sqlobject import SQLObject, UuidCol
from sqlobject.tests.dbtest import setupClass
testuuid = UUID('7e3b5c1e-3402-4b10-a3c6-8ee6dbac7d1a')
class UuidContainer(SQLObject):
uuiddata = UuidCol(default=None)
def test_uuidCol():
setupClass([UuidContainer], force=True)
my_uuid = UuidCont... |
from .base import Capability, BaseObject, Field, StringField, FloatField, \
IntField, UserError
from .date import DateField
__all__ = ['MagnetOnly', 'Torrent', 'CapTorrent']
class MagnetOnly(UserError):
"""
Raised when trying to get URL to torrent but only magnet is available.
"""
def ... |
from datetime import date, datetime
from dateutil import relativedelta
import json
import time
from openerp.osv import fields, osv
from openerp.tools import float_compare
from openerp.tools.translate import _
from openerp.tools import DEFAULT_SERVER_DATETIME_FORMAT, DEFAULT_SERVER_DATE_FORMAT
from openerp import SUPERU... |
import netaddr
from oslo_log import log as logging
from oslo_utils import uuidutils
import webob
from nova.api.openstack import common
from nova.api.openstack.compute.schemas import floating_ips
from nova.api.openstack import extensions
from nova.api.openstack import wsgi
from nova.api import validation
from nova impor... |
from synapse.types import EventID, RoomID, UserID
from synapse.api.errors import SynapseError
from synapse.api.constants import EventTypes, Membership
class EventValidator(object):
def validate(self, event):
EventID.from_string(event.event_id)
RoomID.from_string(event.room_id)
required = [
... |
"""Unit tests.""" |
"""Various learning rate decay functions."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensorflow.python.framework import ops
from tensorflow.python.ops import math_ops
from tensorflow.python.ops import control_flow_ops
def exponential_decay(learni... |
from alembic import op
import sqlalchemy as sa
from neutron.db import migration
"""subnet force network id
Revision ID: c613d0b82681
Revises: 63fd95af7dcd
Create Date: 2019-08-19 11:15:14.443244
"""
revision = 'c613d0b82681'
down_revision = '63fd95af7dcd'
neutron_milestone = [migration.TRAIN]
def upgrade():
op.alte... |
import os.path
import re
import xbmcgui
import urllib
import common
from string import lower
from entities.CListItem import CListItem
from xml.dom.minidom import parse as parseXml
from utils import fileUtils as fu
from utils.xbmcUtils import getKeyboard, getImage
from utils import regexUtils
class FavouritesManager:
... |
"""The main command group for genomics.
Everything under here will be the commands in your group. Each file results in
a command with that name.
This module contains a single class that extends base.Group. Calliope will
dynamically search for the implementing class and use that as the command group
for this command t... |
from rdflib import Literal
from classes import ldp
from namespaces import dcterms, iana, ore, rdf
ns = ore
class Proxy(ldp.Resource):
def __init__(self, position, proxy_for, proxy_in):
super(Proxy, self).__init__()
self.title = 'Proxy for {0} in {1}'.format(position, proxy_in.title)
self.pre... |
import logging
from argparse import ArgumentParser
from typing import Any, List
from django.conf import settings
from django.db import transaction
from zerver.lib.logging_util import log_to_file
from zerver.lib.management import ZulipBaseCommand
from zerver.models import UserProfile
from zproject.backends import ZulipL... |
import logging
from lib import constants
def set_default_file_handler(logger, log_path, log_level=logging.DEBUG):
"""
:type logger: logging.Logger
:param log_path: str
:param log_level: str
"""
logger.setLevel(log_level)
formatter = logging.Formatter(constants.log.DEFAULT_FORMAT)
fh = logging.FileHandle... |
"""Fake data generator.
To use:
1. Install fake-factory.
pip install fake-factory
2. Create your OSF user account
3. Run the script, passing in your username (email).
::
python -m scripts.create_fakes --user fred@cos.io
This will create 3 fake public projects, each with 3 fake contributors (with
you as the ... |
"""
Network
-------
Returns information about the network including ip address, dns, data
sent/received, and some error information.
:const IP_PRIVATE:
set of private class A, B, and C network ranges
.. seealso::
:rfc:`1918`
:const IP_NONNETWORK:
set of non-network address ranges including all of th... |
import zmq
import argparse
def setup(location=None, server=False):
context = zmq.Context()
sender = context.socket(zmq.PUB)
receiver = context.socket(zmq.SUB)
if server:
sender.bind('tcp://{}'.format(location[0]))
receiver.bind('tcp://{}'.format(location[1]))
else:
sender.con... |
"""A fake minimal version of netifaces module.
This module should only be used to work around a limitation of the travis-ci
test environment.
For more information on appropriate use cases see: fake-packages/README.md
"""
AF_INET = 2
AF_LINK = 17
def interfaces(self): # pragma: no cover
return ['lo', 'eth0']
def if... |
import mock
from sahara import conductor
from sahara import context
from sahara.tests.unit import base
from sahara.tests.unit.conductor import test_api
from sahara.utils import general
class UtilsGeneralTest(base.SaharaWithDbTestCase):
def setUp(self):
super(UtilsGeneralTest, self).setUp()
self.api ... |
"""
Contains the actual class that runs novaclient (or the executable chosen by
the user)
"""
import os
import subprocess
import sys
import click
from . import credentials
def execute_executable(nova_args, env_vars):
"""
Executes the executable given by the user.
Hey, I know this method has a silly name, bu... |
from django.template import TemplateDoesNotExist
from django.template.loader import get_template
_cached_name_lookups = {}
def select_template_name(template_name_list, using=None):
"""
Given a list of template names, find the first one that exists.
"""
if not isinstance(template_name_list, tuple):
... |
import logging
from django.conf import settings
from django.utils.translation import ugettext_lazy as _
import six
from horizon import exceptions
from openstack_dashboard import api
LOG = logging.getLogger(__name__)
def flavor_list(request):
"""Utility method to retrieve a list of flavors."""
try:
retur... |
"""Inception-ResNet V2 model for Keras.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from keras_applications import inception_resnet_v2
from tensorflow.python.util.tf_export import tf_export
InceptionResNetV2 = inception_resnet_v2.InceptionResNetV2
dec... |
import uuid
import wsme
from wsme.rest import json as wjson
from wsme import types as wtypes
from solum.api.controllers.v1.datamodel import types as api_types
class Requirement(wtypes.Base):
requirement_type = wtypes.text
"Type of requirement."
fulfillment = wtypes.text
"The ID of the service."
class Se... |
from __future__ import absolute_import
import io
import os
import sys
from twisted.logger import eventsFromJSONLogFile, textFileLogObserver
import six
def print_log(path=None, output_stream=None):
if path is None:
from pychron.paths import paths
path = os.path.join(paths.log_dir, "pps.log.json")
... |
"""
PGLock object
"""
from networking_plumgrid.neutron.plugins.db import api as db_api
class PGLock(object):
#fields = {
# 'uuid': fields.StringField(),
# 'created_at': fields.DateTimeField(read_only=True),
#}
@classmethod
def create(cls, uuid):
return db_api.pg_lock_create(uuid)
... |
import os
import sys
import unittest
from pyorient.exceptions import PyOrientCommandException, PyOrientConnectionException, PyOrientException
from pyorient import OrientSocket
from pyorient.messages.connection import ConnectMessage, ShutdownMessage
from pyorient.messages.database import DbExistsMessage, DbOpenMessage, ... |
from __future__ import annotations
import atexit
import errno
import os
import shutil
import stat
import tempfile
import threading
import uuid
from collections import defaultdict
from contextlib import contextmanager
from typing import Any, Callable, DefaultDict, Iterator, Sequence, overload
from typing_extensions impo... |
from django.conf.urls import patterns, include, url
urlpatterns = patterns('',
url(r'^$', 'spirit.views.admin.index.dashboard', name='admin'),
url(r'^index/', include('spirit.urls.admin.index')),
url(r'^category/', include('spirit.urls.admin.category')),
url(r'^comment/flag/', include('spirit.urls.admin... |
"""
iLO Inspect Interface
"""
from oslo_log import log as logging
from oslo_utils import importutils
from ironic.common import exception
from ironic.common.i18n import _
from ironic.common.i18n import _LI
from ironic.common.i18n import _LW
from ironic.common import states
from ironic.common import utils
from ironic.con... |
from kivy.uix.scrollview import ScrollView
from kivy.uix.label import Label
from kivy.lang import Builder
from kivy.properties import ObjectProperty, StringProperty, NumericProperty
from kivy.clock import Clock
from kivy.logger import Logger
import model
class Catalina_Panel(ScrollView):
'''
This is a simple pa... |
"""
Definition of urls for $safeprojectname$.
"""
from django.conf.urls import patterns, include, url
urlpatterns = patterns('',
# Examples:
# url(r'^$', '$safeprojectname$.views.home', name='home'),
# url(r'^$safeprojectname$/', include('$safeprojectname$.$safeprojectname$.urls')),
# Uncomment the admi... |
'''
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this ... |
from django.conf.urls.defaults import patterns, url
from .views import IndexView, CreateView, EditView
urlpatterns = patterns('horizon.dashboards.syspanel.flavors.views',
url(r'^$', IndexView.as_view(), name='index'),
url(r'^create/$', CreateView.as_view(), name='create'),
url(r'^(?P<id>[^/]+)/edit/$', Edit... |
"""
provide web service for DDM
"""
import re
import sys
import cPickle as pickle
from config import panda_config
from taskbuffer.WrappedPickle import WrappedPickle
from pandalogger.PandaLogger import PandaLogger
_logger = PandaLogger().getLogger('DataService')
class DataService:
# constructor
def __init__(self... |
import exceptions
import time
import subprocess
import re
from Utils.WAAgentUtil import waagent
class CommonActions:
def __init__(self, logger):
self.logger = logger
def log_run_get_output(self, cmd, should_log=True):
"""
Execute a command in a subshell
:param str cmd: The comman... |
from a10sdk.common.A10BaseClass import A10BaseClass
class GslbLoadFileList(A10BaseClass):
"""This class does not support CRUD Operations please use parent.
:param geo_location_load_filename: {"minLength": 1, "maxLength": 63, "type": "string", "description": "Specify file to be loaded", "format": "string-rlx"}
... |
from __future__ import print_function
import os
import sys
import mxnet as mx
import numpy as np
fast_rcnn_path = None
sys.path.insert(0, os.path.join(fast_rcnn_path, 'caffe-fast-rcnn', 'python'))
sys.path.insert(0, os.path.join(fast_rcnn_path, 'lib'))
import caffe
from rcnn.symbol import get_symbol_vgg_test
def load_m... |
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.common.action_chains import ActionChains
from random import randint
import unittest
from qa.web_tests import config
import time
class TestAddDeleteService(unit... |
import logging
from .cortex_m import CortexM
from .core_ids import (CORE_TYPE_NAME, CoreArchitecture, CortexMExtension)
from ..core.target import Target
from .cortex_m_core_registers import CoreRegisterGroups
LOG = logging.getLogger(__name__)
class CortexM_v8M(CortexM):
"""@brief Component class for a v8.x-M archit... |
from __future__ import absolute_import
from .factory import toolkit_factory
myTabularEditor = toolkit_factory("tabular_editor", "myTabularEditor") |
"""
Abstract: Operations on a social graph as examples for how to use the core concept 'network'
"""
__author__ = "Michel Zimmer"
__copyright__ = "Copyright 2014"
__credits__ = ["Michel Zimmer"]
__license__ = ""
__version__ = "0.1"
__maintainer__ = ""
__email__ = ""
__date__ = "December 2014"
__status__ = "Development... |
"""A class for storing iteration-specific metrics.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
class IterationStatistics(object):
"""A class for storing iteration-specific metrics.
The internal format is as follows: we maintain a mapping from keys... |
import pytest
import mock
from django.test import RequestFactory
from django.core.urlresolvers import reverse
from django.core.exceptions import PermissionDenied
from django.contrib.auth.models import Permission, Group, AnonymousUser
from tests.base import AdminTestCase
from osf.models import Preprint, OSFUser, Preprin... |
"""
Management class for Storage-related functions (attach, detach, etc).
"""
import time
from os_brick.initiator import connector
from os_win import utilsfactory
from oslo_log import log as logging
from oslo_utils import strutils
import nova.conf
from nova import exception
from nova.i18n import _
from nova import util... |
from django.test import TestCase
from whats_fresh.whats_fresh_api.models import Story
from django.contrib.gis.db import models
class StoryTestCase(TestCase):
def setUp(self):
self.expected_fields = {
'name': models.TextField,
'history': models.TextField,
'facts': models.T... |
import os
import hashlib
from io import BytesIO
from mapproxy.compat.image import Image
from mapproxy.test.image import is_jpeg, tmp_image
from mapproxy.test.http import mock_httpd
from mapproxy.test.system import module_setup, module_teardown, SystemTest, make_base_config
from nose.tools import eq_
test_config = {}
ba... |
from collections import Sequence
from django.conf import settings
from openstack_dashboard.api import nova
from openstack_dashboard.api.base import Quota
from openstack_dashboard.api.nova import flavor_list
from openstack_dashboard.api.nova import novaclient
from openstack_dashboard.api.nova import server_list
from ope... |
import os
import re
import time
import datetime
import Queue
import subprocess
import devops_pb2
import fabric_pb2
import chaincode_pb2
from orderer import ab_pb2
from common import common_pb2
import bdd_test_util
import bdd_grpc_util
from grpc.beta import implementations
from grpc.framework.interfaces.face.face import... |
from datetime import datetime
from openflow.optin_manager.sfa.util.sfatime import utcparse, datetime_to_epoch
from openflow.optin_manager.sfa.models import ExpiringComponents
class ExpirationManager:
@staticmethod
def extend_expiration(slice_name,authority,time_extension):
#time_extended = time_extensio... |
from builtins import oct, object
import logging
import sys
from desktop import appmanager
from desktop.conf import default_ssl_validate
from desktop.lib.conf import Config, coerce_bool, validate_path
if sys.version_info[0] > 2:
from django.utils.translation import gettext as _, gettext_lazy as _t
else:
from django.... |
from AlgorithmImports import *
class BasicTemplateOptionsDailyAlgorithm(QCAlgorithm):
UnderlyingTicker = "GOOG"
def Initialize(self):
self.SetStartDate(2015, 12, 23)
self.SetEndDate(2016, 1, 20)
self.SetCash(100000)
self.optionExpired = False
equity = self.AddEquity(self.... |
import socket
import json
import time
import copy
import os
import hashlib
import certifi
import urllib3
import logging
log = logging.getLogger(__name__)
import hubblestack.status
hubble_status = hubblestack.status.HubbleStatus(__name__)
from . dq import DiskQueue, NoQueue, QueueCapacityError
__version__ = '1.0'
_max_c... |
"""Support for IGN Sismologia (Earthquakes) Feeds."""
from datetime import timedelta
import logging
from typing import Optional
import voluptuous as vol
from homeassistant.components.geo_location import PLATFORM_SCHEMA, GeolocationEvent
from homeassistant.const import (
ATTR_ATTRIBUTION,
CONF_LATITUDE,
CONF... |
from peyotl.ott import create_pruned_and_taxonomy_for_tip_ott_ids
from peyotl.phylo.compat import compare_bits_as_splits, SplitComparison
from peyotl.utility import any_early_exit, get_logger
_LOG = get_logger(__name__)
def evaluate_tree_rooting(nexson, ott, tree_proxy):
"""
Returns None if the taxanomy contrib... |
import capdl
tcb = capdl.TCB('my_tcb')
tcb.ip = 0x8000
tcb.sp = 0xdeadbeef
tcb.init += [0xcafe, 0xdeaf]
ep = capdl.Endpoint('my_ep')
ep_cap = capdl.Cap(ep)
tcb['fault_ep'] = ep_cap
cspace = capdl.CNode('my_cnode', 28) # <-- size in bits
vspace = capdl.PageDirectory('my_pd')
tcb['cspace'] = capdl.Cap(cspace)
tcb['vspace... |
import sys
import io
import os
import tempfile
import subprocess
import shutil
import shlex
from os.path import join, dirname, isfile, splitext
from datetime import datetime
from acrylamid import log, readers, commands
from acrylamid.errors import AcrylamidException
from acrylamid.compat import string_types
from acryla... |
from pylab import *
import matplotlib
import numpy
import scipy.stats
from scipy.stats.distributions import norm
from scipy.stats.distributions import poisson
from scipy.stats.distributions import gamma
from datetime import date
from datetime import timedelta
import os.path
import random
days = ["Mon", "Tue", "Wed", "T... |
from gevent.coros import Semaphore
class WebSocket(object):
def __init__(self, sock, rfile, environ):
self.rfile = rfile
self.socket = sock
self.origin = environ.get('HTTP_ORIGIN')
self.protocol = environ.get('HTTP_SEC_WEBSOCKET_PROTOCOL', 'unknown')
self.path = environ.get('... |
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding field 'Check.supports_https'
db.add_column('check_check', 'supports_https',
self.gf('django.db.models.fi... |
import re
from datetime import datetime
from tower import ugettext_lazy as _
STATUS_NULL = 0
STATUS_UNREVIEWED = 1
STATUS_PENDING = 2
STATUS_NOMINATED = 3
STATUS_PUBLIC = 4
STATUS_DISABLED = 5
_STATUS_LISTED = 6 # Deprecated. See bug 616242
STATUS_BETA = 7
STATUS_LITE = 8
STATUS_LITE_AND_NOMINATED = 9
STATUS_PURGATORY... |
"""
Django settings for webui project.
For more information on this file, see
https://docs.djangoproject.com/en/1.7/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.7/ref/settings/
"""
import os
import sys
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
if B... |
from __future__ import absolute_import
import calendar
import datetime
import jwt
import time
from sentry import options
def get_jwt(github_id=None, github_private_key=None):
if github_id is None:
github_id = options.get('github-app.id')
if github_private_key is None:
github_private_key = option... |
import m5
from m5.objects import *
m5.util.addToPath('../configs/common')
class MyCache(BaseCache):
assoc = 2
block_size = 64
hit_latency = 2
response_latency = 2
mshrs = 10
tgts_per_mshr = 5
class MyL1Cache(MyCache):
is_top_level = True
tgts_per_mshr = 20
cpu = DerivO3CPU(cpu_id=0)
cpu.... |
from tests import AsyncHTTPTestCase
class BasicAuthTests(AsyncHTTPTestCase):
def test_with_single_creds(self):
with self.mock_option('basic_auth', ['foo:bar']):
r = self.fetch('/')
self.assertEqual(401, r.code)
r = self.fetch('/', auth_username='foo', auth_password='bar')... |
from dbbackup import utils
from .base import BaseCommandDBConnector
class MongoDumpConnector(BaseCommandDBConnector):
"""
MongoDB connector, creates dump with ``mongodump`` and restore with
``mongorestore``.
"""
dump_cmd = 'mongodump'
restore_cmd = 'mongorestore'
object_check = True
drop... |
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "CAPCollector.settings")
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv) |
"""
Classes and utilites to keep track of files associated to an analysis.
The main class is `FileArchive`, which keep track of all the files associated to an analysis.
The `FileHandle` helper class encapsulates information on a particular file.
"""
from __future__ import absolute_import, division, print_function
impor... |
""" Formula for building vim """
from pakit import Git, Recipe
class Vim(Recipe):
"""
The mode based terminal editor for programmers.
By default built with lua & python 2.x interpreters.
"""
def __init__(self):
super(Vim, self).__init__()
self.src = 'https://github.com/vim/vim.git'
... |
from nose.tools import eq_, ok_
from django.conf import settings
from funfactory.urlresolvers import reverse
from airmozilla.main.models import Event, Tag
from airmozilla.manage import related
from .base import ManageTestCase
class TestRelatedContent(ManageTestCase):
def setUp(self):
super(TestRelatedConten... |
from tests.testing_framework.base_test_cases import BaseTestCase
from flexmock import flexmock
from hamcrest import *
from framework.plugin.plugin_handler import PluginHandler
from tests.testing_framework.utils import ExpensiveResourceProxy
from tests.testing_framework.config.environments import PluginConfigEnvironment... |
"""
views specific to committees
"""
from django.shortcuts import render
from django.http import Http404
from django.template.response import TemplateResponse
from django.views.decorators.csrf import ensure_csrf_cookie
from djpjax import pjax
from billy.core import settings
from billy.utils import popularity
from b... |
import collections
import json
from unittest import mock
from django.contrib.auth.models import Group
from django.contrib.contenttypes.models import ContentType
from django.test import TestCase
from django.test.utils import override_settings
from django.urls import reverse
from rest_framework.test import APIClient
from... |
"""
Telnet OOB (Out of band communication)
This implements the following telnet oob protocols:
MSDP (Mud Server Data Protocol)
GMCP (Generic Mud Communication Protocol)
This implements the MSDP protocol as per
http://tintin.sourceforge.net/msdp/ and the GMCP protocol as per
http://www.ironrealms.com/rapture/manual/file... |
from __future__ import print_function, unicode_literals
import json
import os
import sys
from textwrap import dedent
def get_hashed_filenames(static_path):
json_file = '{}/staticfiles.json'.format(static_path)
with open(json_file) as jsonf:
staticfiles = json.load(jsonf)
return staticfiles['paths'].... |
from __future__ import absolute_import, division, print_function, unicode_literals
import pytest ; pytest
from bokeh.core.enums import ButtonType
from bokeh.layouts import column
from bokeh.models import Circle, ColumnDataSource, CustomAction, CustomJS, Plot, Range1d, Toggle
from bokeh._testing.util.selenium import REC... |
__revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__"
"""
Test setting the $CVSCOM variable.
"""
import os.path
import TestSCons
_python_ = TestSCons._python_
test = TestSCons.TestSCons(match = TestSCons.match_re_dotall)
test.write('SConscript', """
Environment(tools = ['CVS']).CVS('')
""")
msg_cvs = """The CVS... |
class HandyList(list):
@property
def first(self):
if self:
return self[0]
else:
return None
def __getitem__(self, item):
obj = list.__getitem__(self, item)
if type(obj) == dict:
return HandyDict(obj)
return obj
class HandyDict(dict)... |
BANK_MOVIE_CLEAR = 1
BANK_MOVIE_GUI = 2
BANK_MOVIE_DEPOSIT = 3
BANK_MOVIE_WITHDRAW = 4
BANK_MOVIE_NO_OP = 5
BANK_MOVIE_NOT_OWNER = 6
BANK_MOVIE_NO_OWNER = 7 |
import re
from .dialect import Dialect
from .errors import NoSuchLanguageException
class TokenMatcher:
LANGUAGE_RE = re.compile(r"^\s*#\s*language\s*:\s*([a-zA-Z\-_]+)\s*$")
def __init__(self, dialect_name='en'):
self._change_dialect(dialect_name)
self._indent_to_remove = 0
self._active_... |
import random, time
import string, sys
def main():
# Modulo Gerador de Senha.
def PasswordGenerator():
# Titulo
print("\nGerador de Senhas\n")
# Titulo
# INICIO FUNÇÕES DAS OPÇOES DO MENU
#
# Gerador para a senha "Fraca".
def PassFraca(x):
while(True):
# LEMBRETE - TROCAR OS IF'S "-v" e "exit" E ... |
from django.conf import settings
from django.contrib.auth import get_user_model
from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt
import logging
import site_config
from shared import mail
from . import tasks
logger = logging.getLogger(__name__)
User = get_user_model()
def send_fo... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.