code stringlengths 1 199k |
|---|
from __future__ import division
from sys import argv
from qiime.util import parse_command_line_parameters, make_option, gzip_open
if argv[1].endswith('.gz'):
f = gzip_open(argv[1])
else:
f = open(argv[1],'U')
outf = open(argv[2], "w")
barcode_len = int(argv[3])
barcodes = {}
counter = 0
total_bcs = 0
for line i... |
from federal_spending.usaspending.models import Grant
from federal_spending.usaspending.scripts.usaspending.grants_loader import Loader
from django.core.management.base import BaseCommand
from django.db import transaction
class Command(BaseCommand):
@transaction.commit_on_success
def handle(self, grant_path, **... |
""" AFDKOPython copyCFFCharstrings.py -src <file1> -dst <file2>[,file3,...filen_n]
Copies the CFF charstrings and subrs from src to dst fonts.
"""
__help__ = """AFDKOPython copyCFFCharstrings.py -src <file1> -dst <file2>
Copies the CFF charstrings and subrs from src to dst.
v1.002 Aug 27 1014
"""
import os
import sys
i... |
"""Get record from pubmed.
Modified from a script by Simon Greenhill. http://simon.net.nz/
"""
import urllib, logging
from xml.dom import minidom
module_logger = logging.getLogger('chotha.pubmed')
def pubmed_id_from_query(query, email='kaushik.ghose@gmail.com', tool='Chotha', database='pubmed'):
"""This is not design... |
from threading import Thread, Event
from time import sleep
DEFAULT_PLAYTIME = 1800
DEFAULT_TIME_PENALTY = 120
DEFAULT_TIME_PENALTY_CAP = 480
class GameTimer(Thread):
"""A generic periodic timer.
Executes a callback every 'interval' times after 'delay' time.
Note on PyGTK:
If you want to use PeriodicTimer and PyGTK... |
from Components.Converter.Converter import Converter
from Components.Element import cached
from Poll import Poll
import NavigationInstance
from ServiceReference import ServiceReference
from enigma import iServiceInformation, iPlayableService
from string import upper
from Tools.Transponder import ConvertToHumanReadable
... |
from mdp import MDP
from agent import ValueIterationAgent, PolicyIterationAgent
import sys
def print_policy(policy):
"""Print the given policy in a readable state"""
words = { MDP.UP: "^", MDP.DOWN: "v", MDP.RIGHT:">", MDP.LEFT:"<" }
for y in range(0,3):
j = 2 - y
for x in range(0,4):
... |
__author__ = 'williewonka'
import os
from fuzzywuzzy import fuzz
streamin = open("Crisis of the Confederation Map.gml", "r")
streamout = open("Crisis of the Confederation Map Corrected.gml", "w")
existing_provinces = {}
for info in os.walk('provinces'):
files = info[2]
for file in files:
name = file.spl... |
import time
import sqlalchemy.exc
from sqlalchemy import create_engine
from sqlalchemy.pool import NullPool
import sqlalchemy
import psycopg2
from listenbrainz.messybrainz import exceptions, data
SCHEMA_VERSION = 1
engine = None
def init_db_connection(connect_str):
global engine
while True:
try:
... |
from os.path import exists
sph='triax-identical-results'
i=0; outSph=''
while True:
outSph='%s-out%02d.spheres'%(sph,i)
if not exists(outSph): break
i+=1
inSph='%s-in.spheres'%sph
if exists(inSph): print("Using existing initial configuration",inSph)
else:
TriaxialTest(noFiles=True).load()
print("Usi... |
from solarisConfig import solarisConfig
import errors
import os
import StringIO
class baseKickstart(object):
"""Base class for generating a kickstart from a solarisConfig. To be
subclassed to handle multiple versions although this class should be
successful at generating a kickstart for Red Hat Linux... |
import account_analytic_account |
from FGAme import *
from scene import *
XCOORDS = (40, SCREEN_WIDTH - 40)
SRADIUS = 15
class Score(RenderTree):
def __init__(self, side, color):
RenderTree.__init__(self)
self.y_height = SCREEN_HEIGHT - 100
self.x_coord = XCOORDS[0] if side == 'left' else XCOORDS[1]
self.color = colo... |
__path__.append(__path__[0] + "/../../../libs/python/bongo") |
import operator
import re
import settings
class GameError(Exception):
pass
class Game:
"""
A game consists of a number of rounds,
and a global scoreboard.
"""
def __init__(self, scores=None):
self.score_dict = scores if scores else {}
self.active_rounds = set()
def add(self, score, author):
"Add a bet to t... |
from django.conf.urls import *
from userena.contrib.umessages import views as messages_views
from django.contrib.auth.decorators import login_required
urlpatterns = patterns('',
url(r'^compose/$',
messages_views.message_compose,
name='userena_umessages_compose'),
url(r'^compose/(?P<recipients>[\... |
import gdbm as dbm
db = dbm.open("default.camera", 'cs')
key = db.firstkey()
while(key != None):
print("Key: " + key + " Value: " + db[key])
key = db.nextkey(key) |
"""
Django settings for hypercamp project.
For more information on this file, see
https://docs.djangoproject.com/en/1.7/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.7/ref/settings/
"""
import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
PROJECT_PAT... |
from setuptools import setup
setup(name='shoot_up_python',
version='0.1',
description='Take screenshots and upload them to Google Drive',
author='Jason Howell',
license='gpl2',
url='https://github.com/jasonrobot/shoot-up-python',
packages=['shoot_up_python'],
install_requires=[... |
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model 'Status'
db.create_table('do_status', (
('id', self.gf('django.db.models.fields.AutoField')(primary_key=True... |
"Import from GeneWeb"
import re
import time
from gramps.gen.ggettext import gettext as _
from gramps.gen.ggettext import ngettext
import logging
LOG = logging.getLogger(".ImportGeneWeb")
from gramps.gen.errors import GedcomError
from gramps.gen.lib import Attribute, AttributeType, ChildRef, Citation, Date, Event, Event... |
'''
Flixnet Add-on
Copyright (C) 2016 Flixnet
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.
This p... |
from socket import *
import time
class BadNet:
dummy=' '
reorder=0
counter = 1
@staticmethod
def transmit(csocket,message,serverName,serverPort):
if (BadNet.counter % 5) != 0:
csocket.sendto(message,(serverName,serverPort))
print 'BadNet Sends properly packet No ' +str(BadNet.counter)
else:
print 'Bad... |
from email.utils import parseaddr
from sqlalchemy import not_
from pyramid.view import (
view_config,
)
from pyramid.httpexceptions import (
HTTPFound,
)
import colander
from deform import (
Form,
widget,
ValidationFailure,
)
from ..models import (
DBSession,
User,
)
from ..m... |
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "lab2.settings")
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv) |
__author__ = 'eternnoir'
__version__ = '0.1' |
from morsel.panda import *
from math import *
class Quaternion(panda.Quat):
def __init__(self, *args, **kargs):
panda.Quat.__init__(self, *args)
if kargs.has_key("orientation"):
self.orientation = kargs["orientation"]
def getOrientation(self):
hpr = self.getHpr()
return [hpr[0], hpr[2], hpr[1]... |
import logging
import re
import struct
import sys
from base64 import b64encode
from hashlib import sha1
if sys.version_info[0] < 3:
from SocketServer import ThreadingMixIn, TCPServer, StreamRequestHandler
else:
from socketserver import ThreadingMixIn, TCPServer, StreamRequestHandler
'''
+-+-+-+-+-------+-+-----... |
import hr_attendance_payslip |
import os,sys,pdb
import numpy as np
import cv2
import gabor2d
import math
from collections import defaultdict
import copy
from scipy.sparse import csc_matrix
def get_image(arr):
m0 = arr.min()
m1 = arr.max()
return np.uint8( 255 * ( arr - m0) / (m1 - m0) )
img = cv2.imread('test.jpg',1)
H,W,C = img.shape
R... |
import kivy
kivy.require('1.7.0')
from kivy.uix.image import Image
from kivy.core.audio import SoundLoader
class Boom(Image):
sound = SoundLoader.load('boom.wav')
def __init__(self, **kwargs):
self.__class__.sound.play()
super(Boom, self).__init__(**kwargs) |
from ventana import Ventana
import utils
import pygtk
pygtk.require('2.0')
import gtk, gtk.glade, time, sqlobject
import sys, os
sys.path.insert(0, os.path.join('..', 'SQLObject', 'SQLObject-0.6.1'))
try:
import pclases
except ImportError:
sys.path.insert(0, os.path.join('..', 'framework'))
import pclases
t... |
'''
Created on 21/4/2012
@author: David Snowdon (c) 2012
'''
import codecs
import os
import jprops
import json
LANGUAGE_MAP = {
"arabic" : "ar",
"brazilian" : "pt",
"chinese" : "zh",
"czech" : "cs",
"dutch" : "nl",
"danish" ... |
import math
import crosstex.latex
import crosstex.style
class PlainBbl(object):
etalchar = '{\etalchar{+}}'
def header(self, longest):
return '\\newcommand{\etalchar}[1]{$^{#1}$}\n' + \
'\\begin{thebibliography}{%s}\n' % longest
def heading(self, name, sep):
return ''
def ... |
import os
from rebasehelper.helpers.process_helper import ProcessHelper
from rebasehelper.logger import logger
from rebasehelper.helpers.path_helper import PathHelper
from rebasehelper.build_helper import BuildToolBase
from rebasehelper.build_helper import BinaryPackageBuildError
from rebasehelper.build_helper import M... |
"""
***************************************************************************
OTBSpecific.py
***************************************************************************
* *
* This program is free software; you can redistribute it and/or mod... |
import nltk
import logging
from stats_distribution.model import Tweets
logger = logging.getLogger()
class DBError(Exception):
def __init__(self, expr, msg):
self.expr = expr
self.msg = msg
def readRelationalData(DbField):
result = []
if type(DbField) is not str:
raise Exception("DbField is not string"... |
#!/usr/bin/env python
import argparse
import os
import os.path
import codecs
translations = {'cz': [('\\200', u'á'),
('\\201', u'č'),
('\\201', u'Č'),
('\\202', u'é'),
('\\203', u'ě'),
('\\204', u'í'),
... |
"""Version information for Invenio.
This file is imported by ``invenio.__init__``, and parsed by ``setup.py``.
"""
version = (2, 0, 6)
def build_version(*args):
"""Build a PEP440 compatible version based on a list of arguments.
Inspired by Django's django.utils.version
.. doctest::
>>> print(build_v... |
def kabababoom(kababoom):
kabaam = range; kaboom = len; kababaam = 1
return list(kabaam(kababaam,kaboom(kababoom)+kababaam))
def kabababaam(kaboom):
kabaam = range; kabobaam = len; kababoom = [0 for kababaam in kabaam(10000)]; kabeem = 5000; kababiim = 1
for kabiim in kaboom:
kababoom[kabiim%kabeem+kabeem]+=kabab... |
import threading
from enum import IntEnum
from dasbus.error import DBusError
from pyanaconda.core.constants import THREAD_STORAGE, THREAD_PAYLOAD, THREAD_PAYLOAD_RESTART, \
THREAD_WAIT_FOR_CONNECTING_NM, THREAD_SUBSCRIPTION, PAYLOAD_TYPE_DNF, \
THREAD_STORAGE_WATCHER, THREAD_EXECUTE_STORAGE
from pyanaconda.core... |
from os import listdir
from os.path import (isfile, join)
from collections import Iterable, OrderedDict
from invenio.search_engine import get_record
from invenio.bibdocfile import BibRecDocs
NATIONS_DEFAULT_MAP = OrderedDict()
NATIONS_DEFAULT_MAP["Democratic People's Republic of Korea"] = "North Korea"
NATIONS_DEFAULT_... |
import pytest
import random
import time
from cfme import test_requirements
from cfme.cloud.provider.azure import AzureProvider
from cfme.cloud.provider.ec2 import EC2Provider
from cfme.cloud.provider.gce import GCEProvider
from cfme.cloud.provider.openstack import OpenStackProvider
from cfme.common.provider import Base... |
from flask import Blueprint, request, Response
from flask.ext.security import login_required
from arda import mongo
from bson import json_util, SON
from datetime import datetime
from slugify import slugify
mod_api = Blueprint('api', __name__, url_prefix='/api')
@mod_api.route('/service-fee', methods=['GET'])
@login_req... |
"""Handle records from /proc/version files"""
import regentest as RG
import ProcHandlers as PH
PFC = PH.PFC
def re_root_version(inprecs):
"""Iterate through parsed records and re-generate data file"""
__template = "{sys:s} version {rel:s} ({comp_by:s}@{comp_host:s}) \
({compiler:s}) {vers:s}"
for __hilit in... |
from Core import TreeClass as tc
import numpy as np
file_original = open('input/test.txt', 'r')
file_predicted = open('input/full_hid25_re0-0007-test.txt','r')
gram_5_list_original = []
gram_5_node_list_original = []
gram_5_node_list_predicted = []
for line in file_original:
tree = tc.ScoreTree(line)
for node i... |
import Tix
import tkMessageBox
def main(_):
# Close any other pop-up windows and open new external window.
xwin = _.getExtWin(_, title=u'And a company (group)', destroy=True)
group_name = Tix.StringVar()
first_branch = Tix.StringVar()
tv = _.loc(u'Enter the group name for all branches\nUse 2-4 chara... |
from nose.tools import eq_ as eq, assert_raises, raises
import os
from cStringIO import StringIO
from gitosis import ssh
from gitosis import sshkey
from gitosis.test.util import mkdir, maketemp, writeFile, readFile
def _key(s):
return ''.join(s.split('\n')).strip()
KEY_1 = _key("""
ssh-rsa +v5XLsUrLsHOKy7Stob1lHZM1... |
''' This scipt is designed to read the values fom the MLX9061 IR
temperature sensor
'''
from __future__ import division
import sys
import os
from smbus import SMBus
import time
import logging
import logging.handlers
import threading
import Queue
import mlx.control_variable
from mlx.linux_cmd_setup import Linux_Command ... |
try:
from subprocess import check_output
except:
from check_output import check_output
from subprocess import STDOUT
from subprocess import call
import unittest
import os
import numpy
import re
float_expr = re.compile(r"([+-]?\d+\.\d+e[+-]\d+)")
input_file_list = ["data/fio/scan_mca_00001.fio","data/fio/scan_mc... |
from base import Persistence
class PubStatusI18n(Persistence):
pass |
from django.conf import settings
from django.shortcuts import render, render_to_response
from django.shortcuts import get_object_or_404, get_list_or_404
from django.http import HttpResponseForbidden
from django.views.generic import View
from patchwork.models import Patch, Project, Bundle
from patchwork.models import Se... |
from sys import stdout
from traceback import format_exc
from Core.config import Config
import socket
from smtplib import SMTP, SMTPException, SMTPSenderRefused, SMTPRecipientsRefused
from ssl import SSLError
import time
CRLF = "\r\n"
encoding = "UTF8"
def decode(text):
# Converts strings to Unicode
if type(text... |
"""Easy to use object-oriented thread pool framework.
A thread pool is an object that maintains a pool of worker threads to perform
time consuming operations in parallel. It assigns jobs to the threads
by putting them in a work request queue, where they are picked up by the
next available thread. This then performs the... |
import os
def files(type_):
return sorted(filter(lambda x: x.endswith(type_), os.listdir('.')))
def int_file(filename):
return (int(filename.split('.')[0].replace('capt', '')), filename)
def pairs(iterable):
return zip(iterable[0::2], iterable[1::2])
def mount_of(path):
'Return the mountpoint for a give... |
"""
backup_to_s3.py
One simple strategy for backing up a server to S3: a single backup_to_s3
function which takes your S3 authentication details plus three (optional)
dictionaries specifying directories, files and commands to be backed up.
e.g:
backup_to_s3(
access_key = 'your-access-key',
secret_ac... |
from models import Data
from monografias.models import DatasMonografia
from django.forms import ModelForm
from django import forms
class DatasLimiteForm(ModelForm):
class Meta:
model = Data
exclude = ('grupo', 'ano', 'semestre')
def clean(self):
cleaned_data = self.cleaned_data
m... |
"""
EasyBuild support for AMD Core Math Library (ACML), implemented as an easyblock
@author: Stijn De Weirdt (Ghent University)
@author: Dries Verdegem (Ghent University)
@author: Kenneth Hoste (Ghent University)
@author: Pieter De Baets (Ghent University)
@author: Jens Timmerman (Ghent University)
"""
import os
from d... |
import pylab as plb
import numpy as np
from matplotlib import rc
rc('text', usetex=True)
rc('text.latex', unicode=True)
rc('text.latex', preamble=r'\usepackage[russian]{babel}')
rc('font',**{'size':'19'})
def plot(t, inp, wavenet, param, orig=None, target=None, xlabel='', ylabel=''):
plb.rc('font', family='serif')
... |
import logging
logger = logging.getLogger()
import subprocess
import time
import hostapd
from wpasupplicant import WpaSupplicant
def test_wpas_ctrl_network(dev):
"""wpa_supplicant ctrl_iface network set/get"""
id = dev[0].add_network()
if "FAIL" not in dev[0].request("SET_NETWORK " + str(id)):
raise... |
import basic_tools
from mien.math.array import *
from string import join, split
import os
def getDataServer(doc):
'''check the document for a DataServ generate a DataServe class for a
DataServer stored as doc._dataserver. If it is found, return it. if not,
create it and then return it'''
if not doc.__dict__.has_key('... |
''' Setup for core modules
'''
def configuration(parent_package='',top_path=None):
from numpy.distutils.misc_util import Configuration
config = Configuration('learn', parent_package, top_path)
config.set_options(quiet=True)
config.add_subpackage('core')
return config
if __name__ == '__main__':
f... |
import os
import shutil
from kano.utils import run_cmd
from gi import require_version
require_version('Gtk', '3.0')
from gi.repository import Gtk, Gdk
from kano_settings.set_wallpaper import SetWallpaper
from kano_settings.set_screensaver import SetScreensaver
from kano_settings.system.wallpaper import change_wallpaper... |
poem = ["<B>", "Jack", "and", "Jill", "</B>", "went", "up", "the",
"hill", "to", "<B>", "fetch", "a", "pail", "of", "</B>",
"water", "Jack", "fell", "<B>", "down", "and", "broke",
"</B>", "his", "crown", "and", "<B>", "Jill", "came",
"</B>", "tumbling", "after"]
def get_bolds(text):
... |
from __future__ import unicode_literals, absolute_import
import unittest
import sys
import os
import mock
sys.path.insert(0, os.path.join(os.path.dirname(
os.path.abspath(__file__)), '..'))
import pagure.lib.tasks_services
import tests
class PagureFlaskPluginPagureCItests(tests.SimplePagureTest):
""" Tests for ... |
from PySide import QtCore, QtGui
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(640, 480)
self.centralwidget = QtGui.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.verticalLayout... |
"""
CrayIntel toolchain: Intel compilers and MPI via Cray compiler drivers + LibSci (PrgEnv-intel) and Cray FFTW
:author: Petar Forai (IMP/IMBA, Austria)
:author: Kenneth Hoste (Ghent University)
"""
from easybuild.toolchains.compiler.craype import CrayPEIntel
from easybuild.toolchains.linalg.libsci import LibSci
from ... |
epsilon=0.001
y=25.0
guess=y/2.0
step=0
while abs(guess*guess -y )>= epsilon:
guess= guess - (((guess**2)-y)/(2*guess))
step+=1
print step, guess
print ('Square root of ' +str(y)+' is about '+str(guess)) |
__version__ = "0"
__author__ = "IOhannes m zmölnig, IEM"
__license__ = "GNU General Public License"
__all__ = []
from client import client
__all__+=["Client"]
from server import server
__all__+=["server"]
from discovery import publisher, discoverer
__all__+=["Discovery"] |
"""
plugin.py
Copyright (C) 2010 Patrick Installé <PatrickInstalle@P-Installe.be>
Copyright (C) 2010-2011 Corentin Chary <corentincj@iksaif.net>
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 Foundat... |
"""
17176 : 암호해독기
URL : https://www.acmicpc.net/problem/17176
Input #1 :
11
44 0 38 41 38 31 23 8 41 30 38
Hello World
Output #1 :
y
Input #2 :
5
12 3 34 52 0
apple
Output #2 :
n
"""
A = ord('A')
a = ord('a')
def decrypt(encrypted):... |
"""configure test to determine size of void *"""
def _check(context):
context.Message("Determining sizeof(void *)... ")
text = """
int main(void) {
printf("%d", (int)sizeof(void *));
return 0;
}
"""
ret = context.TryRun(text, ".c")
if ret[0] == 0:
context.env.Exit("Could not run sizeof check... |
"""
Tests for kqueue wrapper.
"""
import socket
import errno
import time
import select
import sys
import unittest
from test import test_support
if not hasattr(select, "kqueue"):
raise unittest.SkipTest("test works only on BSD")
class TestKQueue(unittest.TestCase):
def test_create_queue(self):
kq = selec... |
"""BibEdit Utilities.
This module contains support functions (i.e., those that are not called directly
by the web interface), that might be imported by other modules or that is called
by both the web and CLI interfaces.
"""
__revision__ = "$Id$"
import difflib
import fnmatch
import marshal
import os
import re
import ti... |
from picard.coverart.providers.caa import CoverArtProviderCaa
from picard.coverart.image import CaaCoverArtImage, CaaThumbnailCoverArtImage
class CaaCoverArtImageRg(CaaCoverArtImage):
pass
class CaaThumbnailCoverArtImageRg(CaaThumbnailCoverArtImage):
pass
class CoverArtProviderCaaReleaseGroup(CoverArtProviderCa... |
import threading
import socket
import struct
import sys
import time
from dnsdisttests import DNSDistTest, Queue
import dns
import dnsmessage_pb2
class TestProtobuf(DNSDistTest):
_protobufServerPort = 4242
_protobufQueue = Queue()
_protobufCounter = 0
_config_params = ['_testServerPort', '_protobufServer... |
def decorate_A(function):
def wrap_function(*args, **kwargs):
kwargs['str'] = 'Hello!'
return function(*args, **kwargs)
return wrap_function
@decorate_A
def print_message_A(*args, **kwargs):
print(kwargs['str'])
print_message_A()
def decorate_B(function):
def wrap_function(*args, **kwarg... |
import json
import socket
import urllib
import urllib2
import decimal
from django.conf import settings
from petri.common.utils.helpers import force
class IPInfoDBException(Exception):
pass
def _clean_response(raw):
if type(raw) is not dict:
raise IPInfoDBException()
if raw.get('Status', None) != 'OK':
rai... |
import wx
import wx.richtext
import wx.lib.buttons
import input_administrasi_surat
def create(parent):
return surat_masuk(parent)
[wxID_SURAT_MASUK, wxID_SURAT_MASUKDARI, wxID_SURAT_MASUKDATEPICKERCTRL1,
wxID_SURAT_MASUKINPUT_KETERANGAN, wxID_SURAT_MASUKINPUT_NOMOR_SURAT,
wxID_SURAT_MASUKKOTAK_SURAT_MASUK, wxID_S... |
TEXT_DEVICE_NOT_FOUND = '''[Device not found]: Vendor ID: {}\t Product ID: {}\n'''
TEXT_DEVICE_FOUND = '''[Device found]: Vendor ID: {}\t Product ID: {}\n'''
TEXT_BLOCK_TEST = '''[TEST]: zone: {}\t mode:{}\t speed:{}\t color1:{}\t color2: {}\n'''
TEXT_BLOCK_LIGHTS_OFF = '''[Command]: Lights off''' |
from testtools.matchers import Equals
from snapcraft.internal.project_loader._extensions.gnome_3_34 import ExtensionImpl
from tests.unit.commands import CommandBaseTestCase
from .. import ProjectLoaderBaseTest
class ExtensionTest(ProjectLoaderBaseTest, CommandBaseTestCase):
def test_extension(self):
gnome_e... |
import certs.models
from django.db import migrations, models
import jsonfield.fields
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Certificate',
fields=[
('id', models.AutoField(auto_c... |
"""
Twisted implementation of ZeroMQ Majordomo Protocol
MDP specification can be found at http://rfc.zeromq.org/spec:7
"""
import logging
logger = logging.getLogger('txmdp')
handler = logging.StreamHandler()
handler.setFormatter( logging.Formatter('%(asctime)s %(name)s: %(message)s', "%H:%M:%S") )
logger.handlers = [ha... |
import pandas as pd
import numpy as np
import pickle
rawData = pd.read_csv('trenes-despachados.csv', sep = ';')
rawData.head()
rawData.drop(['FR1_REGIST','FR1_KM','FR1_KMV'], axis = 1, inplace = True)
rawData.head()
rawData.columns = ['date','line','dayType','travelId','trainId',
'notDispach1','notDi... |
"""Demonstrate the representations of values using different encodings.
"""
from codecs_to_hex import to_hex
text = u'pi: π'
encoded = text.encode('utf-8')
decoded = encoded.decode('utf-8')
print 'Original :', repr(text)
print 'Encoded :', to_hex(encoded, 1), type(encoded)
print 'Decoded :', repr(decoded), type(decod... |
__author__ = 'Serge Poltavski'
from pddoc.pd import PdObject
from pddoc.cairopainter import CairoPainter
def create(atoms):
assert len(atoms)
return PddpDsp(atoms[0], atoms[1:])
class PddpDsp(PdObject):
def __init__(self, name, args):
PdObject.__init__(self, name, 0, 0, 0, 0, args)
def inlets(se... |
import dbus
import dbus.service
INTROSPECT_DOCTYPE = \
'<!DOCTYPE node PUBLIC "-//freedesktop//DTD D-BUS Object Introspection 1.0//EN" ' \
'"http://www.freedesktop.org/standards/dbus/1.0/introspect.dtd">\n'
def dbus_property(dbus_interface, signature, setter=None):
""" TODO doc """
def decorator(func):
... |
from urllib.request import urlopen, Request
from multiprocessing import Manager
from multiprocessing.pool import Pool
from queue import Empty
from time import sleep
from mimetypes import guess_extension
from os.path import splitext
from urllib.parse import urlparse
import logging
__author__ = "Ivan de Paz Centeno"
wait... |
'''Module containing manual classification panel in the GUI'''
import sys
import string
import multiprocessing as mp
import ctypes
import numpy as np
try:
from PyQt5 import QtWidgets # pylint: disable=import-error
except ImportError:
import sip
sip.setapi('QString', 2)
from PyQt4 import QtGui as QtWidge... |
"""Main Module of the IOC Logic."""
import time as _time
from datetime import datetime as _datetime
import logging as _log
from copy import deepcopy as _dcopy
from threading import Thread as _Thread
import numpy as _np
from mathphys.functions import get_namedtuple as _get_namedtuple
from ..callbacks import Callback as ... |
"""Test parameters description file"""
import pytest
import numpy as np
from ocelot import *
from ocelot.utils.bump_utils import *
"""Lattice elements definition"""
d = Drift(l=0.35)
d1 = Drift(l=0.6)
qf = Quadrupole(l=0.2, k1=4)
qd = Quadrupole(l=0.2, k1=-4)
c1 = Vcor(l=0.1)
c2 = Vcor(l=0.1)
c3 = Vcor(l=0.1)
c4 = Vcor... |
'''Process Burp Suite Professional's output into a well-formed XML document.
Burp Suite Pro's session file zipped into a combination of XML-like tags
containing leading binary headers with type and length definitions followed by
the actual data. The theory is that this allows the file to read sequentially
rather than ... |
'''
Genesis Add-on
Copyright (C) 2015 lambda
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.
This pr... |
""" a
bb
ccc
""" |
import json
import networkx as nx
from networkx.readwrite import json_graph
import httplib2
baseUrl = 'http://localhost:8080/controller/nb/v2/'
containerName = 'default/'
h = httplib2.Http(".cache")
h.add_credentials('admin', 'admin')
resp, content = h.request(baseUrl + 'topology/' + containerName, "GET")
edgePropertie... |
"""
This module contains :class:`DeviceBase` as a base class for other device classes and
infrastructure that can import devices from a module (:class:`DeviceRegistry`). The latter also
produces factory-like objects that create device instances and interfaces based on setups
(:class:`DeviceBuilder`).
"""
import importl... |
"""
Demo #9
The ninth script in our tutorial about using GalSim in python scripts: examples/demo*.py.
(This file is designed to be viewed in a window 100 characters wide.)
This script simulates cluster lensing or galaxy-galaxy lensing. The gravitational shear
applied to each galaxy is calculated for an NFW halo mass p... |
from django.test import LiveServerTestCase
from nose.plugins.attrib import attr
from selenium import webdriver
import time
@attr('selenium')
class TestFePageLogin(LiveServerTestCase):
def setUp(self):
self.driver = webdriver.Firefox()
self.driver.implicitly_wait(1)
def tearDown(self):
se... |
from __future__ import division
import hashlib
import random
import warnings
import p2pool
from p2pool.util import math, pack
def hash256(data):
return pack.IntType(256).unpack(hashlib.sha256(hashlib.sha256(data).digest()).digest())
def hash160(data):
if data == '04ffd03de44a6e11b9917f3a29f9443283d9871c9d743ef3... |
print("Geeks : % 2d, Portal : % 5.2f" %(1, 05.333))
print("Total students : % 3d, Boys : % 2d" %(240, 120))
print("% 7.3o"% (25))
print("% 10.3E"% (356.08977))
print('I love {} for "{}!"'.format('Geeks', 'Geeks'))
print('{0} and {1}'.format('Geeks', 'Portal'))
print('{1} and {0}'.format('Geeks', 'Portal'))
print('Numbe... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.