content
string
import os from log_picker.sending.senderbaseclass import SenderBaseClass from log_picker.sending.senderbaseclass import SenderError from report.plugins.bugzilla import filer from report.plugins.bugzilla.filer import CommunicationError from report.plugins.bugzilla.filer import LoginError class BugzillaBaseClass(Sender...
#!/usr/bin/env python """ A pure python ping implementation using raw socket. Note that ICMP messages can only be sent from processes running as root. Derived from ping.c distributed in Linux's netkit. That code is copyright (c) 1989 by The Regents of the University of California. That code is ...
#!/usr/bin/env python ''' Run this script inside of src/ and it will look for all the files that were changed this year that still have the last year in the copyright headers, and it will fix the headers on that file using a perl regex one liner. For example: if it finds something like this and we're in 2014 // Copyr...
# # (c) Peralta Informatics 2007 # $Id: DeployDatabaseModule.py 299 2008-01-19 08:42:05Z andrei $ # import clr import sys import os import shutil clr.AddReference("System.Data") clr.AddReference("System.Xml") import System.Data import System.Data.SqlClient import System.Diagnostics import System.Text import System.X...
"""Contains a metaclass and helper functions used to create protocol message classes from Descriptor objects at runtime. Recall that a metaclass is the "type" of a class. (A class is to a metaclass what an instance is to a class.) In this case, we use the GeneratedProtocolMessageType metaclass to inject all the usefu...
import string import utils from Variable import Variable import VariableFactory """ Variable type for Sequences ('sequence' format) """ class VariableSequence(Variable): """ Constructor """ def __init__(self, dictionary, sequence_type_name, container_type): # Call the parent constructor ...
#!/usr/bin/env python # -*- coding: utf8 -*- """ Synchronize directory groups This script copies all members of a list of groups to another group. Members may be replaced or added. If a member of a target group is objectClass=group, it will not be purged. (c) 2015, Simon Wunderlin """ # setup paths import os, sys,...
import msrest.serialization class DenyAssignment(msrest.serialization.Model): """Deny Assignment. Variables are only populated by the server, and will be ignored when sending a request. :ivar id: The deny assignment ID. :vartype id: str :ivar name: The deny assignment name. :vartype name: st...
from systemdlogger.plugin import PluginBase from elasticsearch_dsl.connections import connections from elasticsearch_dsl import DocType, Date, String from datetime import datetime class EsLog(DocType): timestamp = Date() message = String(index='not_analyzed') index = 'logs-%s' % datetime.now().strftime('...
import datetime, time crontable = [] outputs = [] slack = None my_uid = None users = {} def setup(given_bot): global slack, my_uid, users print("ingress-septicycle: setup()") slack = given_bot.slack_client my_uid = slack.server.login_data['self']['id'] for u in slack.server.login_data['users']: ...
#!/usr/bin/env python # -*- coding: utf-8 -*- import io import os import re import sys from setuptools import setup, find_packages here = os.path.abspath(os.path.dirname(__file__)) with io.open(os.path.join(here, 'README.rst'), encoding='utf-8') as f: readme = f.read() with io.open(os.path.join(here, 'HISTORY....
""" Testing suite for contrib folder """ from evennia.utils.test_resources import EvenniaTest # testing of rplanguage module from evennia.contrib import rplanguage mtrans = {"testing":"1", "is": "2", "a": "3", "human": "4"} atrans = ["An", "automated", "advantageous", "repeatable", "faster"] text = "Automated tes...
"""`main` is the top level module for your Flask application.""" import logging # Import the Flask Framework from flask import Flask, Response, request, g, jsonify from functools import wraps import urllib2 import json from datetime import datetime, timedelta from pytz import timezone, utc from openweathermap import ...
from flask import request, jsonify, abort, make_response, render_template from app.models import BucketList, BucketListItem from .auth_wrapper import evaluate_auth from . import app @app.route('/', methods=['GET']) def index(): return render_template('index.html') @app.route('/api/v1/bucketlists/', methods=['P...
__copyright__ = "Copyright 2017 Birkbeck, University of London" __author__ = "Martin Paul Eve & Andy Byers" __license__ = "AGPL v3" __maintainer__ = "Birkbeck Centre for Technology and Publishing" from django.core.exceptions import ObjectDoesNotExist from journal import models as journal_models from press import mode...
#!/usr/bin/env python # -*- coding: utf-8 -*- from main.transport_core.transport_cores import TRANSPORT_CORES __author__ = "Ivan de Paz Centeno" import logging from pyvirtualdisplay import Display from selenium.webdriver import Firefox from selenium import webdriver from selenium.webdriver.common.by import By from sel...
from __future__ import unicode_literals from portage.util.elf.constants import ( EF_MIPS_ABI, EF_MIPS_ABI2, ELFCLASS32, ELFCLASS64, EM_386, EM_68K, EM_AARCH64, EM_ALPHA, EM_ARM, EM_IA_64, EM_MIPS, EM_PARISC, EM_PPC, EM_PPC64, EM_S390, EM_SH, EM_SPARC, EM_SPARC32PLUS, EM_SPARCV9, EM_X86_64, E_MIPS_ABI_EABI32, E_MI...
from __future__ import print_function from builtins import range import sys sys.path.insert(1,"../../../") import h2o from tests import pyunit_utils import random def cv_carsGLM(): # read in the dataset and construct training set (and validation set) cars = h2o.import_file(path=pyunit_utils.locate("smalld...
from django.contrib.syndication.feeds import Feed from django.utils.feedgenerator import Atom1Feed from oi.st.models import Game, FS, News, Package, HowTo, Workshop from oi.settings import WEB_URL, SITE_NAME, SITE_DESC, NEWS_IN_HOMEPAGE, PACKAGES_IN_HOMEPAGE, GAMES_IN_HOMEPAGE, FS_IN_HOMEPAGE, HOWTOS_IN_HOMEPAGE, NEWS...
import os.path, uuid from supysonic.db import Folder, Artist, Album, Track, StarredFolder, RatingFolder from supysonic.scanner import Scanner class FolderManager: SUCCESS = 0 INVALID_ID = 1 NAME_EXISTS = 2 INVALID_PATH = 3 PATH_EXISTS = 4 NO_SUCH_FOLDER = 5 SUBPATH_EXISTS = 6 @staticmethod def get(store, uid...
import bge from bge import logic as g from math import * from mathutils import * from sss_dynamic import sssDynamic from sss_destroyable import sssDestroyable ERROR_RADIUS = 200.0 class sssGun(sssDynamic, sssDestroyable): def __init__(self, obj): sssDynamic.__init__(self, obj) sssDestroyable.__i...
""" Generic, re-usable views for use with Fedora-based Django projects. These views expose data intended for use with :mod:`eulindexer`. These views currently return data in JSON form. Projects that use this module should include the following settings in their ``settings.py``:: # Index server url. In this exampl...
from oslo_log import log as logging from sqlalchemy import MetaData, Table, Index LOG = logging.getLogger(__name__) INDEX_COLUMNS = ['updated_at'] INDEX_NAME = 'migrations_updated_at_idx' TABLE_NAME = 'migrations' def _get_table_index(migrate_engine): meta = MetaData() meta.bind = migrate_engine table =...
""" Python-WorkQueue test """ from work_queue import Task, WorkQueue, set_debug_flag from work_queue import WORK_QUEUE_SCHEDULE_FCFS, WORK_QUEUE_SCHEDULE_FILES from work_queue import WORK_QUEUE_RANDOM_PORT from work_queue import WORK_QUEUE_OUTPUT #from workqueue import WORK_QUEUE_MASTER_MODE_STANDALONE, WORK_QUEUE_WOR...
import json import os import time import traceback import Queue from grokcore.component import context from hashlib import sha1 from twisted.web.server import NOT_DONE_YET from twisted.python import log from twisted.internet import reactor, threads, defer from zope.component import queryAdapter, handle from zope.secur...
from weakref import WeakKeyDictionary class DiffResultDescriptor: """Descriptor for managing diff results.""" # @properties could be used instead, but there are so # many result attributes, this will keep the code cleaner. def __init__(self, diff_function): self.diff_function = diff_functio...
from django.test import TestCase from django_inlines import registry from django_inlines.parsing import Lexer, Parser from django_inlines.errors import InlineSyntaxError from test_app.inlines import BasicInline from .test_common import InlinesTestCase __all__ = ('LexerTestCase', 'ParserTestCase',) class LexerTest...
# -*- coding: utf-8 -*- import json import os import sys import getopt import random rooms = [] player = {} mobs = [] skills = [] items = [] difficulty = [] inputRequest = [] availableExits = [] gameoverTexts = {} currentRoomId = "" debug = 0 def outputStr(string): print string def debugOutputStr(string, debugL...
from django.contrib import admin from leagues.models import League, Team from players.models import Player class TeamInline(admin.TabularInline): model = Team extra = 0 show_change_link = True readonly_fields = ['name', 'owner', 'record'] exclude = ['players', 'wins', 'losses', 'ties'] def h...
# -*- coding: utf-8 -*- """ dicom2nifti @author: abrys """ import logging import nibabel import numpy from pydicom.tag import Tag import dicom2nifti.common as common import dicom2nifti.settings as settings import dicom2nifti.resample as resample from dicom2nifti.exceptions import ConversionError, ConversionValidatio...
"""Workers to process data. This module contains all the workers which allow to process data. """ from streambug import worker from streambug import mplogger log = mplogger.getLogger() class DummyProcessor(worker.DefaultWorker): """Dummy processor. It just forwards all received data.""" def __init__(self,...
# simple OpenPIC implementation in python # MODULE: open-pic # CLASS: open-pic from sim_core import * spacename = { Sim_Addr_Space_Memory : "Sim_Addr_Space_Memory", Sim_Addr_Space_IO : "Sim_Addr_Space_IO", Sim_Addr_Space_Conf : "Sim_Addr_Space_Conf", } def show_map_info(info): print " info.ba...
# see also: http://github.com/tav/scripts/raw/master/validate_jsonp.py # Placed into the Public Domain by tav <<EMAIL>> """Validate Javascript Identifiers for use as JSON-P callback parameters.""" import re from unicodedata import category # -------------------------------------------------------------------------...
#!/usr/bin/env python3 from bs4 import BeautifulSoup from sys import argv from sys import exit from sys import exit import urllib.request import subprocess as sp import re import argparse def cleanFrom(element): try: for link in element.strong.find_all('a'): link.extract() except Attribut...
import sys texA = """\ \\documentclass[tikz]{standalone} \\usetikzlibrary{shapes.geometric} \\begin{document} \\begin{tikzpicture}[ rotate=-45, every label/.append style={text depth=+0pt}, label position=center, """ texB = """\ ] \\foreach \\jRow[count=\\jCount from 1, remember=\\mCount] in {% """ c = ...
#!/usr/bin/env python #! -*- coding: utf-8 -*- """Information-retrieval for goo.gl link.""" from __future__ import unicode_literals import click from datetime import datetime import lnk.abstract import lnk.beauty from lnk.googl.command import Command def echo(*args): """ Executes an info command and echoes its...
# -*- coding: utf-8 -*- from __future__ import unicode_literals import os import shutil import subprocess import logging import audiotools from django.conf import settings log = logging.getLogger(__name__) LAME_BINARY = getattr(settings, "LAME_BINARY") SOX_BINARY = getattr(settings, "SOX_BINARY") FAAD_BINARY = getat...
import datetime import unittest from unittest import mock from airflow.models.dag import DAG from airflow.providers.microsoft.azure.sensors.wasb import WasbBlobSensor, WasbPrefixSensor class TestWasbBlobSensor(unittest.TestCase): _config = { 'container_name': 'container', 'blob_name': 'blob', ...
import re import html2text from fi_common import Item, StaticParser, absolutise_url def generate_picker_pattern(url, hostname): return (lambda: re.match(r'.*\.ocasiao\.pt', hostname), lambda: Ocasiao(url)) class Ocasiao(StaticParser): def id(self): return 'Ocasiao' def extract_items(self, parse...
"""Provide a couple of :py:class:`datetime.tzinfo` compatible objects representing local time and UTC. Introduction ------------ This module provides two :py:class:`datetime.tzinfo` compatible objects representing UTC and local time zones. These are used to convert timestamps to and from UTC and local time. The weath...
""" Management command `manage_user` is used to idempotently create or remove Django users, set/unset permission bits, and associate groups by name. """ from django.contrib.auth import get_user_model from django.contrib.auth.hashers import is_password_usable from django.contrib.auth.models import Group from django.co...
from vitrage.datasources.nagios.properties import NagiosProperties \ as NagiosProps from vitrage.tests import base class NagiosBaseTest(base.BaseTest): def _assert_contains(self, expected_service, services): for service in services: if service[NagiosProps.RESOURCE_NAME] == \ ...
import os import pytest from .context import pwmodel as pwm from .context import phpbb_leak_file leak_file = phpbb_leak_file @pytest.mark.parametrize( 'ngrampw', [pwm.models.NGramPw(pwfilename=leak_file)] ) class TestNgram(object): @pytest.mark.parametrize('word', ['asd', 'a']) def test_small_word(se...
""" A neural chatbot using sequence to sequence model with attentional decoder. This is based on Google Translate Tensorflow model https://github.com/tensorflow/models/blob/master/tutorials/rnn/translate/ Sequence to sequence model by Cho et al.(2014) Created by Chip Huyen (<EMAIL>) CS20: "TensorFlow for Deep Lear...
"""test the RunMetadata proto.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from collections import defaultdict import six from tensorflow.core.protobuf import config_pb2 from tensorflow.python.client import session from tensorflow.python.framework ...
from os import listdir from os.path import join as path_join from unittest import main from uuid import uuid4 from eventlet import GreenPool, Timeout import eventlet from sqlite3 import connect from swiftclient import client from swift.common import direct_client from swift.common.exceptions import ClientException fr...
# # This class downloads the movies from # Twitter and parses them out for us. # from keys import APIKeys # Abstract out aPI keys for privacy from TwitterUtils import TwitterUtils # Utility to manipulate Tweets import twitter # Basis for twitter operations import time # Used for counting time until rate limit ...
from superdesk.celery_app import update_key, set_key from superdesk.resource import Resource from superdesk.services import BaseService from superdesk.metadata.item import metadata_schema from superdesk.metadata.utils import extra_response_fields, item_url, aggregations from eve.defaults import resolve_default_values f...
#!env python from setuptools import setup INSTALL_REQUIREMENTS = [ 'argparse' ] VERSION = '1.0.2' setup(name='webbench', version=VERSION, packages=[ 'webbench', ], classifiers=[ 'Development Status :: 5 - Production/Stable', 'Environment :: Console', ...
class Cache(object): 'empty base class to enable isinstance(foo, cache.Cache)' class LRUCache(Cache): ''' Implements an LRU cache based on a linked list. Performance is about 1.1 microseconds per set/get on a core i7 ''' def __init__(self, maxlen=10000): self.map = {} self.root...
'''subclassing kde Author: josef pktd ''' import numpy as np import scipy from scipy import stats import matplotlib.pylab as plt class gaussian_kde_set_covariance(stats.gaussian_kde): ''' from Anne Archibald in mailinglist: http://www.nabble.com/Width-of-the-gaussian-in-stats.kde.gaussian_kde---td1955892...
import logging import urllib import uuid from google.appengine.ext import deferred from google.appengine.api import urlfetch from controllers.gcm.gcm import GCMMessage from consts.client_type import ClientType from consts.notification_type import NotificationType from helpers.firebase.firebase_pusher import FirebaseP...
from __future__ import print_function import json import os import re import sys import xml.etree.ElementTree as etree from Cython.Compiler.Main import compile_single, CompilationOptions from Cython.Compiler.TreeFragment import parse_from_strings from Cython.Compiler.Visitor import TreeVisitor from Cython.Compiler i...
""" Support for Fibaro cover - curtains, rollershutters etc. For more details about this platform, please refer to the documentation at https://home-assistant.io/components/cover.fibaro/ """ import logging from homeassistant.components.cover import ( CoverDevice, ENTITY_ID_FORMAT, ATTR_POSITION, ATTR_TILT_POSITIO...
from __future__ import (absolute_import, division, print_function) __metaclass__ = type import os import sys import tempfile import yaml from collections import namedtuple from ansible.config.data import ConfigData from ansible.errors import AnsibleOptionsError, AnsibleError from ansible.module_utils.six import stri...
import time from mongodisco.job import DiscoJob from disco.core import Job,result_iterator from mongodisco.mongodb_io import mongodb_output_stream,mongodb_input_stream from mongodisco.splitter import calculate_splits as do_split import pymongo from pymongo import Connection from mongodisco.mongo_util import get_collect...
from numbers import Number from collections import Iterable import re import pandas as pd from pandas.io.stata import StataReader import numpy as np pd.set_option('expand_frame_repr', False) class hhkit(object): def __init__(self, *args, **kwargs): # if input data frame is specified as a stata data file or text ...
import Image import os,sys import argparse import common import utils def encodeChinese(msg): type = sys.getfilesystemencoding() return msg.decode('utf-8').encode(type) image_path='保存图片的路径' log_path='输出错误日志' help_image_path=encodeChinese(image_path) help_log_path=encodeChinese(log_path) help_path=encodeChinese('检测...
import math from rsqueakvm import constants, error from rsqueakvm.model.base import W_Object, W_AbstractObjectWithIdentityHash, W_AbstractObjectWithClassReference from rpython.rlib import longlong2float, jit from rpython.rlib.rarithmetic import intmask, r_uint32, r_uint, ovfcheck, r_int64, r_ulonglong from rpython.rl...
import os from django.conf import settings from django.core.management.base import BaseCommand from optparse import make_option from create_indexes import create_indexes from create_event_types import add_event_types from create_locations import add_location_objects from create_object_types import add_object_types fr...
import json import multiprocessing import random from mock import Mock from silk.utils.six import b # noinspection PyUnresolvedReferences from silk.utils.six.moves.BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler # noinspection PyUnresolvedReferences from silk.utils.six.moves.urllib.parse import urlparse, par...
"""vm_vdi_cleaner.py - List or clean orphaned VDIs/instances on XenServer.""" import doctest import os import sys from oslo.config import cfg import XenAPI possible_topdir = os.getcwd() if os.path.exists(os.path.join(possible_topdir, "nova", "__init__.py")): sys.path.insert(0, possible_topdir) from nova imp...
"""Module for handling Android String and Plurals resource files.""" import copy import os import re import six from lxml import etree from translate.lang import data from translate.storage import base, lisa from translate.misc.multistring import multistring from babel.core import Locale EOF = None WHITESPACE = ' ...
"""Configurations for py.test runner""" import pytest from robottelo.config import settings from robottelo.logging import collection_logger @pytest.fixture(scope='session') def configured_settings(): if not settings.configured: settings.configure() return settings @pytest.fixture def test_name(requ...
""" Usage:: hammer task [OPTIONS] SUBCOMMAND [ARG] ... Parameters:: SUBCOMMAND subcommand [ARG] ... subcommand arguments Subcommands:: list List tasks progress Show the progress of the task resume ...
from nose.plugins.skip import SkipTest import dummy from vdsm.ipwrapper import linkAdd, IPRoute2Error from vdsm.utils import random_iface_name def create(prefix='veth_', max_length=15): """ Create a veth interface with a pseudo-random suffix (e.g. veth_m6Lz7uMK9c) for both endpoints. Use the longest poss...
#!/usr/bin/python from wixlib import * version = extract_version_information('/home/andres/Projects/CS') version_stringed = version.replace('.', '_') version_full = version + '.3' upgrade_code = '933473B2-62E5-11DC-99EE-0015582877AD' outdir = '/mnt/vm_1/work' def gen_b2cs_blender_plugin_msm(): (base, merge, dir)...
import logging from odoo import api, fields, models _logger = logging.getLogger(__name__) class VerificationTemplateMassEdit(models.TransientModel): _description = 'Verification Template Mas Edit' _name = 'clv.verification.template.mass_edit' def _default_verification_template_ids(self): return...
# -*- coding: utf-8 -*- r""" .. _tut-freesurfer-reconstruction: ============================= FreeSurfer MRI reconstruction ============================= FreeSurfer is an open source analysis toolbox for MRI data. It contains several command line tools and graphical user interfaces. FreeSurfer can be obtained from ht...
from south.db import db from django.db import models from treepages.models import * class Migration: def forwards(self, orm): # Adding field 'Page.associated_color' db.add_column('treepages_page', 'associated_color', orm['treepages.page:associated_color']) def b...
# # This program solves genereal 2'nd order diff. eq's using RK4. # General form of diff eq.: # # dx^2/dt^2 + p(t,x,v)*dx/dt + q(t,x,v)*x = r(t,x,v) # # This can generally be decomposed to two coupled 2nd order eq's: # dx^2/dt^2 = dv/dt = r - p*v - q*x # dx/dt = v # # These equations are implemented by the functions "...
import numpy as np from ..fileio import FileIO as psopen from ...common import pandas #import pysal_examples from ... import examples as pysal_examples import unittest as ut PANDAS_EXTINCT = pandas is None class Test_Table(ut.TestCase): def setUp(self): self.filehandler = psopen(pysal_examples.get_path('...
#!/usr/bin/env python """ test_spec --------- Tests for the the SSV specification. """ import tempfile import unittest import ssv from ssv.constant import RS from ssv.constant import US class TestSpec(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def check_in_o...
import logging import os import subprocess from toil.common import Toil from toil.job import Job from toil.version import python logger = logging.getLogger(__name__) ''' This workflow's purpose is to create files and jobs for viewing using stats, status, and printDot() in toilDebugTest.py. It's intended for future ...
# -*- coding: utf-8 -*- import pytest from django.core.exceptions import ValidationError from django.apps import apps from django.db.models.fields.related import ForeignKey from django.db.models.fields.related_descriptors import ( ReverseManyToOneDescriptor, ForwardManyToOneDescriptor ) from rest_framework.se...
""" Certificate manager API """ import abc import six @six.add_metaclass(abc.ABCMeta) class Cert(object): """Base class to represent all certificates.""" @abc.abstractmethod def get_certificate(self): """Returns the certificate.""" pass @abc.abstractmethod def get_intermediates(...
#!/usr/bin/env python # -*- coding: utf-8 -*- from urllib2 import urlopen from selenium import webdriver from selenium.webdriver.support.ui import WebDriverWait from selenium.common.exceptions import WebDriverException import time def internet_on(): try: resp = urllib2.urlopen("http://www.google.com/", tim...
from axelrod import Player class Grumpy(Player): """A player that defects after a ceratin level of grumpiness. Grumpiness increases when the opponent defects and decreases when the opponent co-operates.""" name = 'Grumpy' classifier = { 'memory_depth': float('inf'), # Long memory ...
from pymobiledevice.lockdown import LockdownClient from pprint import pprint import plistlib from optparse import OptionParser Requests = """Goodbye All GasGauge WiFi Shutdown Restart MobileGestalt Sleep NAND IORegistry Obliterate """ """ BasebandKeyHashInformation BasebandFirmwareManifestData """ MobileGestaltKeys ...
from tempest.lib.common.utils import data_utils from tempest.lib import exceptions as lib_exc from testtools import testcase as tc from manila_tempest_tests.tests.api import base class ShareTypesAdminNegativeTest(base.BaseSharesMixedTest): def _create_share_type(self): name = data_utils.rand_name("uniqu...
from __future__ import (absolute_import, division, print_function) from abc import ABCMeta, abstractmethod from Muon.GUI.Common.observer_pattern import Observer class HomeTabSubWidget: __metaclass__ = ABCMeta """ Abstract base class which all sub-widgets must inherit from. This is used to enforce a c...
from tornado import template dockerchef = template.Template(""" FROM {{ basecontainer }} RUN mkdir -p /tmp/chef ADD ./{{ cookbooks }} /tmp/chef/ ADD ./solo.rb /tmp/chef/ ADD ./solo.json /tmp/chef/ RUN ls -l /tmp/chef/ # install chef-solo RUN apt-get install curl -y RUN curl -L https://www.opscode.com/chef/install.sh |...
import unittest from airflow.contrib.hooks.azure_container_volume_hook import AzureContainerVolumeHook from airflow.models import Connection from airflow.utils import db class TestAzureContainerVolumeHook(unittest.TestCase): def test_get_file_volume(self): db.merge_conn( Connection( ...
import sys import os if not os.path.exists('Public'): os.makedirs('Public') if not os.path.exists('External'): os.makedirs('External') allFiles = set() for root, directories, filenames in os.walk('Sources/'): count = len(root.split("/")) - 1 prefix = "" if count > 1: for i in range(...
#!/usr/bin/python import sys import serial from intelhex import IntelHex import time def add8(a, b): return (a + b & 0xFF) page_size = 255 class StaxProg(): def __init__(self, port, speed): port = port speed = speed self.hex = IntelHex() self.port = port self.speed =...
import oauth2 as oauth import cgi import logging import os import httplib2 import urllib import json from datetime import datetime from django.core.serializers import serialize from django.http import HttpResponse, HttpResponseRedirect from django.contrib.auth.models import User from django.contrib.auth import login, ...
# -*- coding: utf-8 -*- import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Changing field 'GrowingPlace.phone' db.alter_column(u'growing_places_growingplace', 'phone', self.gf('dja...
import sys import os from random import shuffle import re def sentenceGrab(subject, directory, firstOccurence): bookshelf = os.listdir(directory) sentences = [] for file in bookshelf: if (file.endswith(".txt")): with open(os.path.join(directory, file), "r") as f: text =...
from openerp.osv import orm, fields class banking_import_line(orm.TransientModel): _inherit = 'banking.import.line' _columns = { 'payment_order_id': fields.many2one( 'payment.order', 'Payment order'), 'transaction_type': fields.selection([ # Add payment order related tr...
""" 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 ...
import os import numpy as np from scipy.stats.mstats import gmean import sklearn.model_selection import paths import labels from datasets import mlb import find_best_threshold np.set_printoptions(threshold=np.nan) np.set_printoptions(suppress=True) def submit_cv_ensemble(ensemble, output_file): thresholds = []...
""" Unittest for creating stock class an its method """ from src.Stock import Stock import unittest class StockTest(unittest.TestCase): """ Test stock functions.""" stock_TEA = Stock("TEA", "Common", 0, 0, 100) stock_POP = Stock("POP", "Common", 8, 0, 100) stock_ALE = Stock("ALE", "Common", 23, 0, 6...
# Build paths inside the project like this: os.path.join(BASE_DIR, ...) from datetime import timedelta import os import sys from django.utils.translation import ugettext_lazy as _ import dj_database_url testing = "test" in sys.argv if os.getenv("DJANGO_ENV") == "prod": # "prod" really just means deployed vs. runn...
import wx import wx.lib.buttons def create(parent): return Frame1(parent) [wxID_FRAME1, wxID_FRAME1CHOICE1, wxID_FRAME1CHOICE10, wxID_FRAME1CHOICE11, wxID_FRAME1CHOICE12, wxID_FRAME1CHOICE13, wxID_FRAME1CHOICE14, wxID_FRAME1CHOICE2, wxID_FRAME1CHOICE3, wxID_FRAME1CHOICE4, wxID_FRAME1CHOICE5, wxID_FRAME1CHOI...
from django.utils.deprecation import MiddlewareMixin from django.core.files.base import ContentFile from django.http import HttpResponseRedirect, HttpResponseGone from datetime import timedelta from django.utils import timezone from .models import ( Snapshot, SnapshotFile, ) class LocalizrSnapshotMiddleWare(M...
#!/usr/bin/env python # -*- coding: utf-8 -*- from runner.koan import * def function(): return "pineapple" def function2(): return "tractor" class Class(object): def method(self): return "parrot" class AboutMethodBindings(Koan): def test_methods_are_bound_to_an_object(self): obj...
import builtins import numpy as np import pytest import pandas as pd from pandas import ( DataFrame, Index, Series, isna, ) import pandas._testing as tm @pytest.mark.parametrize("agg_func", ["any", "all"]) @pytest.mark.parametrize("skipna", [True, False]) @pytest.mark.parametrize( "vals", [ ...
from django import template register = template.Library() @register.tag def get_relation_by_type_list(parser, token): """Gets list of relations from object identified by a content type. Syntax:: {% get_relation_list [content_type_app_label.content_type_model] for [object] as [varname] [direction] ...
# -*- coding: utf-8 -*- ''' integration.loader.globals ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Test Salt's loader regarding globals that it should pack in ''' # Import Python libs from __future__ import absolute_import # Import Salt Testing libs from salttesting.helpers import ensure_in_syspath ensure_in_syspath...
# Made by mtrix import sys from com.l2scoria.gameserver.model.quest import State from com.l2scoria.gameserver.model.quest import QuestState from com.l2scoria.gameserver.model.quest.jython import QuestJython as JQuest qn = "171_ActsOfEvil" BLADE_MOLD,TYRAS_BILL,RANGERS_REPORT1,RANGERS_REPORT2,RANGERS_REPORT3,RANGERS_R...