code
stringlengths
1
199k
import math a,n =10000,10000000 ret = 1 #余数 def PowerMod(a, n, ret): if n == 0: return ret if n % 2: # n为奇数 ret = ret * a % 20132013 return PowerMod(a*a%20132013, n/2, ret) #n为偶数。a^n %m = (a^2^n/2)%m = ((a^2%m)^n/2)%m print PowerMod(a, n, ret)
import unittest from ctauto.exceptions import CTAutoMissingEndOfMetablockError, \ CTAutoBrokenEndOfMetablockError, \ CTAutoInvalidMetablockError, \ CTAutoInvalidIdError, \ CTAutoMissingEndOfStringErro...
"""Basic tests for the CherryPy core: request handling.""" from cherrypy.test import test test.prefer_parent_path() import os localDir = os.path.dirname(__file__) import cherrypy access_log = os.path.join(localDir, "access.log") error_log = os.path.join(localDir, "error.log") tartaros = u'\u03a4\u1f71\u03c1\u03c4\u03b1...
from typing import Optional from django.contrib.auth.models import User from jba_core import exceptions def get_user_by_credentials(username: str, password: str) -> Optional[User]: try: user = User.objects.get(username=username) if not user.check_password(password): raise exceptions.Inco...
from vsg.rules import token_indent from vsg import token lTokens = [] lTokens.append(token.generic_clause.generic_keyword) class rule_002(token_indent): ''' This rule checks the indent of the **generic** keyword. **Violation** .. code-block:: vhdl entity fifo is generic ( entit...
import os import pathlib import sysconfig import compileall import subprocess prefix = pathlib.Path(os.environ.get('MESON_INSTALL_PREFIX', '/usr/local')) datadir = prefix / 'share' destdir = os.environ.get('DESTDIR', '') if not destdir: print('Compiling gsettings schemas...') subprocess.call(['glib-compile-sche...
""" Module implementing a dialog to enter the data for a copy or rename operation. """ from __future__ import unicode_literals import os.path from PyQt5.QtCore import pyqtSlot from PyQt5.QtWidgets import QDialog, QDialogButtonBox from E5Gui.E5PathPicker import E5PathPickerModes from .Ui_HgCopyDialog import Ui_HgCopyDia...
from __future__ import print_function, division, absolute_import import os import sys import time import shutil from six.moves.urllib.request import urlopen from six.moves.urllib.error import URLError, HTTPError import tarfile import platform import numpy as np if sys.version_info[0] == 2: def urlretrieve(url, file...
from dungeon.dungeon import Dungeon, Hub from entity.player.players import Player, Party import entity.item.items as items import sys, os import base import web.server try: import dill except: dill = None PARTY = Party() class Manager: def __init__(self): self.checked = False def get_current_release(self): late...
import os import sys import shutil import straight.plugin import numpy as np import pkg_resources from os import path from core import utils from core import argparser from core import log from core import parser def main(): ## Parse arguments ap = argparser.init_arg_parser() options = ap.parse_args() #...
from SimpleLexicon import SimpleLexicon from LOTlib.Evaluation.EvaluationException import RecursionDepthException class RecursiveLexicon(SimpleLexicon): """ A lexicon where word meanings can call each other. Analogous to a RecursiveLOTHypothesis from a LOTHypothesis. To achieve this, we require the LOThypot...
from PyQt4 import QtCore, QtGui try: _fromUtf8 = QtCore.QString.fromUtf8 except AttributeError: def _fromUtf8(s): return s try: _encoding = QtGui.QApplication.UnicodeUTF8 def _translate(context, text, disambig): return QtGui.QApplication.translate(context, text, disambig, _encoding) exce...
"""A few constants which do not depend on other project files""" DEFAULT_ENCODING = 'utf-8' SETTINGS_ENCODING = 'utf-8' CONFIG_DIR = '.codimension3'
from __future__ import unicode_literals import datetime from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('tableaubord', '0041_auto_20170507_2344'), ] operations = [ migrations.AlterField( model_name='evenement', name='d...
import os from ecmwfapi import ECMWFDataServer server = ECMWFDataServer() time=["06"] year=["2013"] param=["129.128","130.128","131.128","132.128","157.128","151.128"] nam=["hgt","air","uwnd","vwnd","rhum","psl"] for y in year: #for m in month: for p in range(len(param)): for t in time: date=y+"-01-01/to/"+y+"-1...
from _commandbase import RadianceCommand from ..datatype import RadiancePath, RadianceTuple from ..parameters.gensky import GenskyParameters import os class Gensky(RadianceCommand): u""" gensky - Generate an annual Perez sky matrix from a weather tape. The attributes for this class and their data descriptor...
from nose.tools import * from DeckMaker.notetranslator import NoteTranslator def setup(): print "SETUP!" def teardown(): print "TEAR DOWN!" def test_basic(): t = NoteTranslator() assert_equal(t.GetMidiCodeForHumans("E5"),64) assert_equal(t.GetMidiCodeForHumans("C1"),12) assert_equal(t.GetMidiCodeForHumans("...
import sys import os import logging import random import PyQt4 from PyQt4.QtCore import * import constants class Model(QAbstractTableModel): keys = list() modelType = None def __init__(self, parent = None): ''' ''' self.log = logging.getLogger('Model') #self.log.debug('__init__ start...
class System(object): """ This is the father class for all different systems. """ def __init__(self, *args, **kwargs): pass def update(self, dt): raise NotImplementedError
import socket import argparse import sys import magic_ping import os import settings import signal import logging import struct logging.basicConfig(format=u'%(levelname)-8s [%(asctime)s] %(message)s', level=logging.DEBUG, filename=u'client.log') def signal_handler(signal, frame): print("\nSTOP CLIENT.") logging...
import logging import traceback import flask from tribble.api import application from tribble.api import utils from tribble.common.db import db_proc from tribble.common.db import zone_status from tribble.common import rpc from tribble.common import system_config mod = flask.Blueprint('zones', __name__) LOG = logging.ge...
import time import logging logger = logging.getLogger(__name__) import re import urllib2 import urlparse from bs4.element import Comment from ..htmlcleanup import stripHTML from .. import exceptions as exceptions from base_adapter import BaseSiteAdapter, makeDate class LiteroticaSiteAdapter(BaseSiteAdapter): def __...
from copy import deepcopy from base import Base class Container(Base): """ Component that allows an entity to contain one or more child entities. """ def __init__(self): Base.__init__(self, children=list, max_bulk=int) @property def saveable_fields(self): fields = self.fields.key...
from flask import Flask, render_template, request, jsonify, session, redirect, escape, url_for import MySQLdb import bcrypt from esipy import App from esipy import EsiClient from esipy import EsiSecurity from esipy.exceptions import APIException import time import json import requests import datetime import math app = ...
from PyQt5.QtCore import Qt from PyQt5.QtWidgets import QDialog from .details_table import DetailsModel class DetailsDialog(QDialog): def __init__(self, parent, app, **kwargs): super().__init__(parent, Qt.Tool, **kwargs) self.app = app self.model = app.model.details_panel self._setup...
from ePuck import ePuck import time import sys import re epucks = { '1797' : '10:00:E8:6C:A2:B6', '1903' : '10:00:E8:6C:A1:C7' } def log(text): """ Show @text in standart output with colors """ blue = '\033[1;34m' off = '\033[1;m' print(''.join((blue, '[Log] ', off, str(text)))) def error(text): red = '\033[1;31...
from django.contrib import admin from iitem_database.models import Item, ItemClass, Area, Creature, Drops, Found, UserItems, ItemReview admin.site.register(Item) admin.site.register(ItemClass) admin.site.register(Area) admin.site.register(Creature) admin.site.register(Drops) admin.site.register(Found) admin.site.regist...
import sys sys.path.append("..") from ucnacore.PyxUtils import * from math import * from ucnacore.LinFitter import * from bisect import bisect from calib.FieldMapGen import * def clip_function(y,rho,h,R): sqd = sqrt(rho**2-y**2) if sqd==0: sqd = 1e-10 return h*rho**2/R*atan(y/sqd)+2*sqd/(3*R)*(3*h*y/2+rho**2-y**2)...
""" Usage: from PBSQuery import PBSQuery This class gets the info from the pbs_server via the pbs.py module for the several batch objects. All get..() functions return an dictionary with id as key and batch object as value There are four batch objects: - server - queue - job - node Each object can be handled as an ...
from PyQt4 import QtCore, QtGui try: _fromUtf8 = QtCore.QString.fromUtf8 except AttributeError: _fromUtf8 = lambda s: s class Ui_Form(object): def setupUi(self, Form): Form.setObjectName(_fromUtf8("Form")) Form.resize(820, 519) Form.setWindowTitle(_("Form")) self.gridLayout_2...
""" Author : qbeenslee Created : 2014/12/12 """ import re CLIENT_ID = "TR5kVmYeMEh9M" ''' 传输令牌格式 加密方式$迭代次数$盐$结果串 举个栗子: ====start==== md5$23$YUXQ_-2GfwhzVpt5IQWp$3ebb6e78bf7d0c1938578855982e2b1c ====end==== ''' MATCH_PWD = r"md5\$(\d\d)\$([a-zA-Z0-9_\-]{20})\$([a-f0-9]{32})" REMATCH_PWD = re.compile(MATCH_PWD) SUPPORT_I...
from os import path as os_path from sys import path as sys_path from pkgutil import extend_path __extended_path = "/home/pi/Documents/desenvolvimentoRos/src/tf2_ros/src".split(";") for p in reversed(__extended_path): sys_path.insert(0, p) del p del sys_path __path__ = extend_path(__path__, __name__) del extend_...
from Motion import * import sys if __name__ == '__main__': if len(sys.argv) < 2: exit("Must specify target image file") try: drive = Drive() drive.turn(float(sys.argv[1])) except: exit("Specify direction change")
import xml.dom.minidom from time import strftime, strptime from sys import exit from textwrap import wrap from os import path def colorize(the_color='blue',entry='',new_line=0): color={'gray':30,'green':32,'red':31,'blue':34,'magenta':35,'cyan':36,'white':37,'highgreen':42,'highblue':44,'highred':41,'highgray':47} if...
from ert.cwrap import BaseCClass, CWrapper from ert.enkf import AnalysisConfig, EclConfig, EnkfObs, EnKFState, LocalConfig, ModelConfig, EnsembleConfig, PlotConfig, SiteConfig, ENKF_LIB, EnkfSimulationRunner, EnkfFsManager, ErtWorkflowList, PostSimulationHook from ert.enkf.enums import EnkfInitModeEnum from ert.util im...
''' This file is part of pyShop pyShop 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 3 of the License, or (at your option) any later version. pyShop is distributed in the hope that it will be usef...
import hashlib import json import logging import os LOG = logging.getLogger(__name__) from oneconf.hosts import Hosts, HostError from oneconf.distributor import get_distro from oneconf.paths import ONECONF_CACHE_DIR, PACKAGE_LIST_PREFIX class PackageSetHandler(object): """ Direct access to database for getting ...
from __future__ import unicode_literals import markdown from markdown.treeprocessors import Treeprocessor from markdown.blockprocessors import BlockProcessor import re from markdown import util import xml.etree.ElementTree as ET import copy from markdown.inlinepatterns import IMAGE_LINK_RE class InFigureParser(object):...
import tkinter, tkinter.ttk import logging from devparrot.core import session, userLogging class StatusBar(tkinter.Frame, logging.Handler): def __init__(self, parent): tkinter.Frame.__init__(self, parent) logging.Handler.__init__(self) self.pack(side=tkinter.BOTTOM, fill=tkinter.X) s...
from Sire.Base import * from Sire.IO import * from Sire.Mol import * from glob import glob from nose.tools import assert_equal, assert_almost_equal has_mol2 = True try: p = Mol2() except: # No Mol2 support. has_mol2 = False def test_read_write(verbose=False): if not has_mol2: return # Glob a...
''' Dialogs and widgets Responsible for creation, restoration of accounts are defined here. Namely: CreateAccountDialog, CreateRestoreDialog, RestoreSeedDialog ''' from functools import partial from kivy.app import App from kivy.clock import Clock from kivy.lang import Builder from kivy.properties import ObjectProperty...
from ._pylib import ffi, lib from . import tile from cached_property import cached_property def find(path): core = lib.mCoreFind(path.encode('UTF-8')) if core == ffi.NULL: return None return Core._init(core) def findVF(vf): core = lib.mCoreFindVF(vf.handle) if core == ffi.NULL: retur...
""" Define the Expansion Valve component. """ from scr.logic.components.component import Component as Cmp from scr.logic.components.component import ComponentInfo as CmpInfo from scr.logic.components.component import component, fundamental_equation def update_saved_data_to_last_version(orig_data, orig_version): ret...
import datetime import pytest from tests.test_utils import create_generic_job from treeherder.model.models import Push @pytest.fixture def perf_push(test_repository): return Push.objects.create( repository=test_repository, revision='1234abcd', author='foo@bar.com', time=datetime.date...
import hashlib import json import sys import traceback from datetime import datetime, timedelta from functools import wraps from uuid import uuid4 import newrelic.agent import waffle from constance import config from django.apps import apps from django.conf import settings from django.core.exceptions import ValidationE...
from django.db import models from metronus_app.model.actor import Actor from metronus_app.model.task import Task class GoalEvolution(models.Model): """ Each time the goal or the price per unit/hour from a task is changed, a new entry is created in the log Maybe should have been named TaskLog, but... """...
import csv import json import sys import click def score(company, sexbiases): """ Given a company record with board of directors and executive names, return our guess of the % of governance that is male. Since names are not always unambiguous determinants of sex, we also return an error bound, with ...
""" Multi-gpu code for Keras/TF. From https://github.com/avolkov1/keras_experiments """ import sys from itertools import chain import warnings from .multi_gpu_utils import Capturing from keras import backend as KB from keras.layers.core import Lambda from keras.models import Model from keras.layers.merge import Concate...
from . import base_wizard_mixin from . import document_cancel_wizard from . import document_correction_wizard from . import document_status_wizard from . import invalidate_number_wizard
from south.db import db from django.db import models from cm.models import * class Migration: def forwards(self, orm): "Write your forwards migration here" for tv in orm.TextVersion.objects.all(): tv.key = orm.TextVersion.objects._gen_key() tv.adminkey = orm.TextVersion.objec...
from openerp.osv import orm, fields import decimal_precision as dp import netsvc from tools import ustr class sale_order_confirm(orm.TransientModel): _inherit = "sale.order.confirm" _columns = { 'cig': fields.char('CIG', size=64, help="Codice identificativo di gara"), 'cup': fields.char('CUP', s...
from docx import Document import datetime from schedule.Assignment import * DATE = 0 SECTION_A_PARTICIPANTS = 1 SECTION_A_LESSON = 2 SECTION_B_PARTICIPANTS = 3 SECTION_B_LESSON = 4 HEADER = 'Date,Type,Assignee,Householder,Lesson,Classroom' def getWeekDate(weekHeaderRow, year, month): '''extract the date from the da...
import win32file # The base COM port and file IO functions. import win32event # We use events and the WaitFor[Single|Multiple]Objects functions. import win32con # constants. from serialutil import * VERSION = "$Revision: 1527 $".split()[1] #extract CVS version MS_CTS_ON = 16 MS_DSR_ON = 32 MS_RING_ON = 64 MS_R...
import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) ADMINS = ( ("David Barragán", "bameda@dbarragan.com"), ) SECRET_KEY = '0q)_&-!hu%%en55a&cx!a2c^7aiw*7*+^zg%_&vk9&4&-4&qg#' DEBUG = False ALLOWED_HOSTS = ['*'] DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3...
""" This module provides functions to parse a DEP. """ from builtins import int from builtins import range from .gettext_helper import _ import copy import ijson from math import ceil from six import string_types from . import utils from . import receipt class DEPException(utils.RKSVVerifyException): """ An exc...
def migrate(cr, version): if not version: return # Replace ids of better_zip by ids of city_zip cr.execute(""" ALTER TABLE crm_event_compassion DROP CONSTRAINT crm_event_compassion_zip_id_fkey; UPDATE crm_event_compassion e SET zip_id = ( SELECT id FROM re...
from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('website', '0036_auto_20170813_0049'), ] operations = [ migrations.AlterField( model_name='userprofile', name='follows', ...
""" A throwaway thread pool with thread-local storage. Throwaway Tasks =============== A throwaway task is one you'd *like* to get done, but it's not a big deal if it doesn't actually get done. Scary as it may be, throwaway tasks are quite common in the wild. They usually compute for a while and then *end* with *one* o...
"""Process one email message, read from stdin.""" import _pythonpath import sys from lp.services.config import config from lp.services.mail.helpers import save_mail_to_librarian from lp.services.mail.incoming import handle_one_mail from lp.services.mail.signedmessage import signed_message_from_string from lp.services.s...
import flask mod = flask.Blueprint('api', __name__)
from odoo import models class SaleOrder(models.Model): _inherit = "sale.order" def action_confirm(self): res = super(SaleOrder, self).action_confirm() for order in self: order.procurement_group_id.stock_move_ids.created_production_id.write( {"analytic_account_id": ord...
from django.conf.urls.defaults import * urlpatterns = patterns('', url(r'^$', 'blog.views.entry_list', name="entry-list"), url(r'^archive/(?P<year>\d{4})/$', 'blog.views.entry_archive_year', name="year-archive"), url(r'^archive/(?P<year>\d{4})/(?P<month>\d{1,2})/$', 'blog.views.entry_archive_month', name="m...
from twisted.trial.unittest import TestCase from mock import Mock from twisted.web.test.test_web import DummyRequest from twisted.web.http import OK, NOT_FOUND from cryptosync.resources import make_site def make_request(uri='', method='GET', args={}): site = make_site(authenticator=Mock()) request = DummyReques...
{ "name": "Purchase Order Approved", "summary": "Add a new state 'Approved' in purchase orders.", "version": "14.0.1.1.0", "category": "Purchases", "website": "https://github.com/OCA/purchase-workflow", "author": "ForgeFlow, Odoo Community Association (OCA)", "license": "AGPL-3", "applic...
""" Copyright (C) 2008 by Steven Wallace snwallace@gmail.com 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 3 of the License, or (at your option) any later versio...
import logging from odoo import api, fields, models, _ from odoo.exceptions import UserError, ValidationError from odoo.tools.safe_eval import safe_eval _logger = logging.getLogger(__name__) class DeliveryCarrier(models.Model): _name = 'delivery.carrier' _inherits = {'product.product': 'product_id'} _descri...
from __future__ import unicode_literals import json from rest_framework.test import APIClient from rest_framework import status from shuup.core.models import Order from shuup.testing.factories import ( create_order_with_product, get_default_product, get_default_shop, get_default_supplier ) def create_order(): ...
''' @since: 2015-01-07 @author: moschlar ''' import sqlalchemy.types as sqlat import tw2.core as twc import tw2.bootstrap.forms as twb import tw2.jqplugins.chosen.widgets as twjc import sprox.widgets.tw2widgets.widgets as sw from sprox.sa.widgetselector import SAWidgetSelector from sprox.sa.validatorselector import SAV...
""" Code to allow module store to interface with courseware index """ from __future__ import absolute_import from abc import ABCMeta, abstractmethod from datetime import timedelta import logging import re from six import add_metaclass from django.conf import settings from django.utils.translation import ugettext_lazy, ...
import stock_production_lot_ext import stock_picking_ext import stock_move_ext import purchase_order_ext import stock_move_split_ext
""" Module exports :class:`AtkinsonWald2007`. """ from __future__ import division import numpy as np from openquake.hazardlib.gsim.base import IPE from openquake.hazardlib import const from openquake.hazardlib.imt import MMI class AtkinsonWald2007(IPE): """ Implements IPE developed by Atkinson and Wald (2007) ...
""" A simple bot to gather some census data in IRC channels. It is intended to sit in a channel and collect the data for statistics. :author: tpltnt :license: AGPLv3 """ import irc.bot import irc.strings from irc.client import ip_numstr_to_quad, ip_quad_to_numstr class CensusBot(irc.bot.SingleServerIRCBot): """ ...
import uuid from django.conf import settings from django.core.cache import cache from django.urls import reverse def _mk_key(token): return "one-time-data-" + token def set_one_time_data(data): token = str(uuid.uuid4()) key = _mk_key(token) cache.set(key, data, 60) return '{}://{}{}'.format(settings...
from . import hr_certification from . import hr_training_participant
"""Make session:proposal 1:1. Revision ID: 3a6b2ab00e3e Revises: 4dbf686f4380 Create Date: 2013-11-09 13:51:58.343243 """ revision = '3a6b2ab00e3e' down_revision = '4dbf686f4380' from alembic import op def upgrade(): op.create_unique_constraint('session_proposal_id_key', 'session', ['proposal_id']) def downgrade():...
from __future__ import with_statement import re from weboob.capabilities.gallery import ICapGallery, BaseGallery, BaseImage from weboob.tools.backend import BaseBackend from weboob.tools.browser import BaseBrowser, BasePage __all__ = ['GenericComicReaderBackend'] class DisplayPage(BasePage): def get_page(self, gall...
import os test_dir = os.path.dirname(__file__) DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(test_dir, 'db.sqlite3'), } } INSTALLED_APPS = [ 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.auth', 'django.contrib....
class FieldRegistry(object): _registry = {} def add_field(self, model, field): reg = self.__class__._registry.setdefault(model, []) reg.append(field) def get_fields(self, model): return self.__class__._registry.get(model, []) def __contains__(self, model): return model in...
__metaclass__ = type from zope.component import ( ComponentLookupError, getMultiAdapter, ) from zope.configuration import xmlconfig from zope.interface import ( implements, Interface, ) from zope.publisher.interfaces.browser import ( IBrowserPublisher, IDefaultBrowserLayer, ) from zo...
import os import sys import glob import json import subprocess from collections import defaultdict from utils import UnicodeReader, slugify, count_pages, combine_pdfs, parser import addresscleaner from click2mail import Click2MailBatch parser.add_argument("directory", help="Path to downloaded mail batch") parser.add_ar...
from . import test_employee_display_own_info
from django.conf.urls import patterns, url from application import views urlpatterns = patterns('', url(r'^$', views.index, name='index'), url(r'^(?P<application_id>\d+)/$', views.detail, name='detail'), url(r'^klogin/(?P<username>\w+)/(?P<password>\w+)/$', views.klogin, name='klogin'), )
from disco.core import Disco, result_iterator from disco.settings import DiscoSettings from disco.func import chain_reader from discodex.objects import DataSet from freequery.document import docparse from freequery.document.docset import Docset from freequery.index.tf_idf import TfIdf class IndexJob(object): def __...
from __future__ import unicode_literals import sys from intelmq.lib import utils from intelmq.lib.bot import Bot from intelmq.lib.message import Event class MalwareGroupIPsParserBot(Bot): def process(self): report = self.receive_message() if not report: self.acknowledge_message() ...
import os, subprocess import argparse parser = argparse.ArgumentParser() parser.add_argument('--virus', default="flu", help="virus to download; default is flu") parser.add_argument('--flu_lineages', default=["h3n2", "h1n1pdm", "vic", "yam"], nargs='+', type = str, help ="seasonal flu lineages to download, options are ...
{ "name": "Product Code Unique", "summary": "Add the unique property to default_code field", "version": "9.0.1.0.0", "category": "Product", "website": "https://odoo-community.org/", "author": "<Deysy Mascorro>, Odoo Community Association (OCA)", "license": "AGPL-3", "application": False,...
import ddt from django.contrib.auth import login, authenticate from importlib import import_module from django_lti_tool_provider import AbstractApplicationHookManager from mock import patch, Mock from oauth2 import Request, Consumer, SignatureMethod_HMAC_SHA1 from django.contrib.auth.models import User from django.test...
import pytest from django.urls import reverse from adhocracy4.dashboard import components from adhocracy4.test.helpers import assert_template_response from adhocracy4.test.helpers import redirect_target from adhocracy4.test.helpers import setup_phase from meinberlin.apps.topicprio.models import Topic from meinberlin.ap...
from flask import Blueprint, render_template from flask.ext.security import current_user mod = Blueprint('documentation', __name__) @mod.route('/documentation') @mod.route('/documentation/index') def doc_index(): return render_template('documentation/index.html', apikey='token' if current_user.is_a...
from __future__ import absolute_import import unittest from gateway.dto import SensorDTO, SensorSourceDTO from gateway.api.serializers import SensorSerializer class SensorSerializerTest(unittest.TestCase): def test_serialize(self): # Valid room data = SensorSerializer.serialize(SensorDTO(id=1, name=...
import logging from datetime import datetime from openerp import SUPERUSER_ID from openerp.osv import orm, fields from openerp.tools import DEFAULT_SERVER_DATETIME_FORMAT _logger = logging.getLogger(__name__) _logger.setLevel(logging.DEBUG) class stock_location(orm.Model): _inherit = "stock.location" _columns =...
from coriolis import utils from coriolis.conductor.rpc import client as rpc_conductor_client from coriolis.minion_manager.rpc import client as rpc_minion_manager_client class API(object): def __init__(self): self._rpc_conductor_client = rpc_conductor_client.ConductorClient() self._rpc_minion_manager...
""" Global settings file. Everything in here is imported *before* everything in settings.py. This means that this file is used for default, fixed and global varibles, and then settings.py is used to overwrite anything here as well as adding settings particular to the install. Note that there are no tuples here, as they...
import logging, logging.handlers import sys logging.handlers.HTTPHandler('','',method='GET') logger = logging.getLogger('simple_example') http_handler = logging.handlers.HTTPHandler('127.0.0.1:9999', '/httpevent', method='GET') logger.addHandler(http_handler) f=open(sys.argv[1]) for i in range(10): line = f.readlin...
import attr from osis_common.ddd import interface @attr.s(frozen=True, slots=True) class EntiteUclDTO(interface.DTO): sigle = attr.ib(type=str) intitule = attr.ib(type=str)
from flask import ( Blueprint, render_template, redirect, url_for, request, flash, current_app, g, ) from flask_login import ( current_user, ) from flask_wtf import Form from wtforms import ( SubmitField, BooleanField, DecimalField, ) from wtforms.validators import DataRe...
from django.dispatch import receiver from assessments.business import scores_encodings_deadline from base.signals import publisher @receiver(publisher.compute_scores_encodings_deadlines) def compute_scores_encodings_deadlines(sender, **kwargs): scores_encodings_deadline.compute_deadline(kwargs['offer_year_calendar'...
from django.contrib import auth from django.contrib.auth.models import User from django.test import TestCase from django.urls.base import reverse class TestAccountRegistration(TestCase): def setUp(self): # create one user for convenience response = self.client.post( reverse('account:regi...
import analytics import anyjson from channels import Group from django.conf import settings from django.utils.translation import ugettext_lazy as _ from rest_framework import serializers from lily.accounts.api.serializers import RelatedAccountSerializer from lily.api.fields import SanitizedHtmlCharField from lily.api.n...
from openerp.osv import orm, fields from openerp.tools.translate import _ class create_extra_documentation(orm.TransientModel): _name = 'module.doc.create' def create_documentation(self, cr, uid, ids, context=None): doc_obj = self.pool.get('module.doc') mod_obj = self.pool.get('ir.module.module'...