code
stringlengths
1
199k
import baboon import collections import unittest class BaboonsTest(unittest.TestCase): def setUp(self): self.orDict = collections.OrderedDict() baboon.setup_keys(self.orDict) def test_baboon1_should_be_poly(self): self.assertEqual(self.orDict["nrOfPolyType1"], 0) baboon.accumulat...
__author__ = 'Hildo Guillardi Júnior' __webpage__ = 'https://github.com/hildogjr/' __company__ = 'University of Campinas - Brazil' import json import requests import re import sys import os import copy from collections import OrderedDict if sys.version_info[0] < 3: from urllib import quote_plus else: from urlli...
from __future__ import division import time import cython_random as random import preflop_equity from utility import MathUtils from game import GameData from hand_simulator import HandSimulator from bet_sizing import BetSizeCalculator from fear import Fear from timer import Timer class Brain(BetSizeCalculator, Fear): ...
""" __MT_post__NamedElement.py_____________________________________________________ Automatically generated AToM3 syntactic object (DO NOT MODIFY DIRECTLY) Author: gehan Modified: Sun Feb 15 10:31:26 2015 _______________________________________________________________________________ """ from ASGNode import * from ATOM...
from mpf.tests.MpfTestCase import MpfTestCase from mpfmc.widgets.display import DisplayWidget from mpfmc.uix.widget import WidgetContainer MYPY = False if MYPY: # pragma: no cover from mpfmc.uix.slide import Slide # pylint: disable-msg=cyclic-import,unused-import class MpfSlideTestCase(MpfTestCase): def...
class A(): def __init__(self, limit): self.limit = limit def print(self): print(self.limit) class B(A): def __init__(self, limit): super().__init__(limit=limit) class C(B): pass a = A(1) a.print() b = B(2) b.print() c = C(10) c.print()
from django.views import generic from django.core.urlresolvers import reverse_lazy, reverse from django.shortcuts import get_list_or_404, get_object_or_404 from django.http.response import HttpResponseRedirect from django.contrib import messages from django.utils.html import mark_safe from ...apps.donate.models import ...
import unittest from monty.fnmatch import WildCard class FuncTest(unittest.TestCase): def test_match(self): wc = WildCard("*.pdf") self.assertTrue(wc.match("A.pdf")) self.assertFalse(wc.match("A.pdg")) if __name__ == "__main__": unittest.main()
from __future__ import unicode_literals from django.db import models, migrations import django.db.models.deletion import django.utils.timezone from django.conf import settings class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operati...
import argparse import io import requests import subprocess import sys DEFAULT_GLOBAL_FAUCET = 'https://signetfaucet.com/claim' DEFAULT_GLOBAL_CAPTCHA = 'https://signetfaucet.com/captcha' GLOBAL_FIRST_BLOCK_HASH = '00000086d6b2636cb2a392d45edc4ec544a10024d30141c9adf4bfd9de533b53' BASE = 0x2800 BIT_PER_PIXEL = [ [0x...
from . import Operation, INestedOperation from ..objects.memory import RegObj class IFConditionOp(Operation, INestedOperation): def __init__(self): super().__init__() self._condmemobj = None self._oplisttrue = None self._oplistfalse = None self._choosedreg = [] def SetOpL...
from cocos import collision_model as cm import constants import entity import ai import logging import game class npc(entity.WorldEntity): ai_type = ai.BasicEnemyAi etype = "enemy" name = "npc" mask_collision = 0b011 mask_event = 0b010 attack_damage = 13 attack_speed = 1.0 attack_cooldow...
from __future__ import print_function import sys import select import logging import pkg_resources from marrow.script import describe from marrow.script.core import ExitException from web.command import release __all__ = ['ScriptCore'] class ScriptCore(object): """Extensible command line script dispatcher for the WebC...
from django.shortcuts import render from django.views.generic import View, ListView, DetailView from .models import Event, Section from endless_pagination.views import AjaxListView class EventsList(AjaxListView): model = Event # queryset = Event.objects.filter(is_publish=True) queryset = Event.objects.all()...
import json import os from pathlib import Path import pytest from dynaconf import default_settings from dynaconf import LazySettings from dynaconf.cli import EXTS from dynaconf.cli import main from dynaconf.cli import read_file_in_root_directory from dynaconf.cli import WRITERS from dynaconf.utils.files import read_fil...
from . import base, psycopg2, pg8000, pypostgresql, zxjdbc, psycopg2cffi base.dialect = psycopg2.dialect from .base import \ INTEGER, BIGINT, SMALLINT, VARCHAR, CHAR, TEXT, NUMERIC, FLOAT, REAL, \ INET, CIDR, UUID, BIT, MACADDR, OID, DOUBLE_PRECISION, TIMESTAMP, TIME, \ DATE, BYTEA, BOOLEAN, INTERVAL, ENUM,...
from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('markets', '0005_a...
"""__init__.py - Various utilities to use throughout the system.""" def serialize_sqla(data): """Serialiation function to serialize any dicts or lists containing sqlalchemy objects. This is needed for conversion to JSON format.""" # If has to_dict this is asumed working and it is used. if hasattr(data, ...
from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.by import By from test_case_02_createVideoB import * class Test_case_03_toolsAB(Test_StartEnd): # 开播视频 def test_03_startVideo(self): '''开始直播''' ...
import json from datetime import datetime, timedelta import webapp2 from google.appengine.api import urlfetch import urllib from apiclient import discovery from google.appengine.ext import deferred from oauth2client.contrib.appengine import AppAssertionCredentials from cfg import * def post_log(message, vote, user_name...
from handler import Handler from models import Blogs class NewPost(Handler): """Creates new post and stores in GDS""" def get(self): self.user_page("blogsubmit.html", "/signup", auth_user=self.user) def post(self): # Check user's auth status if self.user: title = self.req...
""" compile comamnds functions """ import argparse import os import subprocess import re import collections import sys import json import typing import statistics import itertools COMPILE_COMMANDS_FILE_NAME = 'compile_commands.json' class CompileCommand: def __init__(self, directory: str, command: str): sel...
""" Daniel Wilson tutorial3.py """ from ggame import App, RectangleAsset, ImageAsset, SoundAsset from ggame import LineStyle, Color, Sprite, Sound SCREEN_WIDTH = 640 SCREEN_HEIGHT = 480 green = Color(0x00ff00, 1) black = Color(0, 1) noline = LineStyle(0, black) bg_asset = RectangleAsset(SCREEN_WIDTH, SCREEN_HEIGHT, nol...
import time import numpy import os import threading_decorators as ThD import matplotlib.pyplot as plt import magdynlab.instruments import magdynlab.data_types @ThD.gui_safe def Plot_Pw_vs_f(Data): f = plt.figure('Frequency Spectrum', (5, 4)) if not(f.axes): plt.subplot() ax = f.axes[0] if not(ax...
""" Data model and data access methods for Candles. """ import pytz from core.models.instruments import Instrument from django.db import models class Candle(models.Model): """ Candle data model. """ # pylint: disable=too-many-instance-attributes instrument = models.ForeignKey(Instrument, on_delete=model...
from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('core', '0026_auto_20150416_0202'), ] operations = [ migrations.AlterField( model_name='company2company', name='proof', ...
""" Test world metrics + world metrics handlers against dummy conversations. """ import unittest from parlai.core.tod.tod_core import ( STANDARD_API_NAME_SLOT, STANDARD_REQUIRED_KEY, STANDARD_OPTIONAL_KEY, TodStructuredRound, TodStructuredEpisode, TodAgentType, TOD_AGENT_TYPE_TO_PREFIX, ) fr...
"""Utilities for the ``media_library`` app.""" import re VIMEO_PATTERN = re.compile('(?:https?://)?(?:www.)?(vimeo)(?:pro)?.com/(?:.*/)?(\d+)') # NOQA YOUTUBE_PATTERN = re.compile( '(?:https?://)?(?:(?:www\.)?(youtube)(?:\.\w{2,3})+/watch\?.*v=([a-zA-Z0-9_-]+)&?.*|(youtu\.be)/([a-zA-Z0-9_-]+))' # NOQA ) VIDEO_PAT...
"""sctid URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.8/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-based ...
from twilio.twiml.voice_response import Client, Dial, Number, VoiceResponse response = VoiceResponse() dial = Dial(caller_id='+1888XXXXXXX') dial.number('858-987-6543') dial.client('joey') dial.client('charlie') response.append(dial) print(response)
import logging from functools import partial import maya.OpenMaya as api import maya.cmds as cmds import pymel.core as pm import pymetanode as meta from .rigs import isRig LOG = logging.getLogger(__name__) class Event(list): """ A list of callable objects. Calling an Event will cause a call to each item in ...
import unittest """ Given a binary tree, find the vertical sum of nodes that are in same vertical line. Print all sums through different vertical lines. """ """ Approach: 1. A simple way is to calculate horizontal distance of every node in the tree. 2. If horizontal distance of root is hd, the for root.left it is hd-1 ...
from aiohttp import web app = web.Application() if True: # `app.add_routes` with list async def foo(request): # $ requestHandler return web.Response(text="foo") # $ HttpResponse async def foo2(request): # $ requestHandler return web.Response(text="foo2") # $ HttpResponse async def foo3...
import rospy from sensor_msgs.msg import Imu from std_msgs.msg import Float64 from std_msgs.msg import Bool from rospy_tutorials.msg import Floats import RTIMU import sys import os.path import math import time import datetime sys.path.append('.') displayIMU = True staticPressure = 1012.0 def low_pass(curr, prev, alpha)...
import os from slackclient import SlackClient BOT_NAME='zerobot' slack_client=SlackClient(os.environ.get('SLACK_BOT_TOKEN')) if __name__ == "__main__": api_call = slack_client.api_call("users.list") if api_call.get('ok'): # retrieve all users so we can find our bot users = api_call.get('members'...
import argh from argh import arg import os, shutil, glob from subprocess import check_call @arg("mothur_path", type=os.path.abspath, help="Path to Mothur binary") @arg("pcr_target_fasta",type=os.path.abspath, help="Path to multi-fasta that contains PCR target reference sequence (e.g. ecoli)") @arg("pcr_target_i...
"""Django DDP utils for DDP messaging.""" import collections from django.core.serializers import get_serializer _SERIALIZER = None def obj_change_as_msg(obj, msg): """Generate a DDP msg for obj with specified msg type.""" global _SERIALIZER if _SERIALIZER is None: _SERIALIZER = get_serializer('ddp')...
"""Agilent devices """ __drivers__ = {'HEWLETT-PACKARD 34401A' : 'agilent.agilent34410A.Agilent34410A', 'Agilent Technologies 34410A' : 'agilent.agilent34410A.Agilent34410A', #'HEWLETT-PACKARD E3631A' : 'agilent.agilentE3641A', 'Agilent Technologies 33250A' : 'agilent.agilent33250A.Agilent...
"""Bitcoin test framework primitive and message structures CBlock, CTransaction, CBlockHeader, CTxIn, CTxOut, etc....: data structures that should map to corresponding structures in bitcoin/primitives msg_block, msg_tx, msg_headers, etc.: data structures that represent network messages ser_*, deser_*: funct...
import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "gamecraft.settings_heroku_development") from django.core.management import execute_from_command_line execute_from_command_line(sys.argv)
import pytest import praw from app import reddit, scraper from app.models import Submission, Comment def get_and_parse_reddit_submission(submission_id): reddit_submission = reddit.get_submission(submission_id=submission_id) info, comments = scraper.parse_submission(reddit_submission, Submission) return dict...
from __future__ import division, print_function, unicode_literals import numpy as np from psy import sem, data def test_sem(): dat = data['ex5.11.dat'] beta = np.array([ [0, 0], [1, 0] ]) gamma = np.array([ [1, 1], [0, 0] ]) x = [0, 1, 2, 3, 4, 5] lam_x = np.a...
from __future__ import print_function, unicode_literals import os from setuptools import find_packages, setup def read(fname): with open(os.path.abspath(os.path.join(__file__, os.pardir, fname)), 'rb') as fid: return fid.read().decode('utf-8') authors = read('AUTHORS.rst') history = read('HISTORY.rst').repl...
from twisted.internet.protocol import Protocol, ReconnectingClientFactory from twisted.protocols.basic import LineOnlyReceiver from crow2 import hook, log from crow2.lib import config from crow2.events.hook import Hook from crow2.events.hooktree import InstanceHook, HookMultiplexer, CommandHook example_connection = { ...
"""Implementation of adduser manage.py command.""" from __future__ import (absolute_import, division, print_function, unicode_literals) import getpass from django.core.management import base from django.contrib.auth import models class Command(base.BaseCommand): """Add a normal user to the s...
from Crypto.Cipher import AES import base64 import os BLOCK_SIZE = 32 PADDING = b'{' pad = lambda s: s + (BLOCK_SIZE - len(s) % BLOCK_SIZE) * PADDING EncodeAES = lambda c, s: base64.b64encode(c.encrypt(pad(s))) DecodeAES = lambda c, e: c.decrypt(base64.b64decode(e)).rstrip(PADDING) def encrypt_token(secret, token): ...
import io from setuptools import setup with io.open('README.md', encoding='utf-8') as f: README = f.read() setup( name='hiss', version='0.0.1', url='https://github.com/underyx/hiss', author='Bence Nagy', author_email='bence@underyx.me', maintainer='Bence Nagy', maintainer_email='bence@un...
import sys import os from glob import glob from collections import Counter import MeCab def main(): """ """ input_dir = sys.argv[1] tagger = MeCab.Tagger('') tagger.parse('') frequency = Counter() count_processed = 0 for path in glob(os.path.join(input_dir, '*', 'wiki_*')): print...
import torch import torch.nn as nn import numpy as np import gpytorch class GaussianMixtureTorch(nn.Module): def __init__(self, n_components, n_iter=5, covariance_type='diag', covariance_init=1.0, reg_covar=1e-4): """ Initializes a Gaussian mixture model with n_clusters. Arg...
import cherrypy from cherrypy.process import wspbus, plugins from sqlalchemy.orm import scoped_session, sessionmaker from sqlalchemy import create_engine class SATool(cherrypy.Tool): def __init__(self, dburi): cherrypy.Tool.__init__(self, 'on_start_resource', self.bind_session, priority=10) self.dbu...
BASES = ['A', 'C', 'G', 'T'] class InvalidStrand(Exception): pass def _check_input(strand_str): """ Validate the input string is a valid strand """ if isinstance(strand_str, str) == False: raise InvalidStrand('Wrong type, must be a str') for base in strand_str: if base.upper() not in BAS...
import os from unittest import mock from tornado.testing import AsyncTestCase, gen_test from tornado_sqlalchemy import as_future, set_max_workers from ._common import db, User, mysql_url set_max_workers(10) os.environ['ASYNC_TEST_TIMEOUT'] = '100' class ConcurrencyTestCase(AsyncTestCase): session_count = 10 def...
import os, unittest, subprocess, re, signal, time import nrepl from collections import OrderedDict from nrepl.bencode import encode, decode import sys PY2 = sys.version_info[0] == 2 if not PY2: port_type = bytes else: port_type = () class BencodeTest (unittest.TestCase): def test_encoding (self): # ...
import os import subprocess from typing import Optional, Set, Type from irctest.basecontrollers import ( BaseServerController, DirectoryBasedController, NotImplementedByController, ) from irctest.cases import BaseServerTestCase TEMPLATE_CONFIG = """ clients: # ping_frequency - client ping frequency ping...
from random import randint from django.urls import reverse from conf_site.proposals.tests.factories import ( ProposalFactory, ProposalKindFactory, ) from conf_site.reviews.tests.test_proposal_list_view import ( ProposalListViewTestCase, ) class ProposalKindListViewTestCase(ProposalListViewTestCase): rev...
import smtplib def main(): hostname = 'smtp.gmail.com' port = 587 username = 'jlyoung.gmail.test@gmail.com' password = 'testpassword' sender = 'jlyoung.gmail.test@gmail.com' receivers = ['jlyoung.receiver.addr@stackoverflowexample.com'] message = '''From: J.L. Young <jlyoung.gmail.test@gmail.com> To: JLY Receive...
from implementations import Implementation from sklearn import linear_model import matplotlib.pyplot as plt, mpld3 class LinearRegression(Implementation): """A class for linear regression""" def __init__(self, data): self.name = 'linear-regression' self.X = [row[:-1] for row in data] sel...
from django.db import models from django.contrib.auth.models import User from django.core.urlresolvers import reverse from django.utils.crypto import get_random_string from django.utils.html import format_html from django.utils.functional import cached_property class Elu(models.Model): GENDER_CHOICES = ( ('...
from __future__ import print_function, division, absolute_import, unicode_literals from xml.etree import ElementTree as ET from swid_generator.signature_template import SIGNATURE from swid_generator.package_info import PackageInfo from .utils import create_unique_id, create_software_id, create_system_id from .content_c...
''' This script is created for transfer source to py ''' import os 'transfer the qrc resource to py' os.system("pyrcc4 -o ../src/qrc_app.py ../src/app.qrc")
from __future__ import print_function, division import itertools from copy import deepcopy from collections import OrderedDict from warnings import warn import pickle import nilmtk import pandas as pd import numpy as np from hmmlearn import hmm from nilmtk.feature_detectors import cluster from nilmtk.disaggregate impor...
''' This script takes two bowtie outputs, which were produces by searching exactly the same reads against two slightly different genomes. The bowtie parameters used should return a maximum of one location per read, with a maximum of 2 errors (--best --strata -m 1 -v 2) Here are the rules: 1) If neither matched, skip 2...
from setuptools import setup, find_packages setup(name='BIOMD0000000081', version=20140916, description='BIOMD0000000081 from BioModels', url='http://www.ebi.ac.uk/biomodels-main/BIOMD0000000081', maintainer='Stanley Gu', maintainer_url='stanleygu@gmail.com', packages=find_packages()...
import sys from thlib.side.Qt import QtWidgets as QtGui from thlib.side.Qt import QtGui as Qt4Gui from thlib.side.Qt import QtCore from thlib.environment import env_mode, env_inst import thlib.global_functions as gf import thlib.tactic_classes as tc import thlib.ui_classes.ui_main_classes as ui_main_classes groups = ['...
from contextlib import closing import errno import fcntl import hashlib import os import subprocess import tempfile import virtualenv import zipfile def make_user_tmpdir(system_tmp=None): """Create user specific temporary directory """ if system_tmp is None: system_tmp = os.environ.get('TMPDIR', '/t...
import os import eva import eva.base.adapter import eva.job import eva.exceptions import eva.template import productstatus.api class FimexAdapter(eva.base.adapter.BaseAdapter): """ This adapter is a generic interface to FIMEX, that will accept virtually any parameter known to FIMEX. For flexibility, thi...
import time, os, itertools import matplotlib.pyplot as plt import numpy as np import sys sys.path.append(os.getcwd()) import superpixel_analysis as sup import util_plot from skimage import io import scipy.io from scipy.ndimage import center_of_mass, filters, gaussian_filter from sklearn.decomposition import TruncatedSV...
import os import sys import emotion xml_config = """ <config> <controller class="mockup"> <axis name="axis0"> <velocity value="100"/> </axis> </controller> </config> """ emotion.load_cfg_fromstring(xml_config) my_axis = emotion.get_axis("axis0") print my_axis.position() my_axis.move(42) print my_axis.po...
import os, logging, MySQLdb, mutagen.id3, sys, time, pygame mysql_username = 'sploshify' mysql_password = 'sploshify1' mysql_host = 'localhost' mysql_db = 'sploshify' def main(): mysql_connect_object = MySQLdb.connect(host=mysql_host, user=mysql_username, passwd=mysql_password, db=mysql_db) mysql_connect_object...
from unittest import TestCase from nav.web.networkexplorer import search from nav.web.networkexplorer.forms import NetworkSearchForm from nav.web.networkexplorer.views import ( IndexView, RouterJSONView, SearchView, ) from django.db import transaction from django.test.client import RequestFactory class Netw...
from gamera.plugin import * from gamera.args import NoneDefault import _geometry try: from gamera.core import RGBPixel except: def RGBPixel(*args): pass class voronoi_from_labeled_image(PluginFunction): u""" Computes the area Voronoi tesselation from an image containing labeled Cc's. In the returned onebi...
""" wp-login bruteforcer """ from os import path import argparse import requests PARSER = argparse.ArgumentParser(description="wp-login bruteforcer") PARSER.add_argument("--url", dest="URL", help="full link to wp-login.php", required=True) PARSER.add_argument("--user", dest="USER", default="Administ...
__author__ = 'roman' from django import forms from django.utils.translation import ugettext_lazy as _ from . import models class CardNumberField(forms.CharField): def clean(self, value): value = super(CardNumberField, self).clean(value) return ''.join(value.split('-')) class CardNumberForm(forms.For...
import math from cornice import Service from pyramid.security import has_permission from sqlalchemy.sql import or_ from bodhi import log from bodhi.exceptions import BodhiException, LockedUpdateException from bodhi.models import Update, Build, Bug, CVE, Package, UpdateRequest import bodhi.schemas import bodhi.security ...
import hashlib from exception import * from Crypto.Cipher import AES from Crypto.Hash import SHA512 from Crypto import Random def enc(key, plain): """ Encrpt plain text by key. key is an hash value of account-manager user passwd. plain is text to be enc. """ if key is None: raise EmptyKey if plain is None: ...
""" Calculate the total state of the books """ from bluechips import model from bluechips.model import meta from bluechips.model.types import Currency import sqlalchemy class DirtyBooks(Exception): """ If the books don't work out, raise this """ pass def debts(): # In this scheme, negative numbers r...
import django import os import sys if django.VERSION < (1,8): from django.db.backends import BaseDatabaseClient else: from django.db.backends.base.client import BaseDatabaseClient class DatabaseClient(BaseDatabaseClient): executable_name = 'mysql' def runshell(self): settings_dict = self.connect...
import minecraftsession mcsession = minecraftsession.MinecraftSession() if not mcsession.login('email', 'password', 'something random'): print 'Wrong email or password' if not mcsession.checkSession(): print 'Invalid session information' if not mcsession.checkSession('asdfasdf'): print 'Invalid session informatio...
import wave, os from mien.math.array import ravel, Int16 from wx import Sound def array2wav(a, sampr, filename): wav=wave.open(filename, "w") wav.setparams((a.shape[1],2, sampr, a.shape[0], 'NONE', 'not compressed')) scalefac=max(50, max(abs(ravel(a)))) a=(a/scalefac)*32767 a=a.astype(Int16) wav.writeframes(a.tos...
""" repl --- MIT Scheme and Standard ML REPL ======================================== File contains plugin functionality implementation """ import os import os.path from PyQt4.QtCore import pyqtSignal, QEvent, QObject, Qt, QTimer from PyQt4.QtGui import QFileDialog, QFont, QIcon, QMessageBox, QWidget from PyQt4 import ...
from enthought.pyface.workbench.i_editor import MEditor class Editor(MEditor): """ The toolkit specific implementation of an Editor. See the IEditor interface for the API documentation. """ ########################################################################### # 'IWorkbenchPart' interface. ...
'''CTS: Cluster Testing System: CIB generator ''' __copyright__=''' Author: Andrew Beekhof <abeekhof@suse.de> Copyright (C) 2008 Andrew Beekhof ''' from UserDict import UserDict import sys, time, types, syslog, os, struct, string, signal, traceback, warnings, socket from cts.CTSvars import * from cts.CTS import Clu...
from flask import jsonify from pymongo import MongoClient client = MongoClient() db = client.primer coll = db.dataset def data(): print "Innerds of data" cursor = coll.find({},{ '_id':0 }) result = {} i = 0 for c in cursor: result[str(i)]=c i+=1 print result return jsonify(**...
TYPE_VSERVER = 1 TYPE_RULE = 1 << 2 LIST = [ {'name': 'CMS', 'title': N_('CMS'), 'descr': N_('Content Management Systems'), 'list': [ {'name': 'concrete5', 'title': N_('Concrete 5'), 'descr': N_('The CMS made for Marketing, but built for Geeks.'), ...
import os import sys import urllib import urllib2 import json rootdir = os.path.dirname(os.path.abspath(__file__)) CONFFILE = rootdir + '/config.json' TWITTER_REALM = 'Twitter API' SEARCH_URL = 'http://search.twitter.com/search.json' RETWEET_URL = 'http://api.twitter.com/1/statuses/retweet/' # + 'id.json' config = json...
try: import OpenGL.GL as GL except ImportError: raise ImportError, "OpenGL must be installed to use these functionalities" import Object3DQt as qt import numpy DEBUG = 0 class GLWidgetCachePixmap: def __init__(self, name="Unnamed"): self.__name = name self.__pixmap = None self.__tex...
""" Logging subsystem and basic exception class. """ class Scapy_Exception(Exception): pass import logging,traceback,time class ScapyFreqFilter(logging.Filter): def __init__(self): logging.Filter.__init__(self) self.warning_table = {} def filter(self, record): from scapy.config impor...
__author__ = 'Christian Herold' from batchsystem import Batchsystem import time import os import getpass from paramiko import SSHClient, SSHConfig, AutoAddPolicy class SshConnector: host = "" user = "" ssh_config = None ssh_client = None batch_sys = None batch_config = None ssh_log = "" ...
"""HTML character entity references.""" __revision__ = "$Id$" name2codepoint = { 'AElig': 0x00c6, # latin capital letter AE = latin capital ligature AE, U+00C6 ISOlat1 'Aacute': 0x00c1, # latin capital letter A with acute, U+00C1 ISOlat1 'Acirc': 0x00c2, # latin capital letter A with circumflex, U+0...
import cups def callback (prompt): print "Password is required for this operation" password = raw_input (prompt) return password def test_cups_module (): cups.setUser ("root") cups.setPasswordCB (callback) conn = cups.Connection () printers = conn.getPrinters ().keys () if 0: print "Getting cupsd.conf" file...
"""Utility functions for retrying function calls with a timeout. """ import time from ganeti import errors RETRY_REMAINING_TIME = object() class RetryTimeout(Exception): """Retry loop timed out. Any arguments which was passed by the retried function to RetryAgain will be preserved in RetryTimeout, if it is raised...
from __future__ import unicode_literals from django.db import models, migrations import django.utils.timezone class Migration(migrations.Migration): dependencies = [ ('auth', '0001_initial'), ] operations = [ migrations.CreateModel( name='User', fields=[ ...
__author__ = 'Vyacheslav Pryimak' import sys import json import urllib2 from urllib2 import URLError class JsonCheck: __url = None __jsonResponse = None def __init__(self, url=None): self.__url = url self.__connect() def __connect(self): try: req = urllib2.Request(sel...
import sys, os, re, shutil, glob, logging logging.basicConfig(level = logging.DEBUG, format = '%(levelname)s: %(message)s', # ignore application name filename = 'configure.log', filemode = 'w') console = logging.StreamHandler() console.setLevel(logging.INFO) # the console only print out general information ...
import vm_api.vm_api from code_runner_api.languages_supported import languages class LanguageRunner: def __init__(self, submission): self.run_counter = 0 # used to make sure stdin/stdout/stderr files are unique self.submission = submission self.lang = languages[submission.lang] self.run_session = vm_api.vm_api...
"""Pytest configuration.""" from __future__ import absolute_import, print_function import json import logging import os import shutil import re import tempfile import sys import uuid from contextlib import contextmanager from copy import deepcopy from collections import namedtuple from flask.cli import ScriptInfo impor...
import PyKDE4.kdeui as __PyKDE4_kdeui import PyQt4.QtCore as __PyQt4_QtCore import PyQt4.QtGui as __PyQt4_QtGui class KFileFilterCombo(__PyKDE4_kdeui.KComboBox): # no doc def currentFilter(self, *args, **kwargs): # real signature unknown pass def defaultFilter(self, *args, **kwargs): # real signatur...
import sys from mpi4py import MPI import numpy as np import time import platform import os import sys from collections import deque import importlib import os.path import lmfit from scipy.stats import binned_statistic import warnings warnings.simplefilter('error') sys.path.append( os.path.dirname(os.path.abspath(__file...
""" 1Channel XBMC Addon Copyright (C) 2012 Bstrdsmkr 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 version. ...
from convert_feynmp import TEMPLATE_HEADER, TEMPLATE_FOOTER, u import io import os.path import shutil import subprocess import tempfile import re MYWD = None def process(diagram): global MYWD diagram = re.sub('\\\\','\\\\\\\\',diagram) try: if MYWD is None: MYWD = tempfile.mkdtemp() ...