content
stringlengths
4
20k
import json from testtools.matchers import raises, Not import falcon.testing as testing import falcon class FaultyResource: def on_get(self, req, resp): status = req.get_header('X-Error-Status') title = req.get_header('X-Error-Title') description = req.get_header('X-Error-Description') ...
from . import numbers from math import factorial class CrazyStaticMethodInterceptingMetaclass(type): def __getattr__(self, name): clean_name = name.replace("_", " ") if name.startswith("square_root_of_"): return int(numbers.word_to_number(clean_name[14:]) ** (1/2.0)) if name.s...
import asposewordscloud from asposewordscloud.WordsApi import WordsApi from asposewordscloud.WordsApi import ApiException from asposewordscloud.models import PageSetup import asposestoragecloud from asposestoragecloud.StorageApi import StorageApi from asposestoragecloud.StorageApi import ResponseMessage apiKey = "XX...
import mock import six import heat.api.middleware.fault as fault import heat.api.openstack.v1.build_info as build_info from heat.common import policy from heat.tests.api.openstack_v1 import tools from heat.tests import common @mock.patch.object(policy.Enforcer, 'enforce') class BuildInfoControllerTest(tools.Controll...
#!/usr/bin/python import time import getpass from datetime import datetime import glob import multiprocessing import os import sys import traceback import socket import redis import json import uuid import shutil from subprocess import Popen, PIPE from couchdbkit import * # this is user set BASE_DIR = '/opt/NOW' E...
''' Ultimate Whitecream Copyright (C) 2015 mortael Copyright (C) 2015 Fr33m1nd 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...
""" sentry.models.apikey ~~~~~~~~~~~~~~~~~~~~ :copyright: (c) 2010-2015 by the Sentry Team, see AUTHORS for more details. :license: BSD, see LICENSE for more details. """ from __future__ import absolute_import, print_function import six from bitfield import BitField from django.db import models from django.utils imp...
import datetime import numpy as np import pandas as pd import os import sys from sklearn import model_selection sys.path.insert(0, os.getcwd()) from qml_workdir.classes.config import config from qml.cv import QCV from qml.models import QXgb from qml_workdir.classes.models import qm cv = QCV(qm) X = pd.read_csv(c...
''' config.py ''' import os import yaml from heron.statemgrs.src.python.config import Config as StateMgrConfig STATEMGRS_KEY = "statemgrs" VIZ_URL_FORMAT_KEY = "viz.url.format" class Config(object): """ Responsible for reading the yaml config file and exposing various tracker configs. """ def __init__(se...
__title__ = "make DC to DC converter 3D models" __author__ = "Stefan, based on DIP script" __Comment__ = 'make varistor 3D models exported to STEP and VRML for Kicad StepUP script' ___ver___ = "1.3.3 14/08/2015" # maui import cadquery as cq # maui from Helpers import show from collections import namedtuple import ma...
"""Explicitly ban select functions from being used in src/core/**. Most of these functions have internal versions that should be used instead.""" import os import sys os.chdir(os.path.join(os.path.dirname(sys.argv[0]), '../../..')) # map of banned function signature to allowlist BANNED_EXCEPT = { 'grpc_slice_fr...
#!/usr/bin/env python2 import sys,os,os.path import hashlib def digestfile(filename,chunksize=2**20): with open(filename,'rb') as fo: shaobj=hashlib.sha256() def readchunk(): return fo.read(chunksize) for chunk in iter(readchunk,''): shaobj.update(chunk) return shaobj.hexdigest() def getdigests(dirnam...
from __future__ import unicode_literals from datetime import date import logging from django.conf import settings from django.core.paginator import EmptyPage, PageNotAnInteger, Paginator from django.db import models from django.db.models import Q from django.db.models.signals import pre_save from django.dispatch impo...
from django import forms from search_choices import CLIENT_FIELD_CHOICES from search_choices import CLIENT_ORDER_CHOICES from search_choices import CONSTRAINT_CHOICES import datetime """ displays checkboxes for Client Search """ class ClientForm(forms.Form): client_fields = forms.MultipleChoiceField(required=Fals...
from setuptools import setup, find_packages import os CLASSIFIERS = [ 'Development Status :: 3 - Alpha', 'Environment :: Web Environment', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming L...
from __future__ import absolute_import, division, print_function from collections import OrderedDict from functools import partial from hashlib import md5 from operator import attrgetter import pickle import os import uuid from toolz import merge, groupby, curry, identity from toolz.functoolz import Compose from .co...
""" Support for WeMo switches. For more details about this component, please refer to the documentation at https://home-assistant.io/components/switch.wemo/ """ import logging from datetime import datetime, timedelta from homeassistant.components.switch import SwitchDevice from homeassistant.util import convert from ...
import volatility.obj as obj #---------------------------------------------------------------------- # All Windows #---------------------------------------------------------------------- class VadTraverser(obj.CType): ## The actual type depends on this tag value. tag_map = {'Vadl': '_MMVAD_LONG', ...
#!/usr/bin/env python import polypy import polypy_test import sys import time polypy_test.init() [x, y, z] = [polypy.Variable(name) for name in ['x', 'y', 'z']] polypy.variable_order.set([z, y, x]) # polypy.trace_enable("polynomial") # polypy.trace_enable("coefficient") # polypy.trace_enable("coefficient::sgn") # ...
from pygments.styles import STYLE_MAP style_names = sorted(list(STYLE_MAP.keys())) # Our local modules from trepan.processor.command import base_subcmd as Mbase_subcmd from trepan.lib import complete as Mcomplete class SetStyle(Mbase_subcmd.DebuggerSubcommand): """**set style** [*pygments-style*] Set the pygme...
""" An example demonstrating how to put together a crossfilter app based on the Auto MPG dataset. Demonstrates how to dynamically generate bokeh plots using the HoloViews API and replacing the bokeh plot based on the current widget selections. """ import holoviews as hv from bokeh.layouts import row, widgetbox from bo...
# stdlib from typing import List from typing import Optional from typing import Type # third party from google.protobuf.reflection import GeneratedProtocolMessageType from nacl.signing import VerifyKey # syft relative from ..... import serialize from .....core.common.serde.serializable import bind_protobuf from ........
import numpy from theano.tensor.elemwise import Elemwise from theano import scalar class XlogX(scalar.UnaryScalarOp): """ Compute X * log(X), with special case 0 log(0) = 0. """ @staticmethod def st_impl(x): if x == 0.0: return 0.0 return x * numpy.log(x) def impl...
from django.db import models from threepio import logger from core.models.user import AtmosphereUser, get_default_identity from core.models.identity import Identity from hashlib import md5 class UserProfile(models.Model): user = models.OneToOneField(AtmosphereUser, primary_key=True) # Backend Profile attri...
#!/usr/bin/env python #-*- coding:utf-8 -*- from novaclient import client import os def run(config): loads = (k for k in config if config[k]) for load in loads: func = "load_%s" % load try: loadcall = globals()[func] except KeyError: continue loadcall(co...
""" preprocessor.parse ~~~~~~~~~~~~ This module includes parse functionality """ import re from .utils import * from .defines import Defines, Patterns class ParseResult: urls = None emojis = None smileys = None numbers = None hashtags = None mentions = None reserved_words = None def ...
import unittest try: from unittest import mock except ImportError: import mock # There is some weird conflict with `TestLoader.discover` if `nose.case.Test` # is imported directly. Importing `nose.case` works. from nose import case from nose.suite import ContextSuite from tap.plugin import DummyStream, TAP fr...
""" RPC Controller """ from oslo.config import cfg from glance.common import rpc from glance.common import wsgi import glance.db import glance.openstack.common.log as logging LOG = logging.getLogger(__name__) CONF = cfg.CONF class Controller(rpc.Controller): def __init__(self, raise_exc=False): supe...
import threading from lib.logger import * import time from libnmap.process import NmapProcess from libnmap.parser import NmapParser from lib.settings import homenet, lock class PortScanner(threading.Thread): def __init__(self, threadID): threading.Thread.__init__(self) self.threadID = threadID ...
import traceback import string import os import sys import shutil from FDO import * import unittest class InsertTest(unittest.TestCase): def setUp(self): if not os.path.isdir("InsertTest/SDF"): os.makedirs("InsertTest/SDF") if not os.path.isdir("InsertTest/SQLite"): os.maked...
# -*- coding: utf-8 -*- import unittest import odin from odin.exceptions import ValidationError class Author(odin.Resource): name = odin.StringField() country = odin.StringField(null=True) def clean(self): if self.name == "Bruce" and self.country.startswith("Australia"): raise Validat...
#!/usr/bin/env python # -*- coding: utf8 -*- # ***************************************************************** # ** PTS -- Python Toolkit for working with SKIRT ** # ** © Astronomical Observatory, Ghent University ** # ***************************************************************** ##...
from node_common.queryfunc import * from .models import * def returnHeaders(transs): log.debug('Calculating statistics.') ntranss=transs.count() headers={'COUNT-RADIATIVE': ntranss} if TRANSLIM < ntranss: headers['TRUNCATED'] = '%.1f'%(float(TRANSLIM)/ntranss *100) if ntranss: he...
import time from scipy.spatial.distance import euclidean from fastmc.proto import Slot import numpy as np import math from math import floor import threading import itertools import logging from fastmc.proto import Position import types log = logging.getLogger(__name__) log.addHandler(logging.NullHandler()) class P...
import logging import logging.handlers from oslo_config import cfg from ceilometer import dispatcher OPTS = [ cfg.StrOpt('file_path', help='Name and the location of the file to record ' 'meters.'), cfg.IntOpt('max_bytes', default=0, help='The m...
''' CVS module Status class submodule ''' import logging import subprocess import sys from repoman._portage import portage from portage import os from portage.const import BASH_BINARY from portage.output import red, green from portage import _unicode_encode, _unicode_decode class Status(object): '''Performs status...
from psrc.zone.abstract_mode_split import AbstractModeSplit class mode_split_human_powered_over_all(AbstractModeSplit): """ mode split for manual transportatoin to total trips""" def __init__(self): AbstractModeSplit.__init__(self, path = 'psrc.zone', ...
# -*- coding: utf-8 -*- import pytest import gevent import zerorpc from zask import Zask from zask.ext.zerorpc import * from testutils import random_ipc_endpoint def test_no_middleware_runtime(): app = Zask(__name__) endpoint = random_ipc_endpoint() rpc = ZeroRPC(app) class Srv(rpc.Server): ...
# -*- coding: iso-8859-1 -*- """ MoinMoin - authentication using a remote wiki @copyright: 2005 by Florian Festi, 2007-2008 by MoinMoin:ThomasWaldmann @license: GNU GPL, see COPYING for details. """ import xmlrpclib from MoinMoin import log logging = log.getLogger(__name__) ...
from oslo_serialization import jsonutils from nailgun import consts from nailgun.db.sqlalchemy.models import Cluster from nailgun.db.sqlalchemy.models import NetworkGroup from nailgun.db.sqlalchemy.models import Node from nailgun.test.base import BaseIntegrationTest from nailgun.test.base import fake_tasks from nailgu...
import re from lxml import etree from .base import BikeShareSystem, BikeShareStation from pybikes.utils import PyBikesScraper from pybikes.contrib import TSTCache __all__ = ['Nextbike', 'NextbikeStation'] BASE_URL = 'https://nextbike.net/maps/nextbike-live.xml?domains={domain}' CITY_QUERY = '/markers/country/city[@u...
from wolis import utils from wolis.test_case import WolisTestCase class InstallSubsilverTestCase(WolisTestCase): @utils.restrict_phpbb_version('>=3.1.0') def test_install_subsilver(self): self.login('morpheus', 'morpheus') self.acp_login('morpheus', 'morpheus') url = '/adm/inde...
from e3pipe.root.__ROOT__ import * from e3pipe.root.E3RootObject import E3RootObject from e3pipe.dst.__time__ import E3_TIME_OFFSET class E3H1D(ROOT.TH1D, E3RootObject): """ Wrapper around the ROOT.TH1D object. """ def __init__(self, name, title, xbins, xmin, xmax, **kwargs): """ Constructor. ...
from django.conf.urls.defaults import * from django.contrib import admin from django.contrib.auth.forms import AuthenticationForm admin.autodiscover() handler500 = 'djangotoolbox.errorviews.server_error' urlpatterns = patterns('', (r'^$', 'console.views.index'), (r'^submit/$', 'console.views.submit'), (...
import struct import socket import datetime import random import hashlib import proto class Connection(object): def __init__(self, host, port): self.host = host self.port = port self._sock = socket.create_connection((host, port)) def sendall(self, data): return self._sock.se...
__all__ = ["create", "samefile"] from . import fs import ctypes from ctypes import WinError from ctypes.wintypes import BOOL CreateHardLink = ctypes.windll.kernel32.CreateHardLinkW CreateHardLink.argtypes = [ctypes.c_wchar_p, ctypes.c_wchar_p, ctypes.c_void_p] CreateHardLink.restype = BOOL def create(source, link_nam...
from django.db import models from django.core.urlresolvers import reverse from django.contrib.auth.models import User class Action(object): LIST = 'list' ADD = 'add' EDIT = 'edit' DELETE = 'delete' DETAIL = 'detail' class GenericModel(models.Model): class Meta: abstract = True ...
''' Created on Aug 6, 2012 @author: Gary This module is for reading xml Configuration files. ''' import abc import os import datetime import re import sys import logging from xml.etree.ElementTree import ElementTree import pprint from abc_configuration import abcConfiguration class ConfigurationFileNotFoundError(...
#!/usr/bin/env python3 # -*- coding: UTF-8 -*- import sys import os for path in [os.getcwd(),"SchemaExamples"]: sys.path.insert( 1, path ) #Pickup libs from shipped lib directory import logging logging.basicConfig(level=logging.INFO) # dev_appserver.py --log_level debug . log = logging.getLogger(__name__) from sch...
import json import unittest from unittest import mock from airflow.api.common.experimental.trigger_dag import _trigger_dag from airflow.exceptions import AirflowException from airflow.models import DAG, DagRun from airflow.utils import timezone class TestTriggerDag(unittest.TestCase): @mock.patch('airflow.model...
""" responses.py - Willie Anti-Swearing Module Copyright 2013, Eldon McGuinness http://willie.dftba.net """ # TODO Build a regex to represent the bots name from willie import module import random @module.rule('(?:.*\s)?gamestick(?:s)?.*') def gamestick_response (bot, trigger): responses = [ '%s, how dare you me...
''' Script to update user map on CartoDB For full instructions, see the documentation at https://oppiamobile.readthedocs.org/en/latest/ ''' import time import MySQLdb import urllib import json import argparse, hashlib, subprocess from django.db.models import Sum, Q def run(cartodb_account, cartodb_key, so...
# coding=utf-8 """Define custom response handlers - custom hooks with access to the session object.""" from __future__ import unicode_literals import logging from cloudscraper import CloudScraper from medusa.logger.adapters.style import BraceAdapter from requests.utils import dict_from_cookiejar from six import ...
from tincan.serializable_base import SerializableBase """ .. module:: typed_list :synopsis: A wrapper for a list that ensures the list consists of only one type """ class TypedList(list, SerializableBase): _cls = None def __init__(self, *args, **kwargs): self._check_cls() new_args = [sel...
from skdaccess.framework.data_class import DataFetcherCache, TableWrapper from skdaccess.framework.param_class import * # Standard library imports from collections import OrderedDict import re # 3rd part imports import pandas as pd class DataFetcher(DataFetcherCache): ''' Data Fetcher for Mahali temperature...
""" Handler to serve the DIRAC configuration data """ __RCSID__ = "$Id$" import json from tornado import web, gen from RESTDIRAC.RESTSystem.Base.RESTHandler import WErr, RESTHandler from DIRAC import gConfig class ConfigurationHandler( RESTHandler ): ROUTE = "/config" @web.asynchronous @gen.engine def get...
import webapp2, filestore from templates import get_template from models.settings import Settings from models.userimage import UserImage from models.timezones import timezones from models.migratetask import MigrateTask class SettingsHandler(webapp2.RequestHandler): def get(self): #Check whether the migration is do...
# -*- coding: utf-8 -*- import attr from navmazing import NavigateToAttribute from navmazing import NavigateToSibling from widgetastic.exceptions import MoveTargetOutOfBoundsException from widgetastic.widget import View from widgetastic_patternfly import BootstrapNav from widgetastic_patternfly import BreadCrumb from w...
import re import os from django.conf import settings FILLERS = set(['uh','um','okay','yes','yeah','oh','heh','yknow','um-huh','uh-uh','uh-huh','uh-hum','mm-hmm']) def fetch_buckeye_resource(uri): path = os.path.join(settings.BUCKEYE_ROOT,uri) return path def fetch_media_resource(uri): path = os.path.j...
#!/usr/bin/env python # encoding: utf-8 from collections import namedtuple from datetime import timedelta from elevator_simulation.models import IdentMixin from elevator_simulation.models.building import Floor Event = namedtuple("Event", "start_time location description") class Schedule(object): """Class to mo...
#!/usr/bin/env python # -*- coding: utf-8 -*- # vim: ai ts=4 sts=4 et sw=4 nu from __future__ import (unicode_literals, absolute_import, division, print_function) import logging import copy import datetime from snisi_core.models.Periods import MonthPeriod from snisi_core.models.ReportingPeriod...
"""End-To-End Memory Networks. The implementation is based on http://arxiv.org/abs/1503.08895 [1] """ from __future__ import absolute_import from __future__ import division # from tensorflow.nn.rnn_cell import GRUCell, MultiRNNCell from six.moves import range from pprint import pprint import numpy as np import tensor...
from graphql.core.language.location import SourceLocation from graphql.core.validation.rules import NoUnusedFragments from utils import expect_passes_rule, expect_fails_rule def unused_fragment(fragment_name, line, column): return { 'message': NoUnusedFragments.unused_fragment_message(fragment_name), ...
import re import requests from .util import Util from .version import VERSION from .api_config import ApiConfig from quandl.errors.quandl_error import ( QuandlError, LimitExceededError, InternalServerError, AuthenticationError, ForbiddenError, InvalidRequestError, NotFoundError, ServiceUnavailableError) ...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models from django.conf import settings import shoop.core.fields import shoop.front.models.stored_basket class Migration(migrations.Migration): dependencies = [ ('shoop_front', '0002_tax_price_currency'), ...
''' This is the GNU Radio DPD module. Place your Python package description here (python/__init__.py). ''' # import swig generated symbols into the dpd namespace try: # this might fail if the module is python-only from dpd_swig import * except ImportError: pass # import any pure python here #
from __future__ import (absolute_import, division, print_function) __metaclass__ = type import os import json from units.modules.utils import AnsibleExitJson, AnsibleFailJson, ModuleTestCase from units.modules.utils import set_module_args as _set_module_args def set_module_args(args, ignore_provider=None): if '...
import sys import unittest import numpy as np import quantities as pq from numpy.testing import assert_array_almost_equal from elephant.parallel import SingleProcess, ProcessPoolExecutor from elephant.spike_train_generation import homogeneous_poisson_process from elephant.statistics import mean_firing_rate python_ve...
import unittest2 from .frequencydimension import \ FrequencyDimensionEncoder, FrequencyDimensionDecoder, \ LinearScaleEncoderDecoder, GeometricScaleEncoderDecoder, \ ExplicitScaleEncoderDecoder, ExplicitFrequencyDimensionEncoder, \ ExplicitFrequencyDimensionDecoder from zounds.spectral import \ Freq...
#!/usr/bin/python3 from telegram.ext import Updater; from telegram.ext import CommandHandler as CH; from telegram.ext import MessageHandler,Filters; import listapiropos as LP; import telegram import botsettings as BS; import sys import emoji from telegram import InlineQueryResultArticle, InputTextMessageContent from t...
from distutils.core import setup import py2exe setup(windows = [{"script": "lexcess.pyw","icon_resources": [(1, "lexcessicon.ico")]}], author="Garrison Benson", author_email="<EMAIL>", url="http://www.bensonbasement.com/games/lexcess/", data_files=[('.', ["buzzer.wav", ...
#!/usr/bin/python import optparse import sys import os # Install the Python unittest2 package before you run this script. import unittest2 USAGE = """%prog SDK_PATH TEST_PATH Run unit tests for App Engine apps. SDK_PATH Path to the SDK installation TEST_PATH Path to package containing test modules""" def main(...
from django.utils.translation import ugettext_lazy as _ from pygments import highlight from pygments import styles from pygments.lexers import get_lexer_by_name from pygments.formatters import HtmlFormatter from cms.plugin_base import CMSPluginBase from cms.plugin_pool import plugin_pool from models import P...
#!/usr/bin/env python import pygtk pygtk.require('2.0') import gtk import gobject import socket import re import urllib from threading import Timer from client import LiqClient from widgets import View def strbool(b): if b: return "true" else: return "false" class LiqMix(gtk.HBox): def __init__(sel...
#! /usr/bin/env python # ______________________________________________________________________ '''test_forloop Test the Numba compiler on a simple for loop over an iterable object. ''' # ______________________________________________________________________ import unittest import numba from numba import * from numb...
""" Downloads Go binaries from Google Cloud Storage and extracts them to INSTALL_DIR, updating INSTALL_DIR/VERSION stamp file with current version. Does nothing if INSTALL_DIR/VERSION is already up to date. """ import os import shutil import subprocess import sys import tarfile # Path constants. (All of these should ...
class UBCValue: """Represents a User Beancounter value""" # Internal value value = None # The maximum value allowed, the default is an 8-byte integer. This is the # largest number that OpenVZ can accept AFAIK cap = 9223372036854775807 def __init__(self, value): if not isinstance(va...
# # Solution to Project Euler problem 95 # Philippe Legault # # https://github.com/Bathlamos/Project-Euler-Solutions from itertools import permutations def compute(): limit = 1000000 proper_divisors = [set() for i in range(0, limit + 1)] proper_divisors[1] = set() num = 2 multiplied = 2 * num while num <= l...
# -*- coding: utf-8 -*- """ This module tests the barcodeplot visualizer module. Run it like so: coquery$ python -m test.vis.test_barcodeplot """ import unittest import pandas as pd import seaborn as sns import scipy.stats as st import itertools import argparse import matplotlib.pyplot as plt from coquery.coquery ...
from django.conf import settings from django.contrib.auth.decorators import login_required from django.contrib.contenttypes.models import ContentType from django.http import ( Http404, HttpResponse, HttpResponseBadRequest, HttpResponseNotAllowed, HttpResponseRedirect, ) from django.shortcuts import get_object_o...
"""Setuptools entry point.""" import os import codecs from setuptools import setup, find_packages from humilis_kinesis_proxy import __version__, __author__ dirname = os.path.dirname(__file__) description = "Humilis plug-in to deploy a Lambda kinesis_proxy" try: import pypandoc long_description = pypandoc.co...
import tensorflow as tf # neural network for function approximation import gym # environment import numpy as np # matrix operation and math functions from gym import wrappers import gym_morph # customized environment for cart-pole import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt import time star...
""" Responsible for generating the decoder based on parsed table representations. """ from __future__ import print_function import dgen_opt def generate_decoder(tables, out): """Entry point to the decoder. Args: tables: list of Table objects to process. out: a COutput object to write to. "...
import sys import os def splitall(loc): """ Return a list of the path components in loc. (Used by relpath_). The first item in the list will be either ``os.curdir``, ``os.pardir``, empty, or the root directory of loc (for example, ``/`` or ``C:\\). The other items in the list will be strings. ...
from unicodedata import bidirectional from django.utils.encoding import force_unicode _strong_types = ("L", "R", "AL") _rtl_types = ("R", "AL") def get_base_direction(text): """Find the base direction of a text string according to the first character with strong bidi type. Returns ``0`` for LTR, ``1``...
# -*- coding: utf-8 -*- import re import urlparse from core import httptools from core import scrapertools from core import servertools from core import tmdb from core.item import Item from platformcode import config, logger host = 'http://cinefoxtv.net/' headers = [['User-Agent', 'Mozilla/5.0 (Windows NT 10.0; WOW6...
from pants.testutil.pants_run_integration_test import PantsRunIntegrationTest class BackendIndependenceTest(PantsRunIntegrationTest): """Verifies that this backend works with no other backends present.""" @classmethod def hermetic(cls): return True def test_independent_test_run(self): ...
import json import os from django.db.models import Q from django.shortcuts import render from django.http import HttpResponse from django.contrib.auth.decorators import login_required from django.template import loader import weasyprint from datetime import datetime from .models import Event, Person, RoleAssignment, me...
from multiprocessing import Process, Queue, current_process, freeze_support from subprocess import call import shlex class ParallelTasks(): def __init__(self): pass def execute(self, cmd): """ Executes system call with proper arguments""" args = shlex.split(cmd) res = call(...
import json class TagsEndpointsMixin(object): """For endpoints in ``/tags/``.""" def tag_info(self, tag): """ Get tag info :param tag: :return: """ endpoint = 'tags/{tag!s}/info/'.format(**{'tag': tag}) res = self._call_api(endpoint) return res...
#!/usr/bin/env python import axreader import interfaces import common import groundComms ################################# Unit Testing ################################# if __name__ == "__main__": LOG_PATH = "/home/pi/axlisten.log" i = interfaces.interfaces() i.openbeacon() gc = groundComms.gro...
from collections import defaultdict from datetime import datetime import json from unidecode import unidecode from flask import abort from sqlalchemy import func as F from app import db LIMITS = False class QuestionStatus(db.Model): user_id = db.Column(db.Integer, db.ForeignKey('user.id'), primary_key=True) ...
# -*- coding: utf-8 -*- import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models from django.contrib.auth import get_user_model User = get_user_model() class Migration(SchemaMigration): def forwards(self, orm): # Adding field 'Container.json' db.a...
""" Django settings for chatdemo project. For more information on this file, see https://docs.djangoproject.com/en/1.6/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.6/ref/settings/ """ # Build paths inside the project like this: os.path.join(BASE_DIR, ...) i...
from django.db import models from django.contrib.contenttypes import generic from django.contrib.contenttypes.models import ContentType from django_fields import fields as helper_fields from dynamic_rules import rule_registry class RuleManager(models.Manager): def get_by_secondary_object(self, obj): co...
import numpy as np import warnings from composite_materials import * from ply_stack import * # beware the size of machine epsilon.... np.finfo(float).eps class LaminateProperties(object): # Superclass containing all the useful overides and the basic constructor def __init__(self, lam=None): # Constructor wants a...
import sys import matplotlib.pyplot as plt import csv import os if len(sys.argv) < 4 or not sys.argv[1] in ['points', 'result']: print "Usage: plot-clusters.py (points|result) <src-file> <pdf-file-prefix>" sys.exit(1) inFile = sys.argv[1] inFile = sys.argv[2] outFilePx = sys.argv[3] inFileName = os.path.splitext...
from behave import given, when, then # Session Start @given("I sent a Session Start request") @when("I send a Session Start request with no Auth Request ID") def send_service_session_end_request(context): current_service = context.entity_manager.get_current_directory_service() user_identifier = context.entit...
import roan from django.db import models class Palestrante(models.Model): nome = models.CharField(max_length=100) slug = models.SlugField(max_length=100, unique=True) headline = models.CharField(max_length=60) minicurriculo = models.CharField(max_length=1000) twitter = models.CharField(max_length...
import random import struct import sys from socket import socket as sock, AF_INET, SOCK_RAW, IPPROTO_ICMP, SOL_IP, IP_HDRINCL, socket from util.exceptions import TransportMethodException class Handler: def __init__(self, transport_class): self.transport = transport_class # def receive_connection(se...