code stringlengths 1 199k |
|---|
from Components.ActionMap import ActionMap
from Components.config import config, ConfigInteger, ConfigSelection, ConfigSubsection, getConfigListEntry
from Components.ConfigList import ConfigListScreen
from Components.Label import Label
from Components.Language import language
from Components.MenuList import MenuList
fr... |
import sys, Ice, Test
def test(b):
if not b:
raise RuntimeError('test assertion failed')
def allTests(communicator):
sys.stdout.write("testing stringToProxy... ")
sys.stdout.flush()
base = communicator.stringToProxy("test:default -p 12010")
test(base)
print("ok")
sys.stdout.write("te... |
import re
from jaglt import *
from jaglf import *
''' Regexes '''
JRE_Num = [
re.compile(r"[0-8]+o"), #Octal
re.compile(r"[\dA-F]+x"), #Hex
re.compile(r"(?:-?\d+(?:\.(?:\d+)?)?|\.\d+|-?\d+)e-?\d+"), #Scientific
re.compile(r"-?\d+(?:\.(?:\d+)?)?|-?\.\d+"), #Decimal
]
JRE_Str = re.compile(r'"(... |
import ctypes, os, sys, unittest
from PySide.QtCore import *
from PySide.QtGui import *
import ScintillaCallable
sys.path.append("..")
from bin import ScintillaEditPy
scintillaDirectory = ".."
scintillaIncludeDirectory = os.path.join(scintillaDirectory, "include")
sys.path.append(scintillaIncludeDirectory)
import Face
... |
from functools import partial
from types import NoneType
from navmazing import NavigateToSibling, NavigateToAttribute
from cfme.exceptions import DestinationNotFound
from cfme.fixtures import pytest_selenium as sel
from cfme.provisioning import provisioning_form as request_form
from cfme.web_ui import (
Form, Selec... |
print "I could have code like this." # and the comment after is ignored
print "This will run."
print 'Q: Why does the "#" in "print "Hi # there." not get ignored?'
print "The # in that code is inside a string, so it will put into the string until the ending \" character is hit. These pound characters are just considere... |
import MDAnalysis
import matplotlib.pyplot as plt
import numpy as np
from MDAnalysis.analysis.align import *
from MDAnalysis.analysis.rms import rmsd
def ligRMSD(u,ref):
"""
This function produces RMSD data and plots for ligand.
:input
1) Universe of Trajectory
2) reference universe
:ret... |
{
"name": "VAT on payment",
"version": "2.0",
'category': 'Generic Modules/Accounting',
"depends": ["account_voucher_cash_basis"],
"author": "Agile Business Group",
"description": """
See 'account_voucher_cash_basis' description.
To activate the VAT on payment behaviour, this module adds... |
from struct import unpack
import os.path
from math import pi, sqrt
import bpy
from bpy_extras.object_utils import object_data_add
from mathutils import Vector,Matrix,Quaternion
from bpy_extras.io_utils import ImportHelper
from bpy.props import BoolProperty, FloatProperty, StringProperty, EnumProperty
from bpy.props imp... |
def mysql_read():
mysql_info = {}
with open('/etc/openstack.cfg', 'r') as f:
for i in f.readlines():
if i.split('=', 1)[0] in ('DASHBOARD_HOST',
'DASHBOARD_PASS',
'DASHBOARD_NAME',
... |
import pymongo
from scrapy.conf import settings
from scrapy.exceptions import DropItem
from scrapy import log
class MongoDBPipeline( object ):
def __init__( self ):
connection = pymongo.MongoClient(
settings[ 'MONGODB_SERVER' ],
settings[ 'MONGODB_PORT' ]
)
db = connection[settings[ 'MON... |
"""
* Copyright (c) 2017 SUSE LLC
*
* openATTIC 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; version 2.
*
* This package is distributed in the hope that it will be useful,
* but WITHOUT ANY W... |
import wx
from wx.lib import buttons
from gamera.gui import gamera_icons, compat_wx
if wx.Platform != '__WXMAC__' and hasattr(buttons, 'ThemedGenBitmapButton'):
ButtonClass = buttons.ThemedGenBitmapButton
ToggleButtonClass = buttons.ThemedGenBitmapToggleButton
else:
ButtonClass = buttons.GenBitmapButton
Tog... |
import json
import sys
import logging
import logging.handlers
def load_config():
'''Loads application configuration from a JSON file'''
try:
json_data = open('config.json')
config = json.load(json_data)
json_data.close()
return config
except Exception:
print """The... |
'''
Created on 14 Jun 2016
@author: gjermund.vingerhagen
'''
import numpy as np
import scipy.interpolate as intp
import linecache
import utmconverter as utm
def splitHead(inp):
return inp
def lineToArr(l1):
arra = np.array(np.fromstring(l1[144:1024],dtype=int,sep=' '))
for i in range(1,30):
arra = n... |
import os
from iconpacker import IconList
test_icon = "/media/hda7/Graphics/png/Classic_Truck/128.png"
icon_theme = IconList()
def initialization():
treestore = icon_theme.setup_treeview('data/legacy-icon-mapping.xml')
if treestore != None:
for i in icon_theme.icon_list:
icon_theme.set_item(i, test_icon)
retur... |
import os
import sys
import string
from SCons.Script import *
from utils import _make_path_relative
BuildOptions = {}
Projects = []
Rtt_Root = ''
Env = None
class Win32Spawn:
def spawn(self, sh, escape, cmd, args, env):
# deal with the cmd build-in commands which cannot be used in
# subprocess.Popen... |
from twisted.internet.threads import deferToThread as _deferToThread
from twisted.internet import reactor
class ConsoleInput(object):
def __init__(self, stopFunction, reconnectFunction):
self.stopFunction = stopFunction
self.reconnectFunction = reconnectFunction
def start(self):
self.ter... |
"""Deposit API."""
from __future__ import absolute_import, print_function
from flask import current_app
from invenio_pidstore.models import PersistentIdentifier
from invenio_indexer.api import RecordIndexer
from invenio_deposit.receivers import \
index_deposit_after_publish as original_index_deposit_after_publish
f... |
def f1(a, L=[]):
L.append(a)
return L
print(f1(1))
print(f1(2))
print(f1(3))
def f2(a, L=None):
if L is None:
L = []
L.append(a)
return L
print(f2(1))
print(f2(2))
print(f2(3))
def calc_sum(*numbers):
sum = 0
for i in numbers:
sum += i
return sum
print(calc_sum(1, 2, 3))
... |
from collections import namedtuple
try:
from .ip_connection import Device, IPConnection, Error, create_char, create_char_list, create_string, create_chunk_data
except (ValueError, ImportError):
from ip_connection import Device, IPConnection, Error, create_char, create_char_list, create_string, create_chunk_data... |
from neolib.plots.Step import Step
from neolib.NST import NST
import time
class HealPetPet(Step):
_paths = {
'links': '//*[@id="content"]/table/tr/td[2]//a/@href',
'img': '//*[@id="content"]/table/tr/td[2]/div/img/@src',
'cert': '//area/@href',
}
_HEALS = {
'http://images.neo... |
"""
multiprocessTask.py
~~~~~~~~~~~~~~~~~~~
a multiprocess model of producer/consumer
task = Task(work_func, 1, 3, counter=0, a='', callback=cb)
results = task.run()
for i in xrange(26):
lines = ["%d" % i] * random.randint(10, 20)
task.put(lines)
task.finish()
"""
import os
i... |
__doc__ = '''Netfarm Archiver - release 2.1.0 - XmlRpc backend'''
__version__ = '2.1.0'
__all__ = [ 'Backend' ]
from archiver import *
from sys import exc_info
from xmlrpclib import ServerProxy, Error
from urlparse import urlparse
from time import mktime
_prefix = 'XmlRpc Backend: '
class BadUrlSyntax(Exception):
"... |
import os # ÆÄÀÏ »èÁ¦¸¦ À§ÇØ import
import kernel
class KavMain :
#-----------------------------------------------------------------
# init(self, plugins)
# ¹é½Å ¿£Áø ¸ðµâÀÇ ÃʱâÈ ÀÛ¾÷À» ¼öÇàÇÑ´Ù.
#-----------------------------------------------------------------
def init(self, plugins) : # ¹é½Å ¸ð... |
from PySide import QtCore, QtGui
class Ui_Frame(object):
def setupUi(self, Frame):
Frame.setObjectName("Frame")
Frame.resize(237, 36)
Frame.setWindowTitle("")
self.gridLayout = QtGui.QGridLayout(Frame)
self.gridLayout.setSpacing(0)
self.gridLayout.setContentsMargins(0... |
import_templates = [{
'id': 'my_import',
'label': 'My Import (Trident)',
'defaults': [
('ds', '16607027920896001'),
('itt', '1'),
('mr', '1'),
('impstp', '1'),
('asa', '1'),
('impjun', '0'),
('dtd', '5'),
{
'id': 'dr',
'... |
from tablelist import * |
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('servicos', '0007_auto_20210416_0841'),
]
operations = [
migrations.AlterField(
model_name='servico',
name='data_ultimo_uso',
... |
from ..helpers import arguments
from ..helpers.command import Command
from ..helpers.orm import Permissions
@Command('acl', ['config', 'db'], role="owner")
def cmd(send, msg, args):
"""Handles permissions
Syntax: {command} (--add|--remove) --nick (nick) --role (admin)
"""
parser = arguments.ArgParser(ar... |
"""Gets information about the mesh of a case. Makes no attempt to manipulate
the mesh, because this is better left to the OpenFOAM-utilities"""
from PyFoam.RunDictionary.SolutionDirectory import SolutionDirectory
from PyFoam.RunDictionary.ListFile import ListFile
from PyFoam.Error import PyFoamException
from PyFoam.Run... |
import socket
import os
import time
import shutil
import sys
import re
import datetime
import argparse
import ncmd_print as np
from ncmd_print import MessageLevel as MessageLevel
import ncmd_commands as ncmds
import ncmd_fileops as nfops
MAX_TRANSFER_BYTES=2048
QUIT_CMD = "quit now"
HOST = ""
PORT = 10123
ROOT_DIR_PATH... |
"""auth for Users API
"""
from flask import abort
from flask.views import MethodView
from flask.ext.login import login_required, current_user
from sqlalchemy.exc import IntegrityError
from webargs.flaskparser import use_args
from . import users_bp
from ..mixins import RestfulViewMixin
from ...models.users import User
f... |
from console.main.command_handler.commands.command import Command
class SimpleCommand(Command):
pass |
import os
import sys
import configargparse
RESDIR = os.path.join(os.path.dirname(sys.modules[__name__].__file__), 'res')
CFG = {
'fontdir': os.path.join(RESDIR, 'fonts'),
'gfxdir': os.path.join(RESDIR, 'gfx'),
'webdir': os.path.join(RESDIR, 'web'),
}
def init_argparser():
configargparse.init... |
import glob
import os
import shutil
import tempfile
from oeqa.selftest.case import OESelftestTestCase
from oeqa.utils.commands import runCmd, bitbake, get_bb_vars
class oeGoToolchainSelfTest(OESelftestTestCase):
"""
Test cases for OE's Go toolchain
"""
@staticmethod
def get_sdk_environment(tmpdir_SD... |
"""This is the module for models used in Mentor GUI"""
import release
__author__ = '%s <%s>' % \
( release.authors['afolmert'][0], release.authors['afolmert'][1])
__license__ = release.license
__version__ = release.version
import sys
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from cards import ... |
from django.forms import ModelForm
from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
class UserLogin(ModelForm):
class Meta:
model = User
fields = ['username', 'password']
class UserRegister(UserCreationForm):
email = form... |
import os
import numpy as np
from scipy import stats
import matplotlib.pyplot as plt
from matplotlib import cm
import atmath
srcDir = '../runPlasim/postprocessor/indices/'
SRng = np.array([1263, 1265, 1270, 1280, 1300, 1330, 1360, 1435])
restartStateRng = ['warm']*8
firstYear = 101
lastYear = 4200
yearsPerFile = 100
da... |
import sys
import time
import subprocess
from java.io import File
from ucl.physiol.neuroconstruct.cell.utils import CellTopologyHelper
from ucl.physiol.neuroconstruct.cell.compartmentalisation import GenesisCompartmentalisation
from ucl.physiol.neuroconstruct.cell.compartmentalisation import OriginalCompartmentalisatio... |
from com.googlecode.fascinator.common import JsonSimple
class AuthtestData:
def __init__(self):
pass
def __activate__(self, context):
request = context["request"]
response = context["response"]
writer = response.getPrintWriter("text/javascript; charset=UTF-8")
result = Js... |
import sys
devlali = {}
def sum_number(number):
str_n = str(number)
total = 0
for n in str_n:
total += int(n)
return total + number
def generate_devlali():
for i in range(10001):
total = sum_number(i)
if (total in devlali.keys()):
tmp_list = devlali[total]
... |
import easyhistory
import pdSql_common as pds
from pdSql import StockSQL
import sys
import datetime
from pytrade_api import *
from multiprocessing import Pool
import os, time
import file_config as fc
import code
stock_sql_obj=StockSQL(sqlite_file='pytrader.db',sqltype='sqlite',is_today_update=True)
CHINESE_DICT = stock... |
import base64
import json
import re
import urllib
import urlparse
from openscrapers.modules import cleantitle
from openscrapers.modules import client
from openscrapers.modules import directstream
from openscrapers.modules import dom_parser
from openscrapers.modules import source_utils
class source:
def __init__(sel... |
import numpy as np
from sklearn.metrics import mean_squared_error as MSE
from sklearn.metrics import auc, roc_curve, roc_auc_score
def AUC(P, X ,testX = None):
score_in = []
score_out = []
for i in range(X.shape[0]):
Y = X[i]
predY = P[i]
try:
score_in.append(roc_auc_scor... |
import asjson
from flask.views import MethodView
from functools import wraps
from flask.ext.mongoengine.wtf import model_form
from flask import request, render_template, Blueprint, redirect, abort, session, make_response
from .models import User, SessionStorage
from mongoengine import DoesNotExist
auth = Blueprint('aut... |
import purchase_requisition |
import importlib
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured, ObjectDoesNotExist
from ckeditor_link import conf
from django import template
from django.template.defaultfilters import stringfilter
try:
module_name, class_name = conf.CKEDITOR_LINK_MODEL.rsplit(".", 1)
... |
try:
import RPi.GPIO as GPIO
from lib_nrf24 import NRF24
from math import *
import time
import spidev
import sys
import os.path
import numpy
import pickle
import sqlite3
import mat4py as m4p
import os
def compress(uncompressed):
"""Compress a string to a list of output symbols."""
# Build the dictionar... |
"""
***************************************************************************
extentSelector.py
---------------------
Date : December 2010
Copyright : (C) 2010 by Giuseppe Sucameli
Email : brush dot tyler at gmail dot com
**********************************... |
"""
Several methods to simplify expressions involving unit objects.
"""
from __future__ import division
from sympy.utilities.exceptions import SymPyDeprecationWarning
from sympy import Add, Function, Mul, Pow, Rational, Tuple, sympify
from sympy.core.compatibility import reduce, Iterable
from sympy.physics.units.dimens... |
"""
A pure Python implementation of the functionality of the ConvertTo-SecureString
and ConvertFrom-SecureString PoweShell commandlets.
Usage example:
from securestring import encrypt, decrypt
if __name__ == "__main__":
str = "My horse is amazing"
# encryption:
try:
enc = encrypt(str)
print(... |
import sip as __sip
class QTextStream(): # skipped bases: <class 'sip.simplewrapper'>
"""
QTextStream()
QTextStream(QIODevice)
QTextStream(QByteArray, QIODevice.OpenMode mode=QIODevice.ReadWrite)
"""
def atEnd(self): # real signature unknown; restored from __doc__
""" QTextStream.atEnd()... |
"""Convert flat XML files to Gettext PO localization files.
See: http://docs.translatehouse.org/projects/translate-toolkit/en/latest/commands/flatxml2po.html
for examples and usage instructions.
"""
from translate.convert import convert
from translate.storage import flatxml, po
class flatxml2po:
"""Convert a single... |
"""Basic quilt-like functionality
"""
__copyright__ = """
Copyright (C) 2005, Catalin Marinas <catalin.marinas@gmail.com>
This program 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.
This program is dist... |
import pygame
from transcendence.graphics.widget import Box
from transcendence.graphics.button import Button
from transcendence.graphics.progressbar import ProgressBar
import transcendence.graphics as graphics
from transcendence import util
class Slider(Box):
"""A slider widget presents a stepped sliding scale, beg... |
import GemRB
from GUIDefines import *
from ie_stats import *
import CharGenCommon
import GUICommon
import Spellbook
import CommonTables
import LUCommon
import LUProfsSelection
def Imprt():
GemRB.SetToken("NextScript","CharGen")
GemRB.SetNextScript("ImportFile") #import
return
def setPlayer():
MyChar = GemRB.GetVar ... |
from django.db import models
class Institution(models.Model):
name = models.CharField(max_length=50);
@property
def teams(self):
return Team.objects.filter(institution=self)
@property
def judges(self):
return Judge.objects.filter(institution=self)
def __str__(self):
retur... |
import math, sys, time
def drange(start, stop, step): #Generator for step <1, from http://stackoverflow.com/questions/477486/python-decimal-range-step-value
r = start
while r < stop:
yield r
r += step
class adaline:
def __init__(self, w_vec):#, bias): #absorbed
self.w_vec = w... |
""" Gecoaching.com python utility """
__filename__ = "gc_util.py"
__version__ = "0.0.3"
__author__ = "Albert Simenon"
__email__ = "albert@simenon.nl"
__purpose__ = "Utility to download pocket queries from www.geocaching.com"
__date__ = "20/12/2013"
import argparse
import os
import progressbar
import urllib2
... |
import os
import sys
import re
import json
import smtplib
import requests
from telegram import Bot
from bs4 import BeautifulSoup
from ConfigParser import SafeConfigParser
from random import randint
config_filename = '/etc/malioglasi.conf'
url = 'http://www.mobilnisvet.com/mobilni-malioglasi'
filename = '/var/tmp/mobiln... |
from __future__ import absolute_import, division, print_function, unicode_literals
"""
Name: AnalysisWinPIRALog_LINUX
Author: Andy Liu
Email : andy.liu.ud@hotmail.com
Created: 3/24/2015
Copyright: Copyright ©Intel Corporation. All rights reserved.
Licence: This program is fr... |
import nltk
import json
import sys
sys.path.append("../../")
import parser
from entity import Word
class ModelRewriter:
rewriteRules = None
rewriteRuleFileName = "model.txt"
@staticmethod
def loadModel():
inputFile = open("model.txt")
modelJsonString = inputFile.read()
inputFile.... |
__author__ = """Copyright Martin J. Bligh, 2006,
Copyright IBM Corp. 2006, Ryan Harper <ryanh@us.ibm.com>"""
import os, shutil, copy, pickle, re, glob
from autotest_lib.client.bin import kernel, kernel_config, os_dep, test
from autotest_lib.client.bin import utils
class xen(kernel.kernel):
def log(s... |
import scenarios.interfaces
import openwns.geometry.position
import math
class PositionListPlacer(scenarios.interfaces.INodePlacer):
"""
Place a number of nodes on the given positions.
"""
def __init__(self, numberOfNodes = 1, positionsList = [openwns.geometry.position.Position(1,1)], rotate = 0.0):
... |
import sys
import os
import re
from jhbuild.commands import Command, register_command
from jhbuild.utils.cmds import get_output, check_version
from jhbuild.errors import UsageError, CommandError
def get_aclocal_path():
data = get_output(['aclocal', '--print-ac-dir'])
path = [data[:-1]]
env = os.environ.get(... |
""" prepare run , split xml ,run case , merge result """
import traceback
import os
import platform
import time
import sys
reload(sys)
sys.setdefaultencoding('utf8')
import traceback
import collections
from datetime import datetime
from shutil import copyfile
import xml.etree.ElementTree as etree
import ConfigParser
fr... |
from pwn import *
import time
host = "10.211.55.6"
port = 8888
host = "ch41l3ng3s.codegate.kr"
port = 3333
r = remote(host,port)
def sell(idx):
r.recvuntil(">>")
r.sendline("S")
r.recvuntil(">>")
r.sendline(str(idx))
r.recvuntil("?")
r.sendline("S")
def buy(size,name,pr):
r.recvuntil(">>")
... |
from django.db import models
class TempMail(models.Model):
mailfrom = models.EmailField()
mailsubj = models.CharField(max_length=20)
mailrcvd = models.DateTimeField()
mailhdrs = models.CharField()
class SavedMail(models.Model):
mailrcvd = models.DateTimeField()
mailhdrs = models.CharField()
... |
import shutil, os
from client import SpreadsheetClient
if __name__ == "__main__":
"""This script shows how the differnet functions exposed by client.py can be
used."""
EXAMPLE_SPREADSHEET = "example.ods"
# Copy the example spreadsheet from the tests directory into the spreadsheets
# directory
sh... |
from .JSClass import JSClass
class Crypto(JSClass):
def __init__(self):
pass
@property
def enableSmartCardEvents(self):
return False
@property
def version(self):
return "2.4"
def disableRightClick(self):
pass
def importUserCertificates(self, nickname, cmmfResp... |
import gzip
import http.server
import sys
class PrintingHTTPRequestHandler(http.server.BaseHTTPRequestHandler):
def do_PUT(self):
print(self.path, flush=True)
content_encoding = self.headers['X-Endless-Content-Encoding']
print(content_encoding, flush=True)
content_length = int(self.h... |
import gtk
import gtk.gdk as gdk
import gobject
import pango
import gtk.keysyms as _keys
import code
import sys
import keyword
import re
def _commonprefix(m):
"Given a list of pathnames, returns the longest common leading component"
if not m: return ''
prefix = m[0]
for item in m:
for i in range... |
from lib.inductor.rf import sp as Sp
from syntax import *
from functions.science import linspace
@setenv(type='bench', name='sp1')
class sp1():
def __init__(self, **parameters):
ls = parameters.get('ls', 1e-9)
rs = parameters.get('rs', 1.0)
cp = parameters.get('cp', 150e-15)
cs = par... |
import re
import sys
import copy
import types
import inspect
import keyword
import builtins
import functools
import _thread
__all__ = ['dataclass',
'field',
'Field',
'FrozenInstanceError',
'InitVar',
'MISSING',
# Helper functions.
'fields',
... |
import sys
import os
from django.test import TestCase, override_settings, Client
from django.conf import settings
from ..conf import (DatabaseUndefined, validate_database,
InaccessibleSettings, _load_py_file, load_py_settings,
load_colab_apps, load_widgets_settings)
from mock imp... |
import os
import sys
from twisted.internet import reactor, stdio
from twisted.python import log
from twisted.python.log import ILogObserver, FileLogObserver
from twisted.python.logfile import DailyLogFile
from modules.CloudAtCostConsole import CloudAtCostConsole
sys.dont_write_bytecode = True
log_path = os.path.di... |
from django.db import models
class Author(models.Model):
first_name = models.CharField(max_length = 100)
last_name = models.CharField(max_length = 100)
date_of_birth = models.DateField()
profile_photo = models.ImageField(upload_to="media")
linkedin_link = models.URLField(max_length=250)
personal... |
x = 2
cont = 0
while x >= 0:
y = 0
while y <= 4:
print(y)#comando qualquer
y = y - 1
x = x - 1 |
import pcl
p = pcl.PointCloud()
p.from_file("test_pcd.pcd")
fil = p.make_statistical_outlier_filter()
fil.set_mean_k (50)
fil.set_std_dev_mul_thresh (1.0)
fil.filter().to_file("inliers.pcd") |
from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'metuly.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
url(r'^admin/', include(admin.site.urls)),
url(r'^accounts/login/$'... |
import freenect
import signal
import matplotlib.pyplot as mp
from misc.demo import frame_convert
mp.ion()
image_rgb = None
image_depth = None
keep_running = True
def display_depth(dev, data, timestamp):
global image_depth
data = frame_convert.pretty_depth(data)
mp.gray()
mp.figure(1)
if image_depth:... |
import csv
from read_conf import config
import MySQLdb as mysql
conn = mysql.connect(host='localhost',user='root',passwd='111111111',port=3306)
cur = conn.cursor()
def create_db():
count = cur.execute('create database if not exists shopping;')
print "create database",count
result = cur.fetchmany(count)
... |
import sys
from pathlib import Path
from analysis.PluginBase import AnalysisBasePlugin
from plugins.mime_blacklists import MIME_BLACKLIST_COMPRESSED
try:
from ..internal.string_eval import eval_strings
except ImportError:
sys.path.append(str(Path(__file__).parent.parent / 'internal'))
from string_eval impor... |
""" configuration module for awsu, contains two objects """
import boto3
import sqlite3
import logging
import getpass
import datetime
import configparser
import uuid
import requests
import json
from dateutil.tz import tzutc
from urllib.parse import urlencode, quote_plus
from os import environ
from bs4 import BeautifulS... |
from distutils.core import setup
from program_version import RELEASE
setup(name='program',
version=RELEASE,
description='A self updating program example',
author='Mr Snow',
author_email='ninja@snow.com',
url='https://github.com/mr-ninja-snow/Self-Updating-Python-Program.git',
package... |
import unittest
import os
import collections
import mock
import accurev.client
import accurev.depot
class TestAccuRevClient(unittest.TestCase):
def setUp(self):
self.client = accurev.client.Client()
def test_cmd(self):
self.client.chdir('somedirectory')
expected = "accurev somecommand"
... |
"""
Algorithmic Thinking 1
wk 4
Aplication #2
Questions
"""
import urllib2
import random
import time
import math
import UPATrial
import numpy
from collections import deque
import matplotlib.pyplot as plt
def copy_graph(graph):
"""
Make a copy of a graph
"""
new_graph = {}
for node in graph:
... |
import pandas as pd
import numpy as np
from axiomatic.base import AxiomSystem
from axiomatic.elementary_conditions import MinMaxAxiom
params = [1, 1, -0.8, 0.8]
axiom_list = [MinMaxAxiom(params)]
ts = pd.DataFrame(np.random.random((10, 2)))
print(ts)
print(MinMaxAxiom(params).run(ts, dict()))
now = AxiomSystem(axiom_... |
import os.path
import re
import warnings
try:
from setuptools import setup, find_packages
except ImportError:
from distribute_setup import use_setuptools
use_setuptools()
from setuptools import setup, find_packages
version = '0.2.1'
news = os.path.join(os.path.dirname(__file__), 'docs', 'news.rst')
news... |
a, b="cagy",3
e = []
for i in range(0,len(a)):
c = ord(a[i])+b # 转换成整数
if c> 122: # 如果大于z则减去26
c -= 26
e.append(chr(c)) # 加入到列表中
str = "".join(e) # 列表和并成字符串
print str |
from static import tools
class DrawAble(object):
def __init__(self,image,position,zIndex=0,activated=True):
self.image=image
self.position=position
self._zIndex=zIndex
self.__activated=None
self.activated=activated
def __del__(self):
self.activated=False
def __getZIndex(self):
return self._zIn... |
class App:
""" A representation of an Android app containing basic knowledge about the app """
def __init__(self, appName, appID, appVersionCode, appOfferType, appRating, appPrice, appSize):
self.appName = appName
self.appID = appID
self.appVersionCode = appVersionCode
self.appOf... |
"""
ctf.py -- contrast transfer function in electron tomography
Copyright 2014 Holger Kohr
This file is part of tomok.
tomok 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 ... |
bg_image_modes = ('stretch', 'tile', 'center', 'right', 'left')
transitions_jquery_ui = (
'blind', 'bounce', 'clip', 'drop', 'explode', 'fade', 'fold',
'highlight', 'puff', 'pulsate', 'scale', 'shake', 'size', 'slide'
)
transitions_animatecss = (
'bounceIn',
'bounceInDown',
'bounceInLeft',
'boun... |
"""
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 program is distributed in the hope that it will be useful,
but WITHOUT ... |
string = input()
string[0] = "a" |
import os
import unittest
from vsg.rules import generate
from vsg import vhdlFile
from vsg.tests import utils
sTestDir = os.path.dirname(__file__)
lFile, eError =vhdlFile.utils.read_vhdlfile(os.path.join(sTestDir,'rule_015_test_input.vhd'))
lExpected = []
lExpected.append('')
utils.read_file(os.path.join(sTestDir, 'rul... |
from gettext import gettext as _
from checkbox.plugin import Plugin
from checkbox.properties import String
final_text = String(default=_("Successfully finished testing!"))
class FinalPrompt(Plugin):
def register(self, manager):
super(FinalPrompt, self).register(manager)
# Final should be prompted fi... |
from enum import Enum
from typing import Union, List, Optional
from .space2d import *
from .space3d import *
class JoinTypes(Enum):
"""
Enumeration for Line and Segment type.
"""
START_START = 1 # start point coincident with start point
START_END = 2 # start point coincident with end point
E... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.