code stringlengths 1 199k |
|---|
from __future__ import unicode_literals
from django.db import migrations
from corehq.doctypemigrations.djangomigrations import assert_initial_complete
from corehq.doctypemigrations.migrator_instances import apps_migration
from corehq.sql_db.operations import HqRunPython
class Migration(migrations.Migration):
depend... |
import mock
from jsl import fields
from jsl._compat import iteritems, with_metaclass
from jsl.document import Document, DocumentMeta, Options
class OptionsStub(Options):
"""An options container that allows storing extra options."""
def __init__(self, a=None, b=None, c=None, d=None, **kwargs):
super(Opti... |
"""peutils, Portable Executable utilities module
Copyright (c) 2005-2012 Ero Carrera <ero.carrera@gmail.com>
All rights reserved.
For detailed copyright information see the file COPYING in
the root of the distribution archive.
"""
import os
import re
import string
import urllib.request, urllib.parse, urllib.error
impor... |
import sys
if len(sys.argv) <= 1:
print "Usage: add_it_up #"
else:
userData = int(sys.argv[1])
zcount = 0
znumbers = []
while userData > 0:
print "userData is ", userData
znumbers[zcount] = userData
userData -= 1
zcount += 1
print "Numbers: ", znumbers
print "... |
import sys
import threading
import traceback
from ginga.gtkw import gtksel
import gtk
from ginga.misc import Bunch, Future
class PluginManagerError(Exception):
pass
class PluginManager(object):
def __init__(self, logger, fitsview, ds, mm):
super(PluginManager, self).__init__()
self.logger = logg... |
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [("eventstore", "0023_cdu_address_update_msisdn")]
operations = [
migrations.AddField(
model_name="cduaddressupdate",
name="district",
field=models.CharField(default="Empty"... |
"""
This module contains the main logic for start, query, stop graphlab server client connection.
"""
'''
Copyright (C) 2015 Dato, Inc.
All rights reserved.
This software may be modified and distributed under the terms
of the BSD license. See the LICENSE file for details.
'''
from ..cython.cy_unity import UnityGlobalPr... |
"""
(c) RIKEN 2015. All rights reserved.
Author: Keitaro Yamashita
This software is released under the new BSD License; see LICENSE.
"""
from yamtbx.dataproc.myspotfinder.command_line import spot_finder_gui
if __name__ == "__main__":
import sys
spot_finder_gui.run_from_args(sys.argv[1:]) |
import cgi
import cherrypy
from lib.model.user import User
from lib.model.mention import Mention
__all__ = ['Twiseless']
class Twiseless(object):
def __init__(self):
self.login = Login()
@cherrypy.expose
@cherrypy.tools.user()
@cherrypy.tools.render(template="index.mako")
def index(self):
... |
import json
import os
import re
import shlex
import sys
from vee import log
from vee.cli import style, style_note
from vee.homebrew import Homebrew
from vee.package import Package
from vee.pipeline.base import PipelineStep
from vee.subproc import call
from vee.utils import makedirs, cached_property
class HomebrewManage... |
import sys
import os
import time
from datetime import datetime, timedelta
import SocketServer
import ipfix.v9pdu
import ipfix.v5pdu
import ipfix.ie
import ipfix.template
from threading import Thread, Lock
import Queue
from correlator import netflowQueue
import collector_config
ipfix.ie.use_iana_default()
ipfix.ie.use_5... |
from distutils.version import LooseVersion
from itertools import chain
import numpy as np
from numpy import nan
import pytest
from pandas._libs.algos import Infinity, NegInfinity
from pandas._libs.tslib import iNaT
import pandas.compat as compat
from pandas.compat import product
import pandas.util._test_decorators as t... |
def get_speed(astring):
return -42 |
import logging
import os
import pickle
from typing import Optional
import numpy as np
import pandas as pd
import torch
from anndata import read
from collections.abc import Iterable as IterableClass
from scvi._compat import Literal
from scvi._utils import track
from scvi.core.utils import DifferentialComputation
logger ... |
"""Auto-generated file, do not edit by hand. 881 metadata"""
from ..phonemetadata import NumberFormat, PhoneNumberDesc, PhoneMetadata
PHONE_METADATA_881 = PhoneMetadata(id='001', country_code=881, international_prefix=None,
general_desc=PhoneNumberDesc(national_number_pattern='[67]\\d{8}', possible_number_pattern='... |
import unittest
import os
from maskgen import plugins, image_wrap
import numpy
import tempfile
class MedianBlurTestCase(unittest.TestCase):
filesToKill = []
def setUp(self):
plugins.loadPlugins()
def test_something(self):
img = numpy.random.randint(0, 255, (500, 500, 3), dtype='uint8')
... |
import functools
from django.core.exceptions import PermissionDenied
from amo.decorators import login_required
from mkt.access.acl import action_allowed
def admin_required(reviewers=False):
"""
Admin, or someone with AdminTools:View, required.
If reviewers=True ReviewerAdminTools:View is allowed also... |
__author__ = 'Bohdan Mushkevych'
from flow.core.abstract_cluster import AbstractCluster
from flow.core.execution_context import ContextDriven, get_action_logger, valid_context
class AbstractAction(ContextDriven):
""" abstraction for action
API sequence:
1. *set_context*
2. *do*
3. *c... |
import json
from collections import namedtuple
from werkzeug.wrappers import Request, Response
from werkzeug.routing import Map, Rule
from werkzeug.exceptions import HTTPException, NotFound, abort
from jwt_token import JWTToken
from authorize import Auth
Scope = namedtuple('Scope', ['type', 'image', 'actions'])
class D... |
"""
WSGI config for django_test 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.6/howto/deployment/wsgi/
"""
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "example_app.settings")
from django.co... |
from django.conf import settings
from django.conf import LazySettings
import tempfile
import os
class Settings(LazySettings):
# Dict of preset names that have width and height values
IMAGEFIT_PRESETS = getattr(settings, 'IMAGEFIT_PRESETS', {
'thumbnail': {'width': 80, 'height': 80, 'crop': True},
... |
def extractDysrySummaries(item):
"""
Dysry Summaries
"""
vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
if not (chp or vol or frag) or 'preview' in item['title'].lower():
return None
if 'Summary' in item['tags']:
return None
return False |
"""
Copyright 2015, Andrew Lin.
All rights reserved.
Licensed under the BSD 3-clause License. See LICENSE.txt or
<http://opensource.org/licenses/BSD-3-Clause>.
"""
class DeckCreator:
def __init__(self):
pass |
import math
def rot_point(point, pivot, angle):
rads = math.radians(angle)
s = math.sin(rads)
c = math.cos(rads)
x = point[0] - pivot[0]
y = point[1] - pivot[1]
nx = x * c - y * s
ny = x * s + y * c
return (nx + pivot[0], ny + pivot[1])
def scale(x, a, b, l=0., h=1.):
return ((h - l)... |
import datetime as dt
import logging
from flask import Blueprint, flash, redirect, render_template, request, url_for
from flask import Markup
from flask_login import fresh_login_required, login_user, logout_user, current_user
from authmgr.utils import flash_errors
from authmgr.extensions import db
from authmgr.extensio... |
"""
django-helpdesk - A Django powered ticket tracker for small enterprise.
(c) Copyright 2008 Jutda. All Rights Reserved. See LICENSE for details.
forms.py - Definitions of newforms-based forms for creating and maintaining
tickets.
"""
from django import forms
from django.forms import extras
from django.con... |
"""Command for deleting instances."""
from googlecloudsdk.api_lib.compute import base_classes
from googlecloudsdk.api_lib.compute import request_helper
from googlecloudsdk.api_lib.compute import utils
from googlecloudsdk.calliope import exceptions
from googlecloudsdk.core.console import console_io
AUTO_DELETE_OVERRIDE_... |
from __future__ import unicode_literals
import collections
import copy
import datetime
import decimal
import math
import warnings
from base64 import b64decode, b64encode
from itertools import tee
from django.apps import apps
from django.db import connection
from django.db.models.lookups import default_lookups, Register... |
'''Generate models for affinity predictions'''
modelstart = '''layer {
name: "data"
type: "MolGridData"
top: "data"
top: "label"
top: "affinity"
include {
phase: TEST
}
molgrid_data_param {
source: "TESTFILE"
batch_size: 10
dimension: 23.5
resolution: 0.5
shuffle: false
balan... |
from django.test import TestCase
from django.test.client import Client
try:
from django.urls import reverse
except ImportError:
from django.core.urlresolvers import reverse
class RoutingTest(TestCase):
def setUp(self):
self.client = Client()
self.post_dict = {'email': 'nobody@example.com',
... |
import sys
from osgpypp import osgAnimation
from osgpypp import osgDB
from osgpypp import osgGA
from osgpypp import osgViewer
class NoseBegin (osgAnimation.Action.Callback) :
virtual void operator()(osgAnimation.Action* action, osgAnimation.ActionVisitor* nv)
print "sacrebleu, it scratches my nose, let me scrat... |
from __future__ import absolute_import
from sentry.buffer import Buffer
class InProcessBuffer(Buffer):
"""
In-process buffer which computes changes in real-time.
**Note**: This does not actually buffer anything, and should only be used
in development and testing environments.
"""
def i... |
"""
celery.worker.autoreload
~~~~~~~~~~~~~~~~~~~~~~~~
This module implements automatic module reloading
"""
from __future__ import absolute_import
import hashlib
import os
import select
import sys
import time
from collections import defaultdict
from threading import Event
from kombu.utils import eventio
fro... |
from __future__ import print_function, division
__all__ = ['ReferenceFrame', 'Vector', 'Dyadic', 'dynamicsymbols',
'MechanicsStrPrinter', 'MechanicsPrettyPrinter',
'MechanicsLatexPrinter', 'CoordinateSym']
from sympy import (
Symbol, sin, cos, eye, trigsimp, diff, sqrt, sympify,
expand, ze... |
import os
import glob
import numpy as np
import pytest
from matmodlab2 import *
from testing_utils import *
def test_mps_assign_material():
"""Test correctness of assigning a material"""
jobid = 'Job-1'
mps = MaterialPointSimulator(jobid)
try:
mps.run_step('E', 1)
except RuntimeError:
... |
from twisted.plugin import IPlugin
from twisted.words.protocols import irc
from txircd.module_interface import Command, ICommand, IModuleData, ModuleData
from zope.interface import implementer
from typing import Any, Dict, List, Optional, Tuple
irc.ERR_SERVICES = "955" # Custom numeric; 955 <TYPE> <SUBTYPE> <ERROR>
@im... |
"""
WSGI config for data_test 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.6/howto/deployment/wsgi/
"""
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "data_test.settings")
from django.core.w... |
"""
Test the design_matrix utilities.
Note that the tests just look whether the data produced has correct dimension,
not whether it is exact.
"""
import numpy as np
import os
import pandas as pd
from nistats.experimental_paradigm import paradigm_from_csv
from nose.tools import assert_true
def basic_paradigm():
cond... |
from optparse import OptionParser
import os
import sqlite3 as sqlite
from misopy.sashimi_plot.plot_utils.plot_gene import readsToWiggle_pysam
import pysam
import json
import numpy as np
import scipy
import math
from scipy.ndimage import zoom
__author__ = 'Hendrik Strobelt'
vials_db_name = 'all_miso_summaries.sqlite'
vi... |
import os, sys; sys.path.insert(0, os.path.join("..",".."))
from nodebox.graphics import *
img = Image("creature.png")
shadow = colorize(img, color=(0,0,0,1))
shadow = blur(shadow, amount=3, kernel=5)
def draw(canvas):
canvas.clear()
# Some simple mouse interaction to make it more interesting.
# Moving the ... |
"""
Copyright (c) 2014 Francisco Suarez-Ruiz. All rights reserved.
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 2 of the License, or
(at your option) any later v... |
import time
import sys
import srddl.data as sd
from srddl.filetypes.elf import ELF
COUNT = 1
if 1 < len(sys.argv) and sys.argv[1] == 'benchmark':
COUNT = 10
begin, d, e = time.perf_counter(), None, None
for _ in range(COUNT):
try:
filename = sys.argv[1]
except IndexError:
filename = '/bin/ls... |
from flask_wtf import Form
from wtforms import TextField, PasswordField
from wtforms.validators import DataRequired
from FlaskStarter.user.models import User
class LoginForm(Form):
username = TextField('Username', validators=[DataRequired()])
password = PasswordField('Password', validators=[DataRequired()])
... |
def gather_file_paths(base_directory, verbose=False):
# this will go into core tools eventually
# ideas: return number of paths, optionally instead
# or write out, optionally, a text file with all paths, for easy
# searching
# test cases:
# - proper data directory
# - empty... |
'''
Local settings
- Run in Debug mode
- Use console backend for emails
- Add Django Debug Toolbar
- Add django-extensions as app
'''
from .common import * # noqa
DEBUG = env.bool('DJANGO_DEBUG', default=True)
TEMPLATES[0]['OPTIONS']['debug'] = DEBUG
SECRET_KEY = env("DJANGO_SECRET_KEY", default='CHANGEME!!!-@36a!44gf... |
from __future__ import print_function
import argparse
import os
import codecs
import re
import colorsys
import json
parser = argparse.ArgumentParser(
description='Generate uORB pub/sub dependency graph from source code')
parser.add_argument('-s', '--src-path', action='append',
help='Source path(... |
import urllib2, urllib
from django.utils import simplejson
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render_to_response
import defaults
from helpers import render
site = defaults.SITE
def search (request):
if not request.GET.has_key('q'):
payload = {}
else:
... |
from django import forms
from django.contrib.auth import get_user_model, get_permission_codename
from django.contrib.auth.models import Permission
from django.contrib.contenttypes.models import ContentType
from django.contrib.sites.models import Site
from django.core.exceptions import ValidationError, ObjectDoesNotExis... |
import json
DEPS = [
'env',
'flavor',
'recipe_engine/context',
'recipe_engine/file',
'recipe_engine/path',
'recipe_engine/platform',
'recipe_engine/properties',
'recipe_engine/python',
'recipe_engine/raw_io',
'recipe_engine/step',
'run',
'vars',
]
def test_steps(api):
"""Run the DM test."""
... |
__version__ = '0.1.45' |
from django.utils.translation import activate
from applications.questions import get_organiser_menu
def test_organiser_menu_entries_en():
activate('en') # default language, but to be explicit
menu = get_organiser_menu('london')
assert menu[0]['url'] == '/en/london/applications/'
assert menu[1]['url'] =... |
from nagare import presentation, ajax
from nagare.i18n import _
class Overlay(object):
"""Overlay component
"""
def __init__(self, text_factory, content_factory, title=None, dynamic=True, cls=None, centered=False):
"""Initialization
In:
- ``text_factory`` -- a callable generating... |
"""Add plural translations.
Revision ID: deb5c1dad94a
Revises: 71f4f6391672
Create Date: 2017-05-12 12:07:01.259819
"""
revision = 'deb5c1dad94a'
down_revision = '71f4f6391672'
branch_labels = None
depends_on = None
from alembic import op
import sqlalchemy as sa
def upgrade():
op.create_table('plural_translated_str... |
import stem, stem.connection, stem.socket
from stem.control import EventType, Controller
import errno # https://stackoverflow.com/questions/14425401/
from socket import error as socket_error
import socket, functools, re, sys
from threading import Thread
import time, datetime
def main():
print 'Opening log file, furth... |
import re
import sqlite3
import time
def do_karma(bot, user, channel, karma):
if karma[1] == '++':
k = 1
else:
k = -1
conn = sqlite3.connect('karma.db')
c = conn.cursor()
t = (karma[0].lower(),)
# Karma spam check
# SILENTLY ignore if user has modified this karma in the last ... |
from django.db.transaction import non_atomic_requests
from django.utils.translation import ugettext
import caching.base as caching
from olympia import amo
from olympia.amo.templatetags.jinja_helpers import url, absolutify
from olympia.amo.feeds import NonAtomicFeed
from olympia.amo.utils import render
from .models impo... |
"""
This file is part of Urban Mediator software.
Copyright (c) 2008 University of Art and Design Helsinki
See the file LICENSE.txt for copying permission.
Handling mediafiles (stored in the FS)
"""
import md5, mimetypes, time, rfc822, tempfile, StringIO, os, datetime
import web
import PIL.Image as Imag... |
'''
Build the pipeline workflow by plumbing the stages together.
'''
from ruffus import Pipeline, suffix, formatter, add_inputs, output_from
from stages import Stages
from utils import safe_make_dir
def make_pipeline(state):
'''Build the pipeline by constructing stages and connecting them together'''
# Build an... |
from telemetry.internal.actions import seek
from telemetry.testing import tab_test_case
import py_utils
AUDIO_1_SEEKED_CHECK = 'window.__hasEventCompleted("#audio_1", "seeked");'
VIDEO_1_SEEKED_CHECK = 'window.__hasEventCompleted("#video_1", "seeked");'
class SeekActionTest(tab_test_case.TabTestCase):
def setUp(self)... |
def extractWalkTheJiangHu(item):
"""
"""
vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
if not (chp or vol) or 'preview' in item['title'].lower():
return None
if 'TTNH Chapter' in item['title']:
return buildReleaseMessageWithType(item, 'Transcending the Nine Heavens', vol, chp, frag=... |
__version__ = '0.3.0.rc1'
APPNAME = 'klustaviewa'
ABOUT = """KlustaViewa is a software for semi-automatic spike sorting with high-channel count silicon probes. It is meant to be used after the automatic clustering stage. This interface automatically guides the user through the clustered data and lets him or her refine ... |
"""Module dedicated to testing the InstrJob.
"""
import pytest
from i3py.core.job import InstrJob
def test_normal_wait():
"""Test that we can wait for a job terminating within the expected time.
"""
def cond():
return True
job = InstrJob(cond, 0)
assert job.wait_for_completion()
def test_wai... |
import hashlib
from collections import namedtuple
from datetime import datetime
from django.contrib.postgres.fields import ArrayField
from django.db import IntegrityError, connection, models, transaction
from django.utils.encoding import force_str
from django.utils.translation import ugettext_lazy, ugettext_noop, ugett... |
import unittest
from functools import partial
from mock import patch
from pathlib import Path
from PyQt5.QtCore import QPointF, QRect
from PyQt5.QtWidgets import QMessageBox
from inselect.gui.roles import MetadataRole, RectRole
from inselect.gui.sort_document_items import SortDocumentItems
from .gui_test import GUITest... |
"""unit tests"""
import os, unittest
os.environ['CLICACHE_DIR'] = os.path.abspath('.clicache')
import clicache
from clicache import cli
import settings
class CLITestCase(unittest.TestCase):
"""
test direct suprocess handling
"""
funky_string = r"""foo'bar "more" \' \" \n zzz"""
funky_string_quoted = r"""'foo'\''ba... |
def panic(exitcode, fmt, *args):
sys.stderr.write('%s: ' % sys.argv[0])
sys.stderr.write(fmt % args)
sys.stderr.write('\n')
sys.exit(exitcode) |
import sys
import email.iterators
email.iterators._structure(email.message_from_file(sys.stdin)) |
import os, sys
sys.path.insert(0, os.path.abspath('..'))
import unittest
import wirexfers
from wirexfers.providers.ipizza import EELHVProvider, EESwedBankProvider
class IPizzaTestCase(unittest.TestCase):
"""Test cases for IPizza protocol providers."""
# We can currently only test mac generation (no signing/veri... |
class Solution(object):
def cherryPickup(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
# dp holds the max # of cherries two k-length paths can pickup.
# The two k-length paths arrive at (i, k - i) and (j, k - j),
# respectively.
n = len(... |
from java.io import FileWriter,BufferedWriter
import getopt
import sys
import os
import time
createDomainModule = '1.0.6'
log.debug('Loading module [createDomain.py] version [' + createDomainModule + ']')
try:
serverModule
except NameError:
execfile('wlst/server.py')
def __createDomain(configProperties):
webLogicHom... |
from swgpy.object import *
def create(kernel):
result = Tangible()
result.template = "object/tangible/ship/components/droid_interface/shared_ddi_seinar_interface_mk2.iff"
result.attribute_template_id = 8
result.stfName("space/space_item","ddi_seinar_interface_mk2")
#### BEGIN MODIFICATIONS ####
#### END MODIFICA... |
from swgpy.object import *
def create(kernel):
result = Tangible()
result.template = "object/tangible/hair/human/base/shared_hair_human_male_base.iff"
result.attribute_template_id = -1
result.stfName("hair_name","hair")
#### BEGIN MODIFICATIONS ####
#### END MODIFICATIONS ####
return result |
import sys
import os
import cv2 as opencv
class ImageFileWriter:
def __init__(self):
pass
def write_images(self, *args):
image_directory = '/root/ghisallo_venv/src/opencv_direction_indicator_detection/oop/test_images/'
if len(args) % 2 != 0:
print('argument error: got not enough names for files to write.')
... |
from swgpy.object import *
def create(kernel):
result = Intangible()
result.template = "object/draft_schematic/clothing/shared_clothing_boots_casual_04.iff"
result.attribute_template_id = -1
result.stfName("string_id_table","")
#### BEGIN MODIFICATIONS ####
#### END MODIFICATIONS ####
return result |
import os
from django import template
from django.conf import settings
from pimpmytheme.utils import get_lookup_class
from django.utils.safestring import mark_safe
from django.contrib.staticfiles import finders
from django.templatetags.static import static
register = template.Library()
try:
project_name = settings.... |
"""
Export neuroimaging results created with feat in AFNI following NIDM-Results
specification.
@author: Rick Reynolds/Camille Maumet
@copyright:
"""
import re
import os
import glob
import numpy as np
from exporter.exporter import NIDMExporter
from exporter.objects.constants import *
from exporter.objects.modelfitting ... |
from __future__ import absolute_import, print_function, division, unicode_literals
import os
import logging
import io
import unicodecsv as csv
import json
import idigbio
import re
import datetime
try:
from pathlib import Path
except ImportError:
from pathlib2 import Path
try:
from urllib.parse import urlpar... |
import cgi # NEW
def main(): # NEW except for the call to processInput
form = cgi.FieldStorage() # standard cgi script lines to here!
# use format of next two lines with YOUR names and default data
numStr1 = form.getfirst("x", "0") # get the form value associated with form
... |
from django.conf.urls import patterns, url
from . import views
from stronghold.decorators import public
urlpatterns = patterns('',
url(r'^$',
public(views.HomeView.as_view()),
name="home"),
) |
from config.template_middleware import TemplateResponse
from gaecookie.decorator import no_csrf
from gaepermission.decorator import login_not_required
from tekton import router
__author__ = 'Samara Cardoso'
@login_not_required
@no_csrf
def index():
contexto = {'save_path': router.to_path(salvar)}
return Templat... |
from django.conf.urls import patterns, include, url
urlpatterns = patterns('apps.basic_pages.views',
#url(r'^home/$', 'view_homepage', name="view_homepage"),
url(r'^support/$', 'view_support_page', name="view_support_page"),
url(r'^best-practices/$', 'view_best_practices_page', name="view_best_practices_pag... |
from __future__ import unicode_literals
from django.db import migrations
def forwards_func(apps, schema_editor):
EmailTemplate = apps.get_model("konfera", "EmailTemplate")
db_alias = schema_editor.connection.alias
text = """Dear {first_name} {last_name},\n\n
thank you for submitting proposal f... |
'''
Behaviors
=========
.. versionadded:: 1.8.0
Behavior mixin classes
----------------------
This module implements behaviors that can be
`mixed in <https://en.wikipedia.org/wiki/Mixin>`_
with existing base widgets. The idea behind these classes is to encapsulate
properties and events associated with certain types of ... |
"""
ZetCode PyQt4 tutorial
This example shows a QtGui.QProgressBar widget.
author: Jan Bodnar
website: zetcode.com
last edited: September 2011
"""
import sys
from PyQt4 import QtGui, QtCore
class Example(QtGui.QWidget):
def __init__(self):
super(Example, self).__init__()
self.initUI()
def initUI... |
from _pytest.pytester import Pytester
def test_no_items_should_not_show_output(pytester: Pytester) -> None:
result = pytester.runpytest("--fixtures-per-test")
result.stdout.no_fnmatch_line("*fixtures used by*")
assert result.ret == 0
def test_fixtures_in_module(pytester: Pytester) -> None:
p = pytester.... |
from swgpy.object import *
def create(kernel):
result = Intangible()
result.template = "object/draft_schematic/vehicle/component/shared_fuel_cell_c.iff"
result.attribute_template_id = -1
result.stfName("string_id_table","")
#### BEGIN MODIFICATIONS ####
#### END MODIFICATIONS ####
return result |
import unittest
import time
from twilio.jwt.taskrouter.capabilities import (
WorkerCapabilityToken,
TaskQueueCapabilityToken,
WorkspaceCapabilityToken,
)
class TaskQueueCapabilityTokenTest(unittest.TestCase):
def setUp(self):
self.account_sid = "AC123"
self.auth_token = "foobar"
... |
class Solution:
# @return a string
def convert(self, s, nRows):
if nRows == 1:
return s
cycle = nRows * 2 - 2
rows = ['' for _ in range(nRows)]
for i, c in enumerate(s):
m = i % cycle
if m < nRows - 1:
rows[m] += c
e... |
import os
import datetime
import numbers
import pytest
from redis.client import StrictRedis, ConnectionError
from sider.session import Session
from sider.types import Integer
def get_client(cls=StrictRedis):
host = os.environ.get('SIDERTEST_HOST', 'localhost')
port = int(os.environ.get('SIDERTEST_PORT', 6379))
... |
import demistomock as demisto
from CommonServerPython import *
from CommonServerUserPython import *
import xml.etree.ElementTree as ET # type: ignore
import requests
import re
requests.packages.urllib3.disable_warnings()
"""COMMAND FUNCTIONS"""
def alexa_fallback_command(domain, use_ssl, proxies):
headers = {
... |
""" Unit tests for Company views (see views.py) """
from __future__ import unicode_literals
from django.test import TestCase
from django.urls import reverse
from django.contrib.auth import get_user_model
from django.contrib.auth.models import Group
class CompanyViewTestBase(TestCase):
fixtures = [
'category... |
from .. import mixins
class Offering(mixins.DataciteMixin):
def get_datacite_title(self):
return 'test offering'
def get_datacite_creators_name(self):
return 'Test company'
def get_datacite_description(self):
return 'Description of test offering'
def get_datacite_publication_year... |
import math
import random
import string
import urllib2
from bs4 import BeautifulSoup
random.seed(0)
def rand(a, b):
return (b-a)*random.random() + a
def makeMatrix(I, J, fill=0.0):
m = []
for i in range(I):
m.append([fill]*J)
return m
def sigmoid(x):
return math.tanh(x)
def dsigmoid(y):
... |
from swgpy.object import *
def create(kernel):
result = Static()
result.template = "object/static/particle/shared_pt_smoke_small.iff"
result.attribute_template_id = -1
result.stfName("obj_n","unknown_object")
#### BEGIN MODIFICATIONS ####
#### END MODIFICATIONS ####
return result |
from __future__ import absolute_import, division, print_function
import logging
from tqdm.auto import tqdm
from copy import deepcopy
import concurrent.futures
import numpy as np
import pandas as pd
logger = logging.getLogger('prophet')
def generate_cutoffs(df, horizon, initial, period):
"""Generate cutoff dates
... |
from .proc import (
ProcError,
command,
command_ex,
shell_script,
start_process,
)
__all__ = [
'ProcError',
'command',
'command_ex',
'shell_script',
'start_process',
] |
from __future__ import print_function, division
import matplotlib
matplotlib.use('Agg') # Must be before importing matplotlib.pyplot or pylab!
from neuralnilm import Net, RealApplianceSource, BLSTMLayer, DimshuffleLayer
from lasagne.nonlinearities import sigmoid, rectify
from lasagne.objectives import crossentropy, mse... |
from __future__ import print_function
class TestEnv:
class_att = 1
def __init__(self):
self.inst_att = 2
def test(self):
loc_var = 3
print("locals", locals())
print("globals", globals())
print("my self", self)
print("my class", self.__class__)
t = TestEnv()
t.... |
cal=[[0,'S0'],[12,'S1'],[25,'S2'],[41,'S3'],[51,'S4'],[65,'S5'],[80,'S6'],
[95,'S7'],[112,'S8'],[133,'S9'],[144,'S9+5'],[151,'S9+10'],
[163,'S9+15'],[172,'S9+20'],[180,'S9+25'],[192,'S9+30'],
[200,'S9+35'],[213,'S9+40'],[231,'S9+45'],[255,'S9+60'],[256,'junk']]
SMtoSP=[]
debug = False
def SMinit():
calP... |
"""
Steps and objects related to lintian
"""
from buildbot import config
from buildbot.process import buildstep
from buildbot.status.results import FAILURE
from buildbot.status.results import SUCCESS
from buildbot.status.results import WARNINGS
from buildbot.steps.shell import ShellCommand
class MaxQObserver(buildstep.... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.