code
stringlengths
1
199k
"""Unit tests for ORM models """
from unittest import TestCase from nba_data.nba_stats_api_utils.query_parameter_generator import League class TestLeague(TestCase): def test(self): self.assertEquals(League.get_query_parameter_name(), "LeagueId")
from xlr_xldeploy.XLDeployClientUtil import XLDeployClientUtil xld_client = XLDeployClientUtil.create_xldeploy_client(xldeployServer, username, password) xld_client.create_folder_tree(folderID, folderType)
from django.urls import path, register_converter from shared.utils import BigIntConverter from . import views app_name = 'taxonomy' register_converter(BigIntConverter, 'bigint') urlpatterns = [ # ------------------------------------------------------------------------# # Tasks path('tasks/update-taxon/', vi...
from flask import Blueprint, jsonify, abort, request, make_response from Authentication.Authentication import * from util import * api_stocks = Blueprint('api_stocks', __name__) @api_stocks.route("/stocks", methods=['GET']) @auth.login_required def get_stocks(): documentStocks = db.stocks stocks = [] for stock in do...
import datetime import ast import tornado.gen import bson from bson.objectid import ObjectId import motor import twcommon.misc import twcommon.localize from twcommon import wcproto from twcommon.excepts import MessageException, ErrorMessageException class Command: # As commands are defined with the @command decorat...
import _plotly_utils.basevalidators class DyValidator(_plotly_utils.basevalidators.NumberValidator): def __init__(self, plotly_name="dy", parent_name="scattergl", **kwargs): super(DyValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, edit_type=kwa...
import os import time import tornado.web import tornado.ioloop import tornado.curl_httpclient from tornado.escape import json_decode from tornado.testing import AsyncHTTPTestCase from tortik.page import RequestHandler def first_preprocessor(handler, callback): def handle_request(response): handler.first = T...
import numpy from gnuradio import gr,blocks from satisfi import ax25 from math import pi import pmt from gnuradio import digital import sys import time import tnc import array AX25_MAX_PAYLOAD = 200 class ax25_deframer(gr.sync_block): """ docstring for block ax25_framer """ def __init__(self,mycall,verb...
from participantCollection import ParticipantCollection import re import datetime import pyperclip nextMonthURL = "https://www.reddit.com/r/pornfree/comments/e4i39l/stay_clean_december_this_thread_updated_daily/" currentMonthIndex = datetime.date.today().month - 1 if currentMonthIndex == 0: currentMonthIndex = 12 c...
from unittest import mock from django.http import HttpResponse from django.test import TestCase from account.decorators import login_required @login_required def mock_view(request, *args, **kwargs): return HttpResponse("OK", status=200) class LoginRequiredDecoratorTestCase(TestCase): def test_authenticated_user...
import sys import os import datetime import re import scanner_controller import dm_reader import matplotlib as mpl import importlib importlib.reload(scanner_controller) importlib.reload(dm_reader) try: import settings importlib.reload(settings) except ImportError: import settings_template as settings os.chd...
from __future__ import division from __future__ import print_function from __future__ import unicode_literals import numpy as np import scipy.special as special import scipy.stats as st from mipframework import Algorithm, AlgorithmResult, TabularDataResource from mipframework.constants import P_VALUE_CUTOFF, P_VALUE_CU...
import json from flask import Flask, current_app, jsonify, request from subprocess import check_output database = { 'repositories': [{ 'id': '12345', 'name': 'swift-webui', 'activeBranch': 'master' }, { 'id': '67890', 'name': 'koala', 'activeBranch': 'master' ...
""" @author: Jeff Zhang @date: 2017-08-30 """ import numpy as np import matplotlib.pyplot as plt import sys sys.path.append('..') from UnsupervisedLearning.KMeans import KMeans def createGaussSample(mu, Sigma, Num): x, y = np.random.multivariate_normal(mu, Sigma, Num).T return np.array([x, y]).T def getTestDa...
from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('POInvoice', '0003_document'), ] operations = [ migrations.AddField( model_name='document', name='invoice_key', field=...
from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('recipe_book', '0012_auto_20161107_2033'), ] operations = [ migrations.AddField( model_name='recipe', ...
__program__ = "epub test" __version__ = "0.0.0" import markdown import epubgen import re LangAbbr = { 'English':'en', 'Korean':'ko' } seccnt = 0 xcmap = {} # TOC map: chapter ID to filename xcfilename = '' # inform processed file name def fix_toc_anchor(match): global xcfilename if match.group(1) a...
import pandas as pd from plotly import graph_objs as go def create( df: pd.DataFrame, values, x_values=None ): """ :param df: :param values: :param x_values: :return: """ traces = [] df = df.copy() # type: pd.DataFrame if isinstance(values, str): df['...
from __future__ import absolute_import, division, print_function, unicode_literals from builtins import ascii, bytes, chr, dict, filter, hex, input, int, map, next, oct, open, pow, range, round, str, super, zip import configparser import collections import numpy as np import heapq import time import timeit import json ...
import email import imaplib import sys, os import re import datetime def get_all_attach(username, password, server): detach_dir = '.' if 'attachments' not in os.listdir(detach_dir): os.mkdir('attachments') mail = imaplib.IMAP4_SSL(server) typ, accountDetails = mail.login(username, password) ...
import os, sys, inspect cmd_folder = os.path.realpath(os.path.abspath(os.path.split(inspect.getfile( inspect.currentframe() ))[0])) if cmd_folder not in sys.path: sys.path.insert(0, cmd_folder) subf = "pybitcoin" cmd_subfolder = os.path.realpath(os.path.abspath(os.path.join(os.path.split(inspect.getfile( inspect.cu...
from distutils.core import setup from distutils.command.install import install from distutils.command.install_data import install_data from distutils.command.build_ext import build_ext from distutils.command.clean import clean import os import shutil from zipfile import ZipFile import sys from digitaledition_jekyllthem...
import struct import pymodbus.client.sync import binascii import time import sys import requests def read_float_reg(client, basereg, unit=1) : resp = client.read_input_registers(basereg,2, unit=1) if resp == None : return None return struct.unpack('>f',struct.pack('>HH',*resp.registers)) def fmt_or_...
"""Test `Bidi Paired Bracket Type`.""" import unittest from backrefs import uniprops import re class TestBidiPairedBracketType(unittest.TestCase): """Test `Bidi Paired Bracket Type` access.""" def test_table_integrity(self): """Test that there is parity between Unicode and ASCII tables.""" re_ke...
""" Some helper functions for more readable bits and bytes. """ import math def byte_formatter(value): """ Gets a large integer als value and returns a tuple with the value as float and the matching dimension as string, i.e. >>> byte_formatter(242981246) (242.981246, 'MB') Expects positive integ...
import tpdp class PythonModifier(tpdp.ModifierSpec): def AddHook(self, eventType, eventKey, callbackFcn, argsTuple ): self.add_hook(eventType, eventKey, callbackFcn, argsTuple) def ExtendExisting(self, condName): self.extend_existing(condName) def AddItemForceRemoveHandler(self): # in charge of backing up condit...
from MyTasksUI import MyTasksUI
""" This sample illustrates a simple LLVM IR -> PTX compiler implemented using libNVVM. All command-line options are passed along to libNVVM. Arguments that start with '-' are assumed to be options and are passed along accordingly. Otherwise, options are treated as file names and are read as IR input(s). All inputs wil...
"""Creates database session""" from database_setup import Base from sqlalchemy.orm import sessionmaker from sqlalchemy import create_engine engine = create_engine('sqlite:///catalog.db') Base.metadata.bind = engine make_session = sessionmaker(bind=engine) dbsession = make_session()
''' '''
from logging import debug from cli_ui import warning, fatal from gitlabform import EXIT_INVALID_INPUT from gitlabform.gitlab import GitLab, AccessLevel from gitlabform.processors.abstract_processor import AbstractProcessor class GroupMembersProcessor(AbstractProcessor): def __init__(self, gitlab: GitLab): s...
import os from ii_functions import * check_dirs() echolist=os.listdir(indexdir) newdir=os.path.join(cwd, "echo_new/") if not os.path.exists(newdir): os.makedirs(newdir) for echo in echolist: print("doing "+echo) msgids=getMsgList(echo) msgs={} for msgid in msgids: msg=getMsg(msgid) msg["time"]=int(msg["time"])...
import os path = os.path.dirname(os.path.realpath(__file__)) sbmlFilePath = os.path.join(path, 'MODEL1407050000.xml') with open(sbmlFilePath,'r') as f: sbmlString = f.read() def module_exists(module_name): try: __import__(module_name) except ImportError: return False else: return...
import numpy as np import sys, os import scipy.stats import struct import os.path import datetime as dt from datetime import datetime from matplotlib.dates import date2num,num2date from netCDF4 import Dataset from netCDF4 import stringtoarr # for putting strings in as netCDF variables from scipy.io import netcdf import...
import sys from stem.util.connection import get_connections, get_system_resolvers from stem.util.system import get_pid_by_name resolvers = get_system_resolvers() if not resolvers: print "Stem doesn't support any connection resolvers on our platform." sys.exit(1) picked_resolver = resolvers[0] # lets just opt for t...
""" Helper functions for building and running test suites. """ __revision__ = "$Id$" CFG_TESTUTILS_VERBOSE = 1 import os import sys import time import unittest2 import cgi import subprocess from warnings import warn from urlparse import urlsplit, urlunsplit from urllib import urlencode from itertools import chain, repe...
import gi gi.require_version('Gtk', '3.0') from gi.repository import Gtk from gi.repository import GObject from gi.repository import GLib from gi.repository import Gdk from gi.repository import Pango import logging from functools import reduce from zim.plugins import PluginClass from zim.actions import radio_action, ra...
class Solution: # @param root, a tree node # @return a list of lists of integers def levelOrder(self, root): queue, res = [], [] if not root : return res queue.append((root, 0)) while len(queue) : cur = queue.pop(0) if len(res) < cur[1]+1 : res.append(...
""" AUTHOR: Brendan Harmon <brendan.harmon@gmail.com> PURPOSE: Parallel processing of a dynamic landscape evolution model COPYRIGHT: (C) 2017 Brendan Harmon LICENSE: This program is free software under the GNU General Public License (>=v2). """ import os import sys import atexit from multiprocessing i...
''' This study is a Bogazici University - NETAS Nova V-Gate collaboration and funded by TEYDEB project "Realization of Anomaly Detection and Prevention with Learning System Architectures, Quality Improvement, High Rate Service Availability and Rich Services in a VoIP Firewall Product'', by the Scientific and Technologi...
import gi gi.require_version('CScreensaver', '1.0') from gi.repository import GLib import signal import argparse import gettext import shlex from enum import IntEnum from subprocess import Popen, DEVNULL from dbusdepot.screensaverClient import ScreenSaverClient import config from util import settings signal.signal(sign...
from __future__ import absolute_import import os import pwd import importlib import distro import psutil from sys import version_info from tracer.resources.PackageManager import PackageManager from tracer.resources.processes import Process class System(object): @staticmethod def distribution(): """ Checks if /etc...
import os from getpass import getuser class Paths(object): base = '/var/www/hspipeline/web' bins = '/home/adamw/bin' data = '/home/adamw/seq_data' output = os.path.join(data, 'output') r = '/var/www/hspipeline' def __init__(self, proj=None, anc=None, ref=None): self.outlog = '' s...
"""Setup the testExp application""" import logging from tg import config from testexp import model import transaction def bootstrap(command, conf, vars): """Place any commands to setup testexp here""" # <websetup.bootstrap.before.auth from sqlalchemy.exc import IntegrityError try: u = model.User...
from read_data import * import matplotlib.pyplot as plt import numpy as np import csv plot_title = "primary forest" depth, C_content, C_se, d13C, d13Cse = read_data(Folder_File = 'Raw_Data/forest.csv') from scipy.optimize import curve_fit def func(x, a, b, c): return a*np.exp(-b*x) + c def interpolation(): glob...
from Tkinter import * root = Tk() scrollbar = Scrollbar(root) scrollbar.pack(side=RIGHT, fill=Y) listbox = Listbox(root) listbox.pack() for i in range(100): listbox.insert(END, i) listbox.config(yscrollcommand=scrollbar.set) scrollbar.config(command=listbox.yview) mainloop()
from spectral_cube import SpectralCube import cloudpca from scipy.interpolate import UnivariateSpline s = SpectralCube.read('/Users/erik/Dropbox/AstroStatistics/ngc1333.13co.fits') s = s[100:,:,:] evals,evec,matrix = cloudpca.pca(s) ll = cloudpca.EigenImages(evec,s) acorImg = cloudpca.AutoCorrelateImages(ll) acorSpec =...
import yaml CONFIG = dict() def configure(filename): global CONFIG CONFIG.update(yaml.load(file(filename).read()))
import urllib2 import BeautifulSoup import bitly_api from itertools import islice class bookInfo: def __init__(self,book_author,book_name): self.name = book_name self.author = book_author self.publisher = None self.pages = None self.format = None self.year = None self.dlink = list() def setAuthor(self,b...
from collections import deque from collections import namedtuple import threading import logging log = logging.getLogger("heimdall.threadpools") class ThreadPool(object): def append(self, runnable, callback, *args, **kwargs): pass WorkItem = namedtuple("WorkItem", [ "runnable", "callback", "priority", "args...
import logging import os import base64 import tempfile import stat from xen.xend.XendLogging import log from xen.util import mkdir import unittest class scheme_error(Exception): def __init__(self, value): self.value = value def __str__(self): return repr(self.value) class scheme_data: @stati...
"""Class for processing the state of display checkboxes in IesGui.""" __author__ = "Ganesh N. Sivalingam <g.n.sivalingam@gmail.com" from AmphitriteEnums import * class IesCheckboxStates(): def __init__(self): self.atds = False self.contourPlots = False self.conformations = False self...
import redis import time r = redis.StrictRedis(host='192.168.99.100', port=6379, db=0) p = r.pubsub() p.subscribe('queue') for i in range(1,10000): r.publish('queue','data:'+i.__str__()) time.sleep(5) print i
import logging import flask from app.modules.yaml_config import ConfigObject from app.version import Version class LogValuesInjectorFilter(logging.Filter): __request_values = { 'request_host': 'host', 'request_path': 'path', 'request_url': 'url', 'request_method': 'method', '...
""" simpleTAL Interpreter Copyright (c) 2009 Colin Stewart (http://www.owlfish.com/) All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above cop...
"""Este modulo se encarga de generar los graficos de todas las tablas en la base de datos y guardarlos a disco""" from models.lista import lista_de_valores import matplotlib as mpl import matplotlib.pyplot as plt import numpy as np import datetime as dt import date import pylab import matplotlib import matplotlib.dates...
from django import forms class TopDatabasesForm(forms.Form): limit = forms.IntegerField(min_value=1) days = forms.IntegerField(min_value=1) percent = forms.FloatField(required=False) gbytes = forms.FloatField(required=False) def clean(self): cleaned_data = super(TopDatabasesForm, self).clean...
class nodo: izq , der, dato = None, None, 0 def __init__(self, dato): self.izq = None self.der = None self.dato = dato class arbolBinario: def __init__(self): self.raiz = None def agregarNodo(self, dato): # crea un nuevo nodo y lo devuelve return nodo(dato...
import re import urllib import urlparse import itertools import HTMLParser import json from resources.lib.modules import cleantitle from resources.lib.modules import client from resources.lib.modules import source_utils from resources.lib.modules import dom_parser class source: def __init__(self): self.prio...
""" Voluntary public-goods contribution games. """ import meanstat class CobbDouglasVCGame(meanstat.MeanStatisticGame): """ A symmetric public goods game with a Cobb-Douglas payoff specification, following, e.g., Andreoni (1993) """ def __init__(self, N, min_choice, max_choice, step_choice, omega, a...
import os, glob, json from omf import feeder output_dir = "/Users/austinchang/pycharm/omf/omf/data/Component" created = [] overwritten = [] not_overwritten = [] lacked_name = [] def main(src_directory, overwrite=False): dictionaries = read_glm_files(src_directory) for d in dictionaries: create_components(d, overwri...
""" Setup file for creating the filebrowser plugin """ __author__ = "Cody Precord" import sys try: from setuptools import setup except ImportError: print "You must have setup tools installed in order to build this plugin" setup = None if setup != None: setup( name='FileBrowser', version=...
import os basedir = os.path.abspath(os.path.dirname(__file__)) class Config: SECRET_KEY = os.environ.get('SECRET_KEY') or 'hard to guess string' SQLALCHEMY_COMMIT_ON_TEARDOWN = True FLASKY_MAIL_SUBJECT_PREFIX = '[Flasky]' FLASKY_MAIL_SENDER = 'Flasky Admin <flasky@example.com>' FLASKY_ADMIN = os.env...
import os, types import svntest __all__ = ['XFail', 'Skip'] class TestCase: """A thing that can be tested. This is an abstract class with several methods that need to be overridden.""" def __init__(self): # Each element is a tuple whose second element indicates benignity: # e.g., True means "can be ignor...
from Bio.Seq import Seq from ..search.hmmer.hmmer_seqio import iter_fasta_seqs def create_prots_file(infile, hits, outfile, translate, table): seqs_dict = {name:seq for name, seq in iter_fasta_seqs(infile)} with open(outfile, 'w') as OUT: for hit in hits: query = hit[0] query_no_...
import xbmc import xbmcplugin import xbmcaddon import xbmcgui import urllib import urllib2 import re import sys import os import time import socket from StringIO import StringIO import gzip module_log_enabled = False http_debug_log_enabled = False LIST = "list" THUMBNAIL = "thumbnail" MOVIES = "movies" TV_SHOWS = "tvsh...
import sys import os import tempfile from shutil import rmtree from os.path import join, basename, dirname, isdir, abspath from cStringIO import StringIO from logilab.common.testlib import TestCase, unittest_main, create_files from logilab.common.compat import reload from pylint import config from pylint.lint import Py...
from django.db import models from django.contrib.auth.models import User, Group from django.db.models.signals import post_save from django.dispatch import receiver from django.urls import reverse from curriculum.models import Semester, Course import hashlib import datetime class BasicInfo(models.Model): """ Thi...
from collections import OrderedDict from django.contrib import admin from edc_base.modeladmin.admin import BaseModelAdmin from edc_export.actions import export_as_csv_action from ..forms import SubjectRefusalForm from ..models import SubjectRefusal, SubjectEligibility class SubjectRefusalAdmin(BaseModelAdmin): form...
from __future__ import absolute_import from __future__ import print_function from future.builtins import range from future.utils import PY3 from future.utils import iteritems import os import re import textwrap import mock from twisted.internet import defer from twisted.trial import unittest from zope.interface import ...
import timeit from timeit import Timer from random import randrange def test(a,i): try : del a[i] except: pass for i in xrange(10000,1000001,10000): a = {j:None for j in xrange(i)} j = randrange(0,i/10) t = Timer("test(a,j)","from __main__ import test,j,a") p = t.timeit(number=100) print "%d , %5.5f"%(i,p)
""" ********************************************************************** GPL License *********************************************************************** 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 Found...
import operator sentinel = object() def fold(l, op, init_val=sentinel): """Generic fold operation.""" if not l: return init_val if init_val is not sentinel: return op(init_val, fold(l, op)) elif l[1:]: first, *rest = l return op(first, fold(rest, op)) else: re...
import sys import os import re import glob import xmltodict import json import yaml import copy import logging from argparse import ArgumentParser from argparse import RawDescriptionHelpFormatter from elasticsearch1 import Elasticsearch from collections import OrderedDict import datetime import dateutil.parser from ite...
import numpy as np import cv2 import sys from PIL import Image if __name__ == '__main__': try: file_name = sys.argv[1] except: print("Didn't give me a file...") file_name = "Lenna.png" def nothing(*arg): pass cv2.namedWindow('freak') cv2.createTrackbar('hess', 'freak', ...
""" OrderList is a list in which elements are sorted as the result of sort() function. OrderDict is a dict in which the value of the key is the instance of OrderList.The real values are stored in OrderList. Note that the OrderDict is Not the same as collections.OrderDict. Both of OrderList/Dict is used as the same as i...
''' 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...
import os from wic import kickstart from wic import msger from wic.utils import syslinux from wic.utils import runner from wic.utils.oe import misc from wic.utils.errors import ImageError from wic.pluginbase import SourcePlugin class RootfsPlugin(SourcePlugin): """ Create root partition and install syslinux boo...
"""Adding column to store edited_by and edited_on a issue comment Revision ID: 3b441ef4e928 Revises: 15ea3c2cf83d Create Date: 2015-12-03 12:34:28.316699 """ revision = '3b441ef4e928' down_revision = '15ea3c2cf83d' from alembic import op import sqlalchemy as sa def upgrade(): ''' Add the columns editor_id and edite...
from time import time import unittest from zope.interface import Interface import zope.component from zope.schema.interfaces import WrongType, WrongContainedType from zExceptions import Forbidden from zExceptions import BadRequest from Products.PloneTestCase import ptc from pmr2.oauth.interfaces import KeyExistsError f...
def LoadArticles(): id = 1; articles = [] # art = ClsArticle(id, "第一篇叽歪", "2014-06-24 19:00:18") art.add_tag("start") art.add_p("终于有个不是很像样但总归是完完全全属于自己的窝了。") art.add_p("过年的时候就开始有搭窝的想法到现在才有这么个不像样的东西,强烈鄙视一下自己的执行力。") art.add_p("以下是反省:") art.add_p("总想着先把窝搭起来,然后再填东西,很多想法没有记下来,前段时间一直纠结于整个网站该怎么设计,各种折腾各种不满意,不干正经事,净干些有的...
""" UEFI firmware image parsing and manipulation functionality usage: >>> parse_uefi_region_from_file(_uefi, filename, fwtype, outpath): """ __version__ = '1.0' import os import fnmatch import struct import sys import time import collections import hashlib import re import random import binascii import json from ch...
import unittest from qel import scripts from qel.quotation import Collection, Quotation class MergeTests(unittest.TestCase): def test_empty(self): # Should run silently and not raise an exception. qtcoll = Collection() newcoll = scripts.merge(qtcoll, qtcoll) self.assertTrue(len(newco...
import re GECOS_VALID = re.compile(r'^[^:]*$') PORTABLE_FS_CHARS = r'a-zA-Z0-9._-' _USERNAME_BASE = r'[a-zA-Z0-9._](([' + PORTABLE_FS_CHARS + r']{0,2})|([' + PORTABLE_FS_CHARS + r']{3}(?<!root))|([' + PORTABLE_FS_CHARS + r']{4,31})|([' + PORTABLE_FS_CHARS + r']{,30}\$))' USERNAME_VALID = re.compile(r'^' + _USERNAME_BAS...
""" Created by Zoltan Bozoky on 2014.09.08. Under GPL licence. Purpose: ======== * Extract certain PDBs out of the STR file """ import sys import os from disconf import fileio from disconf import path def save_one_pdb_file(NAME, folders, extentions, conformernumber): """ """ file_number, position = path.whi...
from django.conf.urls import patterns, include, url from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', # Examples: # url(r'^$', 'djapp.views.home', name='home'), # url(r'^blog/', include('blog.urls')), url(r'^admin/', include(admin.site.urls)), url(r'^time/$', 'djapp.vi...
import Components.Task from Screens.ChoiceBox import ChoiceBox from Screens.MessageBox import MessageBox from Screens.Screen import Screen from Screens.Standby import TryQuitMainloop from Components.About import about from Components.ActionMap import ActionMap from Components.Button import Button from Components.config...
from dnfpy.core.map2D import Map2D import numpy as np from dnfpyUtils.stats.trajectory import Trajectory class ActivationSize(Trajectory): """ Param : dx Input : 1) activationMap : map of the activation Output: a Limit cases: If only step activation for now """ def _c...
import os from vdsm import netinfo from network import errors from network.models import Bond, Bridge, IPv4, Nic, Vlan from network.models import _nicSort from testrunner import VdsmTestCase as TestCaseBase from testValidation import ValidateRunningAsRoot from nose.plugins.skip import SkipTest from monkeypatch import M...
import struct import re import sys import termios import functools import textwrap import fnmatch import traceback import inspect from IPython.core.magic import (Magics, magics_class, line_magic) from IPython.core.autocall import IPyAutocall from IPython.terminal.embed import InteractiveShellEmbed from traitlets.config...
""" Django settings for server 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__)) SECRET_KEY = '...
import gvizlib import gviz_api print "Content-type: application/json" print dataset = gvizlib.mysqlToJson('server','database','user','password','table') dataset.col2typedict = {"MinMax":"string","min":"number","max":"number"} dataset.dt = gviz_api.DataTable(dataset.col2typedict.items()) sql = """SELECT "MinMax",MIN(tem...
""" Utilities for calculating n-th backoff value. Examples ======== A basic linear backoff: >>> get_backoff = Backoff(Linear(), Factor(20), Truncate(100)) >>> [get_backoff(n + 1) for n in range(6)] [20, 40, 60, 80, 100, 100] We can use py:class:`datetime.timedelta` as our factor to create a linear backoff with 10 minut...
import argparse import MySQLdb import sys import time from colorama import init, Fore from datetime import datetime hostname, port, username, password = ['', '', '', ''] def sizeof_fmt(num, suffix='B'): """@todo: Docstring for sizeof_fmt :num: size in bytes :type num: int :suffix: str :type suffix: ...
""" *************************************************************************** doTranslate.py --------------------- Date : June 2010 Copyright : (C) 2010 by Giuseppe Sucameli Email : brush dot tyler at gmail dot com *****************************************...
import db import dbmethods import miscmethods import datetime versionno = "1.3.2" def GetLabel(localsettings, field): return localsettings.dictionary[field][localsettings.language] def GetCurrentVersion(): return versionno def CheckVersion(localsettings): success = False try: connection = db.GetConnection(locals...
class Context: STATE_PLAYING = "playing" STATE_CONNECT = "connecting" STATE_PAUSED = "paused" UNKNOWN_RADIO = C_("Unknown radio specified by URL", "Unknown radio") station = None state = None def __init__(self): self.resetSongInfo() def resetSongInfo(self): self.url = "" ...
import os, random, sys import vrok import time import threading def get_file_list(path): list = [] for dp, dn, fn in os.walk(path): for f in fn: filepath = os.path.join(dp, f) #print(filepath) if os.path.isfile(filepath) and (f.endswith("mp3") or f.endswith("MP3") or ...
job= rr.getJob() rrGlobal.writeLog(rrGlobal.logLvL.info, "Example Python script:\n I am job " +job.sceneName, "Hello Job Script") rrGlobal.writeLog(rrGlobal.logLvL.info, "Notify parameter ID: "+str(job.notifyFinishParam), "Hello Job Script")