code stringlengths 1 199k |
|---|
from rest_framework import status
from rest_framework.test import APITestCase, APIClient
from django.core.urlresolvers import reverse
from cherrymusic.apps.core.models import User, Track
from cherrymusic.apps.api.v1.serializers import TrackSerializer
from cherrymusic.apps.api.v1.tests.views import UNAUTHENTICATED_RESP... |
"""Read and write image data from and to TIFF files.
Image and metadata can be read from TIFF, BigTIFF, OME-TIFF, STK, LSM, NIH,
SGI, ImageJ, MicroManager, FluoView, SEQ and GEL files.
Only a subset of the TIFF specification is supported, mainly uncompressed
and losslessly compressed 2**(0 to 6) bit integer, 16, 32 and... |
import socketserver, os
from configparser import ConfigParser
"""
Byte
[1] = Action 255 items
"""
class BOBServer(socketserver.BaseRequestHandler):
"""
The request handler class for our server.
It is instantiated once per connection to the server, and must
override the handle() method to implement commu... |
"""
test-gvar.py
"""
import os
import unittest
import collections
import math
import pickle
import numpy as np
import random
import gvar as gv
from gvar import *
try:
import vegas
have_vegas = True
except:
have_vegas = False
FAST = False
class ArrayTests(object):
def __init__(self):
pass
def... |
import pytest
from autonomie.tests.tools import Dummy
def test_default_disable():
from autonomie.forms.user.user import deferred_company_disable_default
companies = [Dummy(employees=range(2))]
user = Dummy(companies=companies)
req = Dummy(context=user)
assert not deferred_company_disable_default("",... |
import matplotlib.pyplot as plt
from h5py import File
from numpy import array
def launch_plots(): # TODO set activation of different plots
plot3d = plt.figure('Plot 3D')
xy_plane = plt.figure('XY')
xz_plane = plt.figure('XZ')
yz_plane = plt.figure('YZ')
ax_plot3d = plot3d.add_subplot(111, projectio... |
import systemtesting
from mantid.simpleapi import *
from reduction_workflow.instruments.sans.sns_command_interface import *
from reduction_workflow.instruments.sans.hfir_command_interface import *
FILE_LOCATION = "/SNS/EQSANS/IPTS-5636/data/"
class EQSANSFlatTest(systemtesting.MantidSystemTest):
def requiredFiles(s... |
import time
from datetime import datetime
from pytz import timezone
from dateutil.relativedelta import relativedelta
import openerp
from openerp.report.interface import report_rml
from openerp.tools import to_xml
from openerp.report import report_sxw
from datetime import datetime
from openerp.tools.translate import _
f... |
"""
Factories for AMQ clients, Thrift clients and SMAC Clients and servers.
@author: Jonathan Stoppani <jonathan.stoppani@edu.hefr.ch>
"""
import weakref
from twisted.internet.protocol import ReconnectingClientFactory
from twisted.internet import defer, error
from txamqp.protocol import AMQClient
from txamqp.contrib.th... |
import re
class Segmentation:
def __init__(self, lab_file=None):
try:
self.segments = self.parse(lab_file)
except TypeError:
self.segments = []
def parse(self, lab_file):
header = True
segments = []
start = 0
for line in lab_file:
... |
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('jordbruksmark', '0002_auto_20161217_2140'),
]
operations = [
migrations.AlterModelOptions(
name='wochen_menge',
options={'verbose_name': ... |
import PyTango
import sys
import numpy
import struct
import pickle
if sys.version_info > (3,):
long = int
# unicode = str
else:
bytes = str
class TestServer(PyTango.Device_4Impl):
# -------- Add you global variables here --------------------------
# --------------------------------------------------... |
if __name__ == '__main__':
import debug
debug.initenv()
import features
if features.WINE:
from sakurakit.skdebug import dwarn
MAC_THEME = {
'ActiveBorder' : "240 240 240",
'ActiveTitle' : "240 240 240",
'AppWorkSpace' : "198 198 191",
'Background' : "0 0 0",
'ButtonAlternativeFace' : "216 21... |
__all__ = ["core"] |
from __future__ import print_function
import samba.getopt as options
import ldb
import logging
from . import common
import json
from samba.auth import system_session
from samba.netcmd import (
Command,
CommandError,
Option,
SuperCommand,
)
from samba.samdb import SamDB
from samba import drs_utils, nttim... |
from setuptools import setup
version = 'y.dev0'
long_description = '\n\n'.join([
open('README.rst').read(),
open('TODO.rst').read(),
open('CREDITS.rst').read(),
open('CHANGES.rst').read(),
])
install_requires = [
'pkginfo',
'setuptools',
'nens',
],
tests_require = [
]
setup(name=... |
import abjad
def test_LilyPondParser__functions__transpose_01():
pitches = ["e'", "gs'", "b'", "e''"]
maker = abjad.NoteMaker()
target = abjad.Staff(maker(pitches, (1, 4)))
key_signature = abjad.KeySignature("e", "major")
abjad.attach(key_signature, target[0])
assert abjad.lilypond(target) == ab... |
import numpy as np
import scipy.spatial.distance as dist
from matplotlib.backends.backend_pdf import PdfPages
import matplotlib.pyplot as plt
import matplotlib.lines as mplines
import scipy.cluster.hierarchy as clust
import os
def kabsch(coord, ref,app):
C = np.dot(np.transpose(coord), ref)
V, S, W = np.linalg.svd(C)... |
import VMSYSTEM.libSBTCVM as libSBTCVM
import VMSYSTEM.libbaltcalc as libbaltcalc
import sys
import os
assmoverrun=19683
instcnt=0
txtblk=0
VMSYSROMS=os.path.join("VMSYSTEM", "ROMS")
critcomperr=0
compvers="v2.2.0"
outfile="assmout.trom"
IOmapread={"random": "--0------"}
IOmapwrite={}
scratchmap={}
scratchstart="------... |
from reportlab.graphics import renderPDF
from reportlab.graphics import shapes
from reportlab.graphics.barcode import code39, code128, code93
from reportlab.graphics.barcode import eanbc, qr, usps
from reportlab.graphics.shapes import Drawing
from reportlab.lib import colors
from reportlab.lib.pagesizes import letter
f... |
'''Test on server shutdown when a zone transaction is open.'''
import psutil
from dnstest.libknot import libknot
from dnstest.test import Test
from dnstest.utils import *
t = Test()
knot = t.server("knot")
zone = t.zone("example.com.")
t.link(zone, knot)
ctl = libknot.control.KnotCtl()
t.start()
ctl.connect(os.path.joi... |
from __future__ import unicode_literals
class SickRageException(Exception):
"""
Generic SiCKRAGE Exception - should never be thrown, only sub-classed
"""
class AuthException(SickRageException):
"""
Your authentication information are incorrect
"""
class CantRefreshShowException(SickRageException... |
import re
import asyncio
import threading
from collections import defaultdict
def connector(bot, dispatcher, NICK, CHANNELS, PASSWORD=None):
@bot.on('client_connect')
async def connect(**kwargs):
bot.send('USER', user=NICK, realname=NICK)
if PASSWORD:
bot.send('PASS', password=PASSWO... |
import unittest
from aiourlstatus import app
class TestEmpty(unittest.TestCase):
def test_no_urls(self):
data = ''
urls, len_urls = app.find_sort_urls(data)
self.assertEqual(urls, [])
self.assertEqual(len_urls, 0)
class TestTXT(unittest.TestCase):
def test_parse_text(self):
... |
import json
import operator
from django.core.exceptions import PermissionDenied
from django.db.models import ProtectedError, Q
from django.forms.models import modelform_factory
from django.http import Http404
from django.shortcuts import get_object_or_404
from django.utils.functional import cached_property
from django.... |
from datetime import timedelta
from django import template
import ws.utils.dates as date_utils
import ws.utils.perms as perm_utils
from ws import forms
from ws.utils.itinerary import get_cars
register = template.Library()
@register.inclusion_tag('for_templatetags/show_wimp.html')
def show_wimp(wimp):
return {
... |
import wxversion
wxversion.select('2.8')
import wx
import wx.aui
from id import *
from model import *
from graphic import *
from sql import *
from django import *
import sqlite3
from xml.dom import minidom
class MainFrame(wx.aui.AuiMDIParentFrame):
def __init__(self, app, posx, posy, sizex, sizey):
self.data = {}... |
"""
Key Manager is a Nicknym agent for LEAP client.
"""
import sys
try:
from gnupg.gnupg import GPGUtilities
assert(GPGUtilities) # pyflakes happy
from gnupg import __version__
from distutils.version import LooseVersion as V
assert(V(__version__) >= V('1.2.3'))
except (ImportError, AssertionError):... |
import json
import random
import ssl
import string
import threading
import time
import websocket
import settings
from player import Player
class WebsocketPlayerControl(object):
def __init__(self, player, server=settings.WS_SERVER):
websocket.enableTrace(settings.DEBUG)
rand_chars = string.ascii_uppe... |
"""
IMAP Mailbox.
"""
import re
import os
import io
import cStringIO
import StringIO
import time
from collections import defaultdict
from email.utils import formatdate
from twisted.internet import defer
from twisted.internet import reactor
from twisted.logger import Logger
from twisted.mail import imap4
from zope.inter... |
"""abydos.tests.distance.test_distance__token_distance.
This module contains unit tests for abydos.distance._TokenDistance
"""
import unittest
from collections import Counter
from abydos.distance import (
AverageLinkage,
DamerauLevenshtein,
Jaccard,
JaroWinkler,
SokalMichener,
)
from abydos.stats im... |
import sys
import re
"""Rewrite the doxygen \\file lines to have the full path to the file."""
def fix(filename):
contents = open(filename, "r").read()
contents = re.sub(
"\\\\file .*\\.h",
"\\\\file " + filename[len("build/include/"):],
contents,
1)
contents = re.sub(
... |
import unittest
"""69. Sqrt(x)
https://leetcode.com/problems/sqrtx/description/
Implement `int sqrt(int x)`.
Compute and return the square root of _x_ , where _x_ is guaranteed to be a
non-negative integer.
Since the return type is an integer, the decimal digits are truncated and only
the integer part of the result i... |
from cloudbot import hook
from cloudbot.util import http
api_root = 'http://api.rottentomatoes.com/api/public/v1.0/'
movie_search_url = api_root + 'movies.json'
movie_reviews_url = api_root + 'movies/%s/reviews.json'
@hook.command('rt')
def rottentomatoes(inp, bot=None):
"""rt <title> -- gets ratings for <title> fr... |
"""
translate.client.exceptions
~~~~~~~~~~~~~~~~~~~~~~~~~~~
These are exception classes that are used by translate.client.Client. Most of
these classes are simple wrappers, just to differentiate different types of
errors. They can be constructed from a requests response object, or JSON
,returned from an API call.
"""
i... |
from PyQt4 import QtCore, QtGui
class Ui_Dialog(object):
def setupUi(self, Dialog):
Dialog.setObjectName("Dialog")
Dialog.resize(253, 111)
self.gridLayout = QtGui.QGridLayout(Dialog)
self.gridLayout.setObjectName("gridLayout")
self.label = QtGui.QLabel(Dialog)
self.la... |
from Ponos import init_db
from env_vars import *
import sqlite3
import os
print(DB_PATH)
open(DB_PATH, 'w').close()
init_db() |
a = input("Dies ist ein Addierer!\nGeben Sie a ein: ")
b = input("Geben Sie b ein: ")
a = int(a)
b = int(b)
result = a
i = 0
if b > 0: # wenn b größer Null
while i < b: # dann Schleife positiv durchlaufen
result += 1
i += 1
elif b < 0: # wenn b kleiner Null
while... |
from __future__ import unicode_literals
import json
import frappe
from erpnext.accounts.party import get_party_account_currency
from erpnext.controllers.accounts_controller import get_taxes_and_charges
from erpnext.setup.utils import get_exchange_rate
from erpnext.stock.get_item_details import get_pos_profile
from frap... |
import userHelper
import serverPackets
import exceptions
import glob
import consoleHelper
import bcolors
import locationHelper
import countryHelper
import time
import generalFunctions
import channelJoinEvent
def handle(flaskRequest):
# Data to return
responseTokenString = "ayy"
responseData = bytes()
# The IP for y... |
from yanntricks import *
def KScolorD():
pspict,fig = SinglePicture("KScolorD")
pspict.dilatation(1)
x=var('x')
C=Circle(Point(0,0),1)
N1=C.graph(90,180)
N2=C.graph(270,360)
C.parameters.color="blue"
N1.parameters.color="black"
N2.parameters.color=N1.parameters.color
N1.wave(0.1,... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import base64
import json
import os
import random
import re
import stat
import tempfile
import time
from abc import ABCMeta, abstractmethod
from ansible import constants as C
from ansible.errors import AnsibleError, AnsibleConnectio... |
from __future__ import division
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
import sys
def stats_file_as_matrix(file_name):
with open(file_name, 'r') as f:
return [ map(float,line.strip().split(' ')) for line in f ]
titles = ["Bitrate", "Delay", "Jitter", "Packe... |
from util import A, B, B_reversed, C, D, E, F, G, H, instr, spec, spec_reversed
_mark = set(dir()) ; _mark.add('_mark')
@A
def jmp(address):
'''
1001 010k kkkk 110k
kkkk kkkk kkkk kkkk
'''
def cli():
return 16, 0b1001010011111000
@B
def ldi(register, immediate):
'''
1110 KKKK dddd KKKK
'''
@C
def out(io... |
import sugar_stats_consolidation
from sugar_stats_consolidation.db import *
from sugar_stats_consolidation.rrd_files import *
from sugar_stats_consolidation.consolidation import *
db = DB_Stats('statistics', 'root', 'gustavo')
db.create();
con = Consolidation('/var/lib/sugar-stats/rrd', db)
con.process_rrds() |
'''
testing speedup of code
Created on Sep 17, 2016
@author: jonaswallin
'''
from Mixture.density import mNIG
from Mixture.density.purepython import mNIG as pmNIG
from Mixture import mixOneDims
import numpy as np
import numpy.random as npr
import timeit
npr.seed(10)
def speed_python(pure_python=False, precompute = True... |
import sys
PY3 = False
if sys.version_info[0] >= 3: PY3 = True; unicode = str; unichr = chr; long = int
if PY3:
import urllib.parse as urlparse # Es muy lento en PY2. En PY3 es nativo
else:
import urlparse # Usamos el nativo de PY2 que es ... |
import json
import re
packageJson = '../../../package.json'
with open(packageJson) as data_file:
data = json.load(data_file)
config = '../../pkjs/config.js'
with open(config) as conf_file:
s = conf_file.readline()
keys = []
while (s):
suggestKey = re.search(r"messageKey\"\:(.[^,]*)", s)
... |
import plt, ipp
import os, string
print "Starting try-trace.py: dir() = %s" % dir()
print "- - - - -"
print "NO_COMRESSION = %d" % plt.NO_COMPRESSION
base = "/home/nevil" # Ubuntu
fn = "pypy/1000packets.pcap.gz"
full_fn = base + '/' + fn
print "%s: isfile %s" % (full_fn, os.path.isfile(full_fn))
trace_format = "pc... |
from pyspark import SparkContext, SparkConf, SQLContext, Row, HiveContext
from pyspark.sql.types import *
from datetime import date, datetime, timedelta
import sys, re, os
st = datetime.now()
conf = SparkConf().setAppName('PROC_O_IBK_WSYH_ECACCT').setMaster(sys.argv[2])
sc = SparkContext(conf = conf)
sc.setLogLevel('WA... |
class LexToken:
colno = 0
ttype = ''
tvalue = ''
def __init__(self, tokenstr):
t = tokenstr.split(':')
if len(t) < 2 or len(t) > 3:
raise Exception("invalid token: %s" % t)
self.colno = t[0]
self.ttype = t[1]
if len(t) == 3:
self.tvalue = t[2]
def __repr__(self):
if '' == s... |
from umlfri2.application.commands.base import Command
from umlfri2.application.events.diagram import ConnectionMovedEvent
class MoveConnectionLabelCommand(Command):
def __init__(self, connection_label, delta):
self.__diagram_name = connection_label.connection.diagram.get_display_name()
self.__connec... |
import urllib
import re
try:
import xml.etree.cElementTree as etree
except ImportError:
import elementtree.ElementTree as etree
import sickbeard
import generic
from sickbeard.common import Quality
from sickbeard import logger
from sickbeard import tvcache
from sickbeard import helpers
class EZRSSProvider(generi... |
"""
Unit tests for the HashTask object
By Simon Jones
26/8/2017
"""
import unittest
from test.TestFunctions import *
from source.HashTask import *
from source.Channel import Channel
class HashTaskUnitTests(unittest.TestCase):
"""
Unit tests for the HashTask object
"""
def setUp(self):
self.task1_t_channel = Chann... |
"""
This file demonstrates writing tests using the unittest module.
These will pass when you run "manage.py test".
Replace this with more appropriate tests for your application.
"""
from django.test import TestCase
class SimpleTest(TestCase):
def test_basic_addition(self):
"""Test that 1 + 1 always equals 2... |
__all__ = ['BASIC', 'LOAD', 'SUBMIT', 'STORE_READ', 'STORE_CUD', 'ConfigurationMeta', 'create_configuration', 'expose']
BASIC = 0
LOAD = 1
SUBMIT = 2
STORE_READ = 3
STORE_CUD = 4
class ConfigurationMeta(type):
"""Each class created with this metaclass will have its exposed methods registered
A method can be exp... |
import sys
import argparse
parser = argparse.ArgumentParser(
description='convert a non-standord hostname like xx-xx-[1-3] to a '
'expansion state',
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog="""
Sample:
$ ./converter.py xxx-xxx-\[1-3\]
xxx-xxx-1
xxx-xxx-2
xxx-xxx-3
Tips: You can pass... |
import sys,os,shelve
import re,dfxml,fiwalk
from bc_utils import filename_from_path
from openpyxl.workbook import Workbook
from openpyxl.writer.excel import ExcelWriter
from openpyxl.cell import get_column_letter
def bc_generate_feature_xlsx(PdfReport, data, feature_file):
wb = Workbook()
dest_filename = PdfRep... |
"""AAPP Level-1 processing on NOAA and Metop HRPT Direct Readout data. Listens
for pytroll messages from Nimbus (NOAA/Metop file dispatch) and triggers
processing on direct readout HRPT level 0 files (full swaths - no granules at
the moment)
"""
from ConfigParser import RawConfigParser
import os
import sys
import loggi... |
import time
import config_mqtt
class Asynch_result:
def __init__(self, correlation_id, requests, yield_to):
self.correlation_id = correlation_id
self._requests_need_result = requests
self.yield_to = yield_to
def get(self, timeout = config_mqtt.ASYNCH_RESULT_TIMEOUT):
# time.sleep... |
"""Namegame, where you try to remember a team number starting with the last number of the previous played team"""
import asyncio
import gzip
import pickle
import traceback
from collections import OrderedDict
from functools import wraps
import discord
import tbapi
from discord.ext.commands import has_permissions
from fu... |
DOCUMENTATION = """
---
module: ec2_elb_lb
description:
- Returns information about the load balancer.
- Will be marked changed when called only if state is changed.
short_description: Creates or destroys Amazon ELB.
version_added: "1.5"
author:
- "Jim Dalton (@jsdalton)"
options:
state:
description:
... |
from __future__ import absolute_import
from .base_model_ import Model
from datetime import date, datetime
from typing import List, Dict
from ..util import deserialize_model
class StorageData(Model):
"""
NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.... |
from __future__ import division
'''Test for checking variation of initial prestress force along a
post-tensioned member.
Data and rough calculation are taken from
Example 4.3 of the topic 4 of course "Prestressed Concrete Design
(SAB 4323) by Baderul Hisham Ahmad
ocw.utm.my
Problem statement:
Determine the initial pres... |
"""
This module contains various methods for checking the type of timelines and a
class that creates all kinds of timelines.
"""
import re
from functools import partial
from gettext import gettext as _
from turses.models import Timeline, is_DM
HOME_TIMELINE = 'home'
MENTIONS_TIMELINE = 'mentions'
FAVORITES_TIMELINE = '... |
import re
from tower import ugettext_lazy as _lazy
from tower import ugettext as _
from django import forms
from django.conf import settings
from django.forms.widgets import CheckboxSelectMultiple
from kuma.contentflagging.forms import ContentFlagForm
import kuma.wiki.content
from kuma.core.form_fields import StrippedC... |
import logging
import requests
import sys
from datetime import datetime
from configlib import getConfig, OptionParser
from logging.handlers import SysLogHandler
from pymongo import MongoClient
import os
sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), '../lib'))
from utilities.toUTC import toUTC... |
from __future__ import unicode_literals
from __future__ import division
from __future__ import absolute_import
from collections import Mapping
import mo_dots as dot
from mo_math import SUM
from pyLibrary.queries.containers import Container
from pyLibrary.queries.domains import Domain, ALGEBRAIC, KNOWN
from mo_dots impo... |
import subprocess;
import re;
import json;
import sys;
import os;
import importlib;
silent = os.getenv("SILENT");
if silent:
class Discarder(object):
def write(self, text):
pass # do nothing
# now discard everything coming out of stdout
sys.stdout = Discarder()
if "check_output" not in dir( subprocess... |
import json
import logging
import re
import uuid
from threading import Event
from pyre import Pyre
from ..tools import zmq, green # , spy_call, w_spy_call, spy_object
logger = logging.getLogger(__name__)
class PyreNode(Pyre):
def __init__(self, *args, **kwargs):
# spy_object(self, class_=Pyre, except_=['na... |
"""URL routes for the sample app."""
from django.conf.urls import include, url
from django.views.generic import TemplateView
from rest_framework.routers import DefaultRouter
from .viewsets import ChoiceViewSet, QuestionViewSet, UserViewSet
router = DefaultRouter()
router.register(r'users', UserViewSet)
router.register(... |
import os
from outlawg import Outlawg
from fftool import (
DIR_CONFIGS,
local
)
from ini_handler import IniHandler
Log = Outlawg()
env = IniHandler()
env.load_os_config(DIR_CONFIGS)
def launch_firefox(profile_path, channel, logging, nspr_log_modules=''):
"""relies on the other functions (download, install, ... |
"""
Created on Sun Jan 8 14:45:26 2017
@author: leonidas
"""
import numpy as np
import operator
def classify(inputPoint,dataSet,labels,k):
dataSetSize = dataSet.shape[0]
diffMat = np.tile(inputPoint,(dataSetSize,1))-dataSet
sqDiffMat = pow(diffMat,2)
sqDistances = sqDiffMat.sum(axis=1)
distan... |
import mock
from crashstats.base.tests.testbase import TestCase
from crashstats.api.cleaner import Cleaner, SmartWhitelistMatcher
from crashstats import scrubber
class TestCleaner(TestCase):
def test_simplest_case(self):
whitelist = {'hits': ('foo', 'bar')}
data = {
'hits': [
... |
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from jx_base.expressions import Variable, DateOp, TupleOp, LeavesOp, BinaryOp, OrOp, InequalityOp, extend, Literal, NullOp, TrueOp, FalseOp, DivOp, FloorOp, \
NeOp, NotOp, LengthOp, NumberOp, StringOp, Cou... |
"""TxnReconcile allow txn_id to be null
Revision ID: 08b6358a04bf
Revises: 04e61490804b
Create Date: 2018-03-07 19:48:06.050926
"""
from alembic import op
from sqlalchemy.dialects import mysql
revision = '08b6358a04bf'
down_revision = '04e61490804b'
branch_labels = None
depends_on = None
def upgrade():
op.alter_col... |
from cl.api import views
from cl.audio import api_views as audio_views
from cl.people_db import api_views as judge_views
from cl.search import api_views as search_views
from django.conf.urls import url, include
from rest_framework.routers import DefaultRouter
router = DefaultRouter()
router.register(r'dockets', search_... |
from django.contrib.auth import get_user_model
from django.utils.translation import ugettext_lazy as _
from rest_framework import serializers
from akvo.rsr.forms import (check_password_minimum_length, check_password_has_number,
check_password_has_upper, check_password_has_lower,
... |
import base64
import random
import string
from binascii import hexlify, unhexlify
from openerp import api, fields, models
try:
from captcha.image import ImageCaptcha
except ImportError:
pass
try:
from simplecrypt import decrypt, encrypt
except ImportError:
pass
class Website(models.Model):
_inherit ... |
from django.db import migrations
import djmoney.models.fields
class Migration(migrations.Migration):
dependencies = [
("projects", "0008_auto_20190220_1133"),
]
operations = [
migrations.AddField(
model_name="project",
name="amount_invoiced",
field=djmoney... |
from django.views.decorators.cache import never_cache
from django.views.generic.base import RedirectView
from C4CApplication.views.utils import create_user
class MemberDetailsRedirectView(RedirectView):
url = ""
connected_member = None
def dispatch(self, request, *args, **kwargs):
# Create the objec... |
"""
Specific overrides to the base prod settings to make development easier.
"""
import logging
from os.path import abspath, dirname, join
from corsheaders.defaults import default_headers as corsheaders_default_headers
from edx_django_utils.plugins import add_plugins
from openedx.core.djangoapps.plugins.constants impor... |
from unittest.mock import ANY, patch
from django.test import override_settings
from geoip2.errors import AddressNotFoundError
from rest_framework import status
from rest_framework.test import APITestCase
from karrot.groups.factories import GroupFactory
from karrot.users.factories import UserFactory
from karrot.utils.ge... |
import logging
import superdesk
from flask import current_app as app
from settings import DAYS_TO_KEEP
from datetime import timedelta
from werkzeug.exceptions import HTTPException
from superdesk.notification import push_notification
from superdesk.io import providers
from superdesk.celery_app import celery
from superde... |
"""
A Python "serializer". Doesn't do much serializing per se -- just converts to
and from basic Python data types (lists, dicts, strings, etc.). Useful as a basis for
other serializers.
"""
from __future__ import unicode_literals
from django.conf import settings
from keops.core.serializers import base
from django.db i... |
"""
Tests the "preview" selector in the LMS that allows changing between Staff, Learner, and Content Groups.
"""
from textwrap import dedent
from common.test.acceptance.fixtures.course import CourseFixture, XBlockFixtureDesc
from common.test.acceptance.pages.common.auto_auth import AutoAuthPage
from common.test.accepta... |
from __future__ import unicode_literals
from django.db import models
from django.utils import timezone
from crm.models import Person
from geocodable.models import LocationAlias
import uuid
class Event(models.Model):
name = models.CharField(max_length=200)
timestamp = models.DateTimeField()
end_timestamp = m... |
""" Models for the shopping cart and assorted purchase types """
from collections import namedtuple
from datetime import datetime
from datetime import timedelta
from decimal import Decimal
import json
import analytics
from io import BytesIO
from django.db.models import Q, F
import pytz
import logging
import smtplib
imp... |
import time
from datetime import date, datetime, timedelta
from optparse import make_option
import openid.store.nonce
from django.conf import settings
from django.core.management.base import BaseCommand
from django.db import connection, transaction
from django.utils.translation import ugettext as _
from identityprovide... |
from odoo.tests import common
from odoo.tests import tagged
@tagged("post_install", "-at_install")
class TestNameCodeYearId(common.SavepointCase):
@classmethod
def setUpClass(cls):
super(TestNameCodeYearId, cls).setUpClass()
cls.event_obj = cls.env['event.event']
cls.skill_type_lang = cl... |
try:
import serial # Python2
except ImportError:
from serial3 import * # Python3
from nupic.frameworks.opf.modelfactory import ModelFactory
import os,sys
ser = serial.Serial('/dev/ttyACM0', 9600)
def get_online(number_of_records=20):# 0 means forever
model = ModelFactory.loadFromCheckpoint(os.getcwd() + "... |
{
'name': 'Partners Persons Management',
'version': '1.0',
'category': 'Tools',
'sequence': 14,
'summary': '',
'description': """
Partners Persons Management
===========================
Openerp consider a person those partners that have not "is_company" as true, now, those partners can have:
---... |
"""
Tests suite for the views of the private messages app.
"""
from django.test import TestCase, Client
from django.conf import settings
from django.core.urlresolvers import reverse
from django.contrib.auth import get_user_model
from django.utils import timezone
from ..models import (PrivateMessage,
... |
from openerp import models, fields, api
class PurchaseOrderLine(models.Model):
_inherit = "purchase.order.line"
@api.multi
@api.depends(
"product_id",
)
def _compute_allowed_purchase_uom_ids(self):
obj_product_uom =\
self.env["product.uom"]
for document in self:
... |
from openerp.osv import fields,osv
import time
import openerp.addons.decimal_precision as dp
from openerp.tools.translate import _
from openerp import pooler
from openerp import netsvc
import base64
from datetime import datetime, timedelta
from dateutil.relativedelta import relativedelta
from openerp.addons.Edumedia_In... |
from requests import post
import io
import base64
class ZivService(object):
def __init__(self, cnc_url, user=None, password=None, sync=True):
self.cnc_url = cnc_url
self.sync = sync
self.auth = None
if user and password:
self.auth = (user,password)
def send_cycle(self... |
"""
Tests for send_email_base_command
"""
import datetime
from unittest import skipUnless
import ddt
import pytz
from django.conf import settings
from mock import DEFAULT, Mock, patch
from openedx.core.djangoapps.schedules.management.commands import SendEmailBaseCommand
from openedx.core.djangoapps.site_configuration.t... |
def configure(app):
if app.config.get('DEBUG_TOOLBAR_ENABLED'):
try:
from flask_debugtoolbar import DebugToolbarExtension
DebugToolbarExtension(app)
except ImportError:
app.logger.info('flask_debugtoolbar is not installed')
if app.config.get('OPBEAT'):
... |
import json
from django.contrib.auth.models import User
from django.core.exceptions import ValidationError
from django.urls import reverse
from django.db import models
from django.utils.html import strip_tags
from opaque_keys.edx.django.models import CourseKeyField
from six import text_type
class Note(models.Model):
... |
"""
Basic unit tests for LibraryContentBlock
Higher-level tests are in `cms/djangoapps/contentstore/tests/test_libraries.py`.
"""
import six
from bson.objectid import ObjectId
from fs.memoryfs import MemoryFS
from lxml import etree
from mock import Mock, patch
from search.search_engine_base import SearchEngine
from six... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.