code stringlengths 1 199k |
|---|
from django.contrib import admin
from Blogs.models import(Post, Comment)
admin.site.register(Post)
admin.site.register(Comment) |
"""
ETHERNET module
Decode ethernet layer (RFC 894) Ethernet II.
"""
import nfstest_config as c
from baseobj import BaseObj
from macaddr import MacAddr
from packet.internet.ipv4 import IPv4
from packet.internet.ipv6 import IPv6
from packet.internet.arp import ARP,RARP
__author__ = "Jorge Mora (%s)" % c.NFSTEST_AUTHO... |
"""
bkr job-cancel: Cancel running Beaker jobs
==========================================
.. program:: bkr job-cancel
Synopsis
--------
:program:`bkr job-cancel` [--msg <message>] [*options*] <taskspec>...
Description
-----------
Specify one or more <taskspec> arguments to be cancelled.
The <taskspec> arguments follow ... |
import pytest
from spinner import transforms
from spinner import coordinates
from spinner import cabinet
from example_cabinet_params import exact
def test_hex_to_cartesian():
h = coordinates.Hexagonal
c = coordinates.Cartesian2D
# Test single element cases
o0 = "o0"
o1 = "o1"
o2 = "o2"
assert transforms.hex_to_c... |
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('statusboard', '0015_merge_20170222_2058'),
]
operations = [
migrations.AddField(
model_name='service',
name='position',
... |
import json
import sys
import urllib
keyword = sys.argv[1]
def getTimes(query,num):
"Questa funzione fa una ricerca su NY Times"
url = "http://query.nytimes.com/svc/cse/v2/sitesearch.json?query="+query.replace(" ","%20")+"&pt=article&page="+str(num)
jtext = urllib.urlopen(url)
return jtext
def search(te... |
import time
Density=2400
frictionAngle=radians(35)
tc = 0.001
en = 0.3
es = 0.3
params=utils.getViscoelasticFromSpheresInteraction(tc,en,es)
facetMat=O.materials.append(ViscElMat(frictionAngle=frictionAngle,**params)) # **params sets kn, cn, ks, cs
sphereMat=O.materials.append(ViscElMat(density=Density,frictionAngle=fr... |
import os
import re
import sys
import json
import urllib
import socket
import subprocess
import cgi, cgitb
from os import listdir
from os.path import isfile, join
def peos_notify(patient_id):
EXECUTION_PATH = "../peos/os/kernel/"
#Error constants
ERROR_USER_NOT_EXIST = 1
ERROR_SCRIPT_FAIL = 2
os.chd... |
"""
:created: 2014-01-25
:author: Rinze de Laat
:copyright: © 2014 Rinze de Laat, Delmic
This file is part of Odemis.
.. license::
Odemis is free software: you can redistribute it and/or modify it under the
terms of the GNU General Public License version 2 as published by the Free
Software Foundation.
O... |
import web
session = web.config.get('_session')
def require_login(func):
def proxyfunc(self, *args, **kw):
if session.get('logged') is True:
return func(self, *args, **kw)
else:
session.kill()
raise web.seeother('/login?msg=loginRequired')
return proxyfunc
def... |
from django.db import models
from jokeregistryweb.jokes.models import Joke
class Claim(models.Model):
'''A claim of prior art (or infringement)'''
FILED = 0
APPROVED = 1
REJECTED = 2
STATUS_CHOICES = (
(FILED, 'Filed'),
(APPROVED, 'Approved'),
(REJECTED, 'Rejected')
)
... |
from functools import cmp_to_key
from time import time
from timer import TimerEntry as RealTimerEntry
from PowerTimer import PowerTimerEntry, AFTEREVENT
from Components.ActionMap import ActionMap
from Components.Button import Button
from Components.config import config
from Components.Label import Label
from Components... |
import os
import cPickle as pkl
from collections import namedtuple
import requests
from bs4 import BeautifulSoup
Song = namedtuple('Song', ['title', 'artist', 'album', 'length'])
class Playlist(object):
def __init__(self, title, url):
self.title = title
self.file_name = title.lower().replace(' ', '-... |
"""Module to check modules existance.
This exports this booleans:
- has_reportlab -- True if reportlab is found
- has_PIL -- True if PIL is found
- has_pygtk -- True if pygtk is found
Copyright (C) 2005-2008 Xosé Otero <xoseotero@users.sourceforge.net>
"""
__all__ = ["has_reportlab", "has_PIL", "has_pygtk"]
try:... |
"""
Date editing module for GRAMPS.
The EditDate provides visual feedback to the user via a pixamp
to indicate if the associated GtkEntry box contains a valid date. Green
means complete and regular date. Yellow means a valid, but not a regular date.
Red means that the date is not valid, and will be viewed as a text str... |
sql_template0 = """alter table _shadow_orders_{0}_ modify fingerprint text DEFAULT '' COMMENT '下单fingerprint';"""
if __name__ == '__main__':
for index in range(0, 50):
print(sql_template0.format(index))
print("------")
for index in range(50, 100):
print(sql_template0.format(index)) |
try:
from xml.etree import cElementTree as etree
except ImportError:
from xml.etree import ElementTree as etree
import xml2nrn
import neuroml
import metadata
import morphml
import biophysics
class FileWrapper:
def __init__(self, source):
self.source = source
self.lineno = 0
def read(self... |
import rrdtool, os
from def_rrds import rrds
import def_metrics
from def_metrics import metrics
for m in metrics:
if isinstance(metrics[m]['rrd'], list):
# multiples rrds
for i,f in enumerate(metrics[m]['rrd']):
if not os.path.isfile(f):
rrdtool.create(f, rrds[m][i])
... |
import os
import sys
import unittest
import pwd
import grp
import stat
from tempfile import TemporaryDirectory
from test import generic
sys.path.append(os.path.join(os.path.dirname(__file__), '..'))
import config
import snapshots
import mount
CURRENTUID = os.geteuid()
CURRENTUSER = pwd.getpwuid(CURRENTUID).pw_name
CURR... |
import os
import time
import glob
import cPickle
import sys
import types
from operator import truth
import xmlrpclib
from spacewalk.common.rhnLib import parseRPMName
from spacewalk.common.rhnLog import log_debug, log_error
from spacewalk.common.rhnException import rhnFault
from spacewalk.common.rhnConfig import CFG
fro... |
import functools
class memoize(object):
def __init__ (self, func):
self.func = func
def __call__ (self, *args, **kwargs):
if (args, str(kwargs)) in self.__dict__:
value = self.__dict__[args, str(kwargs)]
else:
value = self.func(*args, **kwargs)
self.__... |
from datetime import datetime
import csv
import pandas
import os
import sys
os.chdir(sys.argv[1])
ticker_f = open(sys.argv[2], "rb")
ticker_reader = csv.reader(ticker_f)
tickers = [r[0] for r in ticker_reader][1:]
ticker_f.close()
tln = len(tickers)
t_1 = datetime.now()
res = None
for i, t in enumerate(tickers):
t_... |
__dff_module_info_version__ = "1.0.0"
from api.vfs import *
from api.module.script import *
from api.loader import *
from api.module.module import *
from api.taskmanager.taskmanager import *
from api.types.libtypes import Parameter, Variant, Argument, typeId, ConfigManager
from datetime import timedelta, datetime
from ... |
from pylab import *
from vna_control import *
from csv_utils import *
import argparse, os, time, sys
SWEEP_CENTER = 15e6
SWEEP_SPAN = 20e6
SWEEP_POINTS = 1201
TX_STARTUP_DELAY = 2 # 20
BEAMS = 24
if __name__ == '__main__':
# setup arguement parser and parse arguements
parser = argparse.ArgumentParser()
pars... |
import os
import sys
import random
import pygame
from Engine import *
from Montag import *
from Character import Character
from pygame.locals import *
class AICharacter(Character):
def __init__(self, screen, **kwargs):
super().__init__(screen, **kwargs)
self.enemy = kwargs.get("enemy", None)
... |
from __future__ import division, absolute_import, unicode_literals
import time
from qtpy import QtCore
from qtpy import QtGui
from qtpy import QtWidgets
from qtpy.QtCore import Qt
from qtpy.QtCore import Signal
from qtpy.QtWidgets import QDockWidget
from .. import core
from .. import gitcfg
from .. import qtcompat
from... |
'''
Module for handling openstack neutron calls.
:maintainer: <akilesh1597@gmail.com>
:maturity: new
:platform: all
:optdepends: - neutronclient Python adapter
:configuration: This module is not usable until the following are specified
either in a pillar or in the minion's config file::
keystone.user: ad... |
import numpy as np
from scipy.sparse import csr_matrix, coo_matrix
def save_sparse_csr(filename,array):
np.savez(filename,data = array.data ,indices=array.indices,
indptr =array.indptr, shape=array.shape )
def load_sparse_csr(filename):
loader = np.load(filename)
return csr_matrix(( loader['da... |
"""
Dtella - Core P2P Module
Copyright (C) 2008 Dtella Labs (http://www.dtella.org)
Copyright (C) 2008 Paul Marks
$Id$
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 2
of the License... |
def p5a():
xs = [-.75, -0.5,-0.25,0]
fxs = [-.0718125, -.02475, .3349375, 1.101]
getdd123(xs,fxs,3)
def getdd123(xs,fxs,n):
l1stdd = []
l2nddd = []
l3rddd = []
for i in range(0,n):
l1stdd.append((fxs[i+1]-fxs[i])/(xs[i+1]-xs[i]))
for i in range(0,n-1):
l2nddd.append((l1stdd[i+1]-l1stdd[i])/(xs[i... |
import math
from cornice import Service
from pyramid.exceptions import HTTPNotFound
from sqlalchemy import func, distinct
from sqlalchemy.sql import or_
from bodhi import log
from bodhi.models import Build, BuildrootOverride, Package, Release, User
import bodhi.schemas
import bodhi.services.errors
from bodhi.validators... |
import os
import numpy as np
from matplotlib import pyplot as plt
from numpy import genfromtxt
from matplotlib import cm
from mpl_toolkits.mplot3d.art3d import Poly3DCollection
import matplotlib as mpl
from mpl_toolkits.mplot3d import Axes3D
def axisEqual3D(ax):
extents = np.array([getattr(ax, 'get_{}lim'.format(di... |
__author__ = 'Dongwoo Kim'
import itertools
from collections import defaultdict
import numpy as np
def num_neighbor(T, idx, link_val=1):
"""
find neighborhood of given idx (node)
"""
outlink = len(np.nonzero(T[idx, :, :] == link_val))
inlink = len(np.nonzero(T[:, idx, :] == link_val))
return out... |
'''
run with: python ten2eleven.py -f agmethods2 test_dummy_old_MDA_code.py
Author: Tyler Reddy
'''
from lib2to3.fixer_base import BaseFix
from lib2to3.fixer_util import Name, Call, LParen, RParen, ArgList, Dot
from lib2to3 import pytree
class FixAgmethods2(BaseFix):
PATTERN = """
power< head =any+
... |
"""Data model for app."""
from google.appengine.ext import db
from google.appengine.api import search
from google.appengine.api import memcache
import datetime
YEAR_MAX = 25
class Country(db.Model):
"""Country. Just to make things simple."""
# Sorting order.
order = db.IntegerProperty(default=1)
# Local... |
__author__ = (
"Michael Cohen <scudette@google.com>",
"Adam Sindelar <adam.sindelar@gmail.com>")
from rekall import obj
from rekall import plugin
from rekall_lib import registry
from rekall.plugins.darwin import common
class DarwinUnpListCollector(common.AbstractDarwinProducer):
"""Walks the global list of ... |
from __future__ import print_function
import argparse
import collections
import io
import json
import logging
import os
import queue
import random
import re
import requests
import sys
import traceback
import threading
import time
from ..core import provider
from ..utils import rnd
from . import window
logger = logging.... |
import sys, xbmcplugin, xbmcgui,xbmc
_id = "plugin.video.italian-news"
_resdir = "special://home/addons/" + _id + "/resources"
_thisPlugin = int(sys.argv[1])
_icons = _resdir + "/icons/"
sys.path.append( xbmc.translatePath(_resdir + "/lib/"))
import rai
_tg1Icon=xbmc.translatePath(_icons +"Tg1_logo.png")
_tg2Icon=xbmc.... |
def sanitize(time_string):
if '-' in time_string:
splitter = '-'
elif ':' in time_string:
splitter = ':'
else:
return(time_string)
(mins, secs) = time_string.strip().split(splitter)
return(mins + '.' + secs)
def get_coach_data(filename):
try:
with open(filename) as fn:
data = fn.readli... |
"""Add default COMPILE_YARA_RULE_ON_SAVE setting
Revision ID: af2de80654b6
Revises: 2f0f6d26a505
Create Date: 2018-11-11 19:26:53.631142
"""
from alembic import op
import sqlalchemy as sa
from app.models import cfg_settings
import datetime
from sqlalchemy.dialects import mysql
revision = 'af2de80654b6'
down_revision = ... |
import sys
from PyQt4.QtCore import *
from PyQt4.QtGui import *
import moviedata
class MainWindow(QMainWindow):
def __init__(self, parent=None):
super(MainWindow, self).__init__(parent)
self.movies = moviedata.MovieContainer()
self.table = QTableWidget()
self.setCentralWidget(self.ta... |
from wader.common.consts import WADER_CONNTYPE_USB
from core.hardware.zte import (ZTEWCDMADevicePlugin,
ZTEWCDMACustomizer,
ZTEWrapper)
class ZTEMF180Wrapper(ZTEWrapper):
def send_ussd(self, ussd):
"""Sends the ussd command ``ussd... |
import time
def select_same_fill_color(context):
doc = context.document
select = []
properties = doc.CurrentProperties()
if properties.HasFill():
color = properties.fill_pattern.Color()
layer = doc.ActiveLayer()
doc.SelectNone()
for obj in layer.GetObjects():
... |
import logging
import re
from streamlink.compat import html_unescape, urlparse
from streamlink.plugin import Plugin, PluginArguments, PluginArgument
from streamlink.plugin.api import validate
from streamlink.stream import DASHStream, HLSStream, HTTPStream
from streamlink.stream.ffmpegmux import MuxedStream
from streaml... |
import socket, sys, time, argparse
parser = argparse.ArgumentParser(description="This bad server accepts an HTTP connection and replies with a valid HTML document which links to assets. However, attemps to load the assets should result in a net::ERR_EMPTY_RESPONSE.")
parser.add_argument("-p", "--port", type=int, help="... |
import array
import tempfile
from portage import _unicode_decode
from portage import _unicode_encode
from portage.tests import TestCase
class ArrayFromfileEofTestCase(TestCase):
def testArrayFromfileEof(self):
# This tests if the following python issue is fixed
# in the currently running version of python:
# h... |
"""audio driver subsystem"""
from os.path import exists
from os import environ
from subprocess import check_call
from functools import partial
from .drive import Driver
import click
DRIVE_QUEUE = 'a.drive'
CTL_PATH = '{}/.config/pianobar/ctl'.format(environ['HOME'])
COMMANDS = {'p', 'n', '^', '(', ')'}
def callback(ctl... |
import sys,os,string
def GFX_MenuDialog(filename,*items):
file=open(filename,'w')
file.writelines(map(lambda x:x+"\n", items))
file.close()
os.system("python X11_MenuDialog.py "+filename);
if __name__=="__main__":
import qt,string
class WidgetView ( qt.QWidget ):
def __init__( self, *args ):
apply... |
'''Handles the local BLAST and the parsing of the results.
The BLAST uses the NCBI blast+ command-line tools to run a local BLAST against
the organism's genome. In the event that a closed genome is not available for
a species, the genome of a closely related strain can be used in its place.
When a hit has been found, t... |
from django.db import models
class Tip(models.Model):
text = models.TextField(max_length=1000)
date = models.DateField(auto_now_add=True)
class Meta:
ordering = ['-date']
def __unicode__(self):
return '%s ' % (self.text)
class CurrentTip(models.Model):
index = ... |
from setuptools import setup
from glob import glob
from WebPlayer2LocalPlayer import __version__
APP = ['WebPlayer2LocalPlayer.py']
DATA_FILES = [
('images', glob('images/*.png')),
]
OPTIONS = {
'argv_emulation': True,
'includes': [
'sip',
'PyQt5', 'PyQt5.QtGui', 'PyQt5.QtPrintSupport',
... |
from setuptools import setup
import os.path
setup(
name='State Fragility',
version='1',
py_modules=['state_fragility'],
data_files=[('', [
"./state_fragility.db"
])]
) |
import fsui
from fswidgets.widget import Widget
from launcher.i18n import gettext
from launcher.option import Option
from launcher.settings.settings_page import SettingsPage
from system.prefs.components.notworking import PrefsNotWorkingWarningPanel
class AudioSettingsPage(SettingsPage):
def __init__(self, parent: W... |
"""
edits mothur taxonomy summary file
transfers last name that is not "unclassified" or "uncultured" to "unclassified" or "uncultured" assignment
make sure that the file has default sorting (by rankID)
Copyright:
tax_summary_edit edits mothur taxonomy summary file
Copyright (C) 2016 William Brazelton
Thi... |
"""Base library classes.
These classes are the most basic library classes. As such they are the
least useful but most content-agnostic.
"""
import os
import shutil
import time
from gi.repository import GObject
from senf import fsn2text, fsnative
from quodlibet import _
from quodlibet.formats import MusicFile, AudioFile... |
import pytest
from roam_tests import objects
from roam.infodock import FeatureCursor, NoFeature
layer = objects.newmemorylayer()
layer = objects.addfeaturestolayer(layer, 2)
features = layer.getFeatures()
featureone = next(features)
featuretwo = next(features)
@pytest.fixture
def cursor():
return FeatureCursor(laye... |
def newusers(m):
dict_updater()
un = m.from_user.username
if un not in DBDIC:
uid = m.from_user.id
DBDIC[un] = [uid,0]
if hasattr(m, 'new_chat_participant'):
un = m.new_chat_participant.username
if un not in DBDIC:
uid = m.new_chat_participant.id
D... |
__version__ = "${API_EVENT_VERSION}"
__all__ = ["libevents"] |
import os
from enigma import eEPGCache, getBestPlayableServiceReference, \
eServiceReference, iRecordableService, quitMainloop, eActionMap
from Components.config import config
from Components.UsageConfig import defaultMoviePath
from Components.TimerSanityCheck import TimerSanityCheck
from Screens.MessageBox import Mes... |
from castle.cms.interfaces import IReferenceNamedImage
from plone.app.uuid.utils import uuidToObject
from persistent.mapping import PersistentMapping
from persistent.dict import PersistentDict
from lxml.html import fromstring
from lxml.html import tostring
from plone import api
from plone.app.blocks.layoutbehavior impo... |
import re
import sys
from rebasehelper.cli import CLI
from rebasehelper.archive import Archive
class Completion(object):
@staticmethod
def extensions():
archives = Archive.get_supported_archives()
return [a.lstrip('.') for a in archives]
@staticmethod
def options():
def get_delim... |
from __future__ import absolute_import
import itertools
import os
import posixpath
import random
import tempfile
import unittest
import silenttestrunner
from bindings import treestate
from edenscm.mercurial import pycompat
from hghave import require
testtmp = os.getenv("TESTTMP") or tempfile.mkdtemp("test-treestate")
d... |
Dependencies
Python2.7
Python Requests
python-rt https://gitlab.labs.nic.cz/labs/python-rt
(should have a local copy installed on tsbackup, unntested with newer versions)
jsondb
request_tracker
these last two are in the freegeek github repostitory
configure EMAIL, WEEKLYDB, MONTHLYDB on installed copy
use in cronjob wi... |
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):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('catalog', '0001_initial'),
]
... |
''' forms, mostly used for simple tastypie validation '''
from django.contrib.gis import forms
class MeetingForm(forms.Form):
''' form for meetings '''
day_of_week = forms.IntegerField(min_value=1, max_value=7)
start_time = forms.TimeField()
end_time = forms.TimeField()
name = forms.CharField(max_le... |
"""Common code for XMPP backends."""
import ipaddress
import logging
import random
import re
import string
import time
from datetime import datetime
from datetime import timedelta
from importlib import import_module
import pytz
from .constants import CONNECTION_HTTP_BINDING
from .constants import CONNECTION_UNKNOWN
fro... |
import uncertainties
from uncertainties import ufloat
import math
import numpy
import numpy
import pylab
from scipy.optimize import curve_fit
import math
import scipy.stats
def linear(x, a, b):
return a*x+b
def fitPassaBasso(x, f_0):
return 1/pylab.sqrt(1/(1+(x/f_0)^2))
Vout_o, dVout_o, f_o, df_o = pylab.loadtxt('/ho... |
import sepolicyanalysis.domain_grouping as grouping
import sys
def get_security_types():
try:
packages = set()
types = set()
exclude = set()
txt = open("/etc/sepolicyanalysis/security_related.conf", "r")
packages = {}
for line in txt:
if (len(line) < 1) or (line[0] == '#'):
continue
if line.start... |
import os
from pdfrw import PdfWriter, PdfReader, IndirectPdfDict, PdfName, PdfDict,PdfObject
INVOICE_TEMPLATE_PATH = 'templates/9_FP_GM_I_GS_AUTOBIS.pdf' # DOCUMENTO BASE
INVOICE_OUTPUT_PATH = 'invoice.pdf' #DESTINO
ANNOT_KEY = '/Annots'
ANNOT_FIELD_KEY = '/T'
ANNOT_VAL_KEY = '/V'
ANNOT_RECT_KEY = '/Rect'
SUBTYPE_KEY ... |
"""
Basic Twitter Authentication
requirements: Python 2.5+ tweepy (easy_install tweepy | pip install tweepy)
"""
__author__ = 'Bernie Hogan'
__version__= '1.0'
import string
import codecs
import os
import pickle
import copy
import sys
import json
import webbrowser
import tweepy
from tweepy import Cursor
import twitte... |
"""list all previously made bookings"""
import os
import sys
import cgi
import datetime
import json
import shuttle
import shconstants
import smtplib
import shcookie
print "Content-type: text/html\r\n"
shuttle.do_login(shcookie.u, shcookie.p)
form = cgi.FieldStorage()
if 'action' in form:
act = form.getvalue("action")... |
import random
import os
def createNewField():
result = []
for i in range(3):
tmp = []
for i2 in range(3):
tmp.append(' ')
result.append(tmp)
return result
def printField(field):
print ''
for element in field:
print element
print ''
def isFieldFull(field):
occupiedPlaces = 0
for row in field:
for pl... |
from __future__ import absolute_import
from __future__ import print_function
import sys
from os import kill
from os.path import join as pjoin
from os.path import split as psplit
from os.path import exists as pexist
import os
import socket
import string
from .getch import Getch
import random
import hashlib
import loggin... |
import re
from . import expression
class AssertionBase:
pass
class RowAssertion(AssertionBase):
def __init__(self, config, assert_config):
assert assert_config["type"] == "row"
self.config = config
self.assert_config = assert_config
def check(self, data):
if self.type == "eq"... |
from mmfparser.data.chunkloaders.actions.names import * |
import inkex
import inkscapeMadeEasy_Base as inkBase
import inkscapeMadeEasy_Draw as inkDraw
class myExtension(inkBase.inkscapeMadeEasy):
def __init__(self):
inkex.Effect.__init__(self)
self.OptionParser.add_option("--tab", action="store", type="string", dest="tab", default="object")
self.Op... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import sys
import os
sys.path.insert(0, os.path.join('ansible', 'lib'))
sys.path.append(os.path.abspath(os.path.join('..', '_extensions')))
sys.path.insert(0, os.path.abspath(os.path.join('..', '..', '..', 'lib')))
VERSION = '2.10'
... |
from sa_tools.base.magic import MagicMixin
from sa_tools.inbox import Inbox
from sa_tools.session import SASession
from sa_tools.index import Index
import os
import pickle
import sys
def py_ver() -> str:
return str(sys.version_info.major)
class APSession(object):
def __init__(self, username: str, passwd: str=No... |
from gnuradio import usrp1
import time,math
from usrpm import usrp_dbid
import db_base
import db_instantiator
from usrpm.usrp_fpga_regs import *
debug_using_gui = False # Must be set to True or False
TX_POWER = (1 << 0) # TX Side Power
RX_TXN = (1 << 1) # T/R antenna switch for TX/RX ... |
import socket
UDP_IP = '' # Leave empty for Broadcast support
ADMIN_PORT = 48899
INT_IP = '10.0.1.61'
INT_MAC = '111a02bf232b'
adminsock = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
adminsock.bind((UDP_IP, ADMIN_PORT))
while True:
admindata, adminaddr = adminsock.recvfrom(64) # buffer size is 64 bytes
# Di... |
import fstimer.fslogger
import fstimer.timer
from gi.repository import Gtk
def main():
pytimer = fstimer.timer.PyTimer()
Gtk.main()
if __name__ == '__main__':
main() |
import random
import uuid
from keystoneauth1 import exceptions
from keystoneauth1 import loading
from keystoneauth1.tests.unit.loading import utils
class V3PasswordTests(utils.TestCase):
def setUp(self):
super(V3PasswordTests, self).setUp()
self.auth_url = uuid.uuid4().hex
def create(self, **kwa... |
import re
from io import BytesIO
from typing import Optional, List
from telegram import MAX_MESSAGE_LENGTH, ParseMode, InlineKeyboardMarkup
from telegram import Message, Update, Bot
from telegram.error import BadRequest
from telegram.ext import CommandHandler, RegexHandler
from telegram.ext.dispatcher import run_async
... |
from abc import ABCMeta, abstractmethod
import csv
import os
import re
import subprocess
import sys
import plaid2text.config_manager as cm
from plaid2text.interact import separator_completer, prompt
class Entry:
"""
This represents one entry (transaction) from Plaid.
"""
def __init__(self, transaction, ... |
""" Hook specifications for tox.
"""
from pluggy import HookspecMarker, HookimplMarker
hookspec = HookspecMarker("tox")
hookimpl = HookimplMarker("tox")
@hookspec
def tox_addoption(parser):
""" add command line options to the argparse-style parser object."""
@hookspec
def tox_configure(config):
""" called after... |
"""
Provides classes that represent complete taxonomies, built using components from
the taxacomponents module.
"""
from taxacomponents import Citation, RankTable, Taxon
from taxonvisitor import TaxonVisitor
from taxonvisitors_concrete import PrintTaxonVisitor, CSVTaxonVisitor
from nameresolve import CoLNamesResolver
c... |
DEBUG = False
ALLOWED_HOSTS = [
'*',
]
LANGUAGE_CODE = 'fr-fr'
TIME_ZONE = 'Europe/Paris' |
from BaseOracle import *
from Factura import *
from ConfigDB import *
class CargaFacturaOracle(object):
def __init__(self):
pass
def carga(self, factura):
cfgOra = ConfigDB("oracle")
cfgOra.getConfig()
#cfgOra.imprimir()
oracle = BaseOracle(cfgOra.maquina, cfgOra.usuario,... |
import os
import math
FRAME_T_STATES = 69888
INTERRUPT_DELAY = 942
CONTENTION_FACTOR = 0.34
SKOOL_DAZE = 'skool_daze'
BACK_TO_SKOOL = 'back_to_skool'
SKOOL_DAZE_TAKE_TOO = 'skool_daze_take_too'
EZAD_LOOKS = 'ezad_looks'
BACK_TO_SKOOL_DAZE = 'back_to_skool_daze'
NOTES = {
'F0': -7,
'G0': -6,
'A1': -5,
'B... |
import functools
from nxtools import logging, log_traceback
from .utils import (
Qt,
QWidget,
QSlider,
QTimer,
QHBoxLayout,
QVBoxLayout,
QIcon,
RegionBar,
TimecodeWindow,
get_navbar,
)
try:
from .mpv import MPV
has_mpv = True
except OSError:
has_mpv = False
log_tr... |
import logging
import os
import statvfs
from gettext import gettext as _
from gi.repository import GObject
from gi.repository import Gio
from gi.repository import GLib
from gi.repository import Gtk
from gi.repository import Gdk
import cPickle
import xapian
import json
import tempfile
import shutil
from sugar3.graphics.... |
import logging, os
import psycopg2
database_name = 'postgres_database'
user = 'postgres_user'
password = 'some_password_here_lol'
port = 5432
host = 'postgres_host_normally_localhost'
path_to_gnaf_data = '/path/to/gnaf/data/'
logging.basicConfig(format='%(asctime)s %(levelname)s:%(message)s', level=logging.DEBUG)
def g... |
import time
import datetime
import Adafruit_DHT
log_path = "/var/log/iot/"
sensor = Adafruit_DHT.DHT11
pin = 23
def write_log(text):
log = open(log_path + datetime.datetime.now().strftime("%Y-%m-%d") + "_dht.log","a")
line = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") + " " + text + "\n"
log.write(line)
l... |
import server
import time
from Sensoria.stereotypes.TimeControlData import TimeControlData
from Sensoria.stereotypes.InstantMessageData import InstantMessageData
class TemperatureSensor (server.TemperatureSensor):
def __init__ (self):
super (TemperatureSensor, self).__init__ ("HD", "Heater Temperature")
class Heater... |
from unittest2 import TestCase
from mock import patch
class FakeSettings(object):
def __init__(self, **kwargs):
self.accessed = []
self.failed = []
self.values = {}
self.values.update(kwargs)
def __getattr__(self, attr):
try:
val = self.values[attr]
ex... |
"""setuptools based packaging and installation module.
Defines the project properties, as well as a special command to build a
standalone executable, by using PyInstaller.
Run with --help to see available options.
"""
from setuptools import setup, find_packages
from codecs import open
from os import path
import sys
imp... |
from django.core.urlresolvers import reverse
from django.core.mail import send_mail
from django.shortcuts import render, redirect
from django.contrib.auth.models import User
from django.contrib.auth.decorators import login_required
from .models import ActivateCode
import uuid
import os
from django.http import HttpRespo... |
'''
Author Joshua Pitts the.midnite.runr 'at' gmail <d ot > com
Copyright (C) 2013,2014, Joshua Pitts
License: GPLv3
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 ve... |
from django.http import HttpResponse
from django.core.cache import cache
from EventSubscriptions.models import EventWithSubscriptions
import requests
'''
This view provides the final result requested from the exercise. It first looks for it in the cache; if the result is
not there, it calls the class "EventWithSubscrip... |
from distutils.core import setup
from distutils.extension import Extension
from Cython.Distutils import build_ext
setup(name="ribify", version="0.0",
ext_modules = [Extension("ribify", ["rm_ribify.py"])]) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.