content string |
|---|
"""
Unit test for treadmill.appcfg.configure
"""
import os
import pwd
import shutil
import tempfile
import unittest
import mock
import treadmill
import treadmill.services
from treadmill.appcfg import configure as app_cfg
from treadmill.apptrace import events
class AppCfgConfigureTest(unittest.TestCase):
"""Te... |
# -*- coding: utf-8 -*-
from south.utils import datetime_utils as datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding field 'Code.episode'
db.add_column(u'niqati_code', 'episode',
... |
# Python Cocos2d Game Development
# Part 1: Getting Started
# Tutorial: http://jpwright.net/writing/python-cocos2d-game-1/
# Github: http://github.com/jpwright/cocos2d-python-tutorials
# Jason Wright (<EMAIL>)
# Imports
from random import randint
import pyglet
from pyglet.window import key
import cocos
from coco... |
"""
Markdown.py
0. just print whatever is passed in to stdin
0. if filename passed in as a command line parameter,
then print file instead of stdin
1. wrap input in paragraph tags
2. convert single asterisk or underscore pairs to em tags
3. convert double asterisk or underscore pairs to strong tags
"""
imp... |
import wx
from logbook import Logger
import eos.db
from gui.fitCommands.helpers import restoreCheckedStates
from service.fit import Fit
pyfalog = Logger(__name__)
class CalcAddProjectedFitCommand(wx.Command):
def __init__(self, fitID, projectedFitID, amount, state=None):
wx.Command.__init__(self, True... |
from django import http
from unittest import mock
from urllib.parse import quote
from olympia.addons import decorators as dec
from olympia.addons.models import Addon
from olympia.amo.tests import TestCase, addon_factory
class TestAddonView(TestCase):
def setUp(self):
super(TestAddonView, self).setUp()
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
Copyright 2014-2015 Dake Feng, Peri LLC, <EMAIL>
This file is part of TomograPeri.
TomograPeri is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foun... |
# might be able to make this better by auto matching file names and directories
import re
import ntpath
import os.path
def path_leaf(path):
head, tail = ntpath.split(path)
return tail or ntpath.basename(head)
def replaceIdsInFiles(originalFilePath, targetFileFolder):
with open(originalFilePath) as origi... |
from odoo import fields, models, tools
class ReportStockQuantity(models.Model):
_name = "report.stock.quantity"
_auto = False
_description = "Stock Quantity Report"
date = fields.Date(string="Date", readonly=True)
product_tmpl_id = fields.Many2one(
comodel_name="product.template",
... |
# -*- coding: utf-8 -*-
"""ESEDB plugin related functions and classes for testing."""
from plaso.containers import sessions
from plaso.parsers import esedb
from plaso.storage.fake import writer as fake_writer
from tests.parsers import test_lib
class ESEDBPluginTestCase(test_lib.ParserTestCase):
"""ESE database-ba... |
"""Support running map reduce jobs using a manifest file to store the input paths."""
import logging
import luigi.task
from luigi import configuration
from edx.analytics.tasks.util.url import get_target_class_from_url, get_target_from_url, url_path_join
CONFIG_SECTION = 'manifest'
log = logging.getLogger(__name__)... |
import requests
try:
from urlparse import urlparse
from urllib import quote_plus
except ImportError:
from urllib.parse import urlparse
from urllib.parse import quote_plus
from contextlib import contextmanager
from flask import current_app
from compair.core import abort
from . import KalturaCore
class ... |
import requests
from django.conf import settings
from rest_framework import serializers
from rest_framework.validators import UniqueTogetherValidator
from server.chapters.serializers import ChapterSerializer
from server.riders.serializers import RiderSerializer
from server.rides.models import Ride, RideRiders
class ... |
import defragger
import logging
class Scheduler_FF:
def _sort_hosts_to_schedule(self, hosts_info, candidates, vmdata):
'''
@returns a list of pairs (rank, node_id) where node_id is in candidates and fits the vm
and the rank indicates the order in which the nodes are taken
'''
... |
from __future__ import division
from vistrails.core import debug
from vistrails.core.modules.basic_modules import Color
from vistrails.core.utils.color import rgb2hsv, hsv2rgb
class BaseLinearInterpolator(object):
def __init__(self, ptype, mn, mx, steps):
self._ptype = ptype
self._mn = mn
... |
"""
mov eax, off_xxxx
.
.
.
.
GetProcAddress
mov off_yyyy, eax
.
.
.
.
(repeat)
off_xxxx dd aApiName
Gets the ApiName, propagates the name to off_xxxx, gives the API name itself to off_yyyy, then redirects all refs to yyyy to the API name directly
"""
Message("start\n")
def skiplines(ea, x):
... |
import os
import argparse
import logging
logging.basicConfig(level=logging.DEBUG)
from common import find_mxnet, data, fit
from common.util import download_file
import mxnet as mx
def download_cifar10():
data_dir="data"
fnames = (os.path.join(data_dir, "cifar10_train.rec"),
os.path.join(data_dir,... |
from typing import Iterable
from airflow.exceptions import AirflowException
from airflow.hooks.base import BaseHook
from airflow.sensors.base import BaseSensorOperator
class SqlSensor(BaseSensorOperator):
"""
Runs a sql statement repeatedly until a criteria is met. It will keep trying until
success or fa... |
# -*- encoding:utf-8 -*-
#from flask_mail import Mail
# from flask_sqlalchemy import SQLAlchemy
# from flask_security import Security, SQLAlchemyUserDatastore
from flask import Flask
from mongoengine import connect
from flask_mongoengine import MongoEngine
from flask_debugtoolbar import DebugToolbarExtension
from .... |
import bitcoin.core
import bitcoin.core.script
importprotocol
importtransactions
import unittest
import unittest.mock
class TransactionBuilderTests(unittest.TestCase):
def setUp(self):
self.target = openassets.transactions.TransactionBuilder(10)
# issue_asset
def test_issue_asset_success(self):
... |
# -*- coding: utf-8 -*-
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 unique constraint on 'OTM1ModelRelic', fields ['instance', 'otm1_model_id', 'otm2_model_name']
db.c... |
from decimal import Decimal
import doctest
import unittest
from couchdb import design
from couchdb import old_mapping as mapping
from couchdb.tests import testutil
class DocumentTestCase(testutil.TempDatabaseMixin, unittest.TestCase):
def test_mutable_fields(self):
class Test(mapping.Document):
... |
"""
.. currentmodule: gdshortener
:synopsis: Module that enables the use of `is.gd - v.gd url shortener <http://is.gd/developers.php>`_.
"""
import HTMLParser
import urllib
import urllib2
import json
_V_GD_SHORTENER_URL_ = 'http://v.gd'
_IS_GD_SHORTENER_URL_ = 'http://is.gd'
class GDBaseException(Exception):
... |
import os
import unittest
import boto3
import pytest
from brume.template import Template
from moto import mock_s3
CONFIG = {
'region': 'eu-west-1',
'local_path': 'test_stack',
's3_bucket': 'dummy-bucket',
}
class TestTemplate(unittest.TestCase):
"""Test for brume.Template."""
def setUp(self):
... |
'''
test iam2 login by plain user
# 1 create project
# 2 create plain user
# 3 login in project by plain user
# 4 TODO:more operations
# 5 logout
# 6 delete
@author: rhZhou
'''
import zstackwoodpecker.test_util as test_util
import zstackwoodpecker.operations.account_operations as acc_ops
import zstackwoodpecker.opera... |
"""
Copyright 2016, Michael DeHaan <<EMAIL>>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, s... |
import urllib
from django.template.response import TemplateResponse
from django.core.exceptions import PermissionDenied
from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect, Http404
from django.utils.encoding import force_unicode
from django.utils.html import escape
from django.con... |
import mock
from oslo_config import cfg
from neutron.common import config as neutron_config
from neutron.plugins.ml2 import config as ml2_config
from neutron.tests import base
UCSM_IP_ADDRESS_1 = '1.1.1.1'
UCSM_USERNAME_1 = 'username1'
UCSM_PASSWORD_1 = 'password1'
UCSM_IP_ADDRESS_2 = '2.2.2.2'
UCSM_USERNAME_2 = 'us... |
# coding: utf-8
"""
Kubernetes
No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
OpenAPI spec version: v1.8.2
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from __future__ import absolute_import
import os
import sys
im... |
'''Datastream comparison classes for the ncreview tool.
This module contains the classes nessecary to perform a comparison of two
datastreams and output the resulting comparison report to a json file which
can be rendered by the web tool.
Recurring Attributes
A name attribute is the name of the object's correspond... |
from telemetry.core import util
from telemetry.page.actions import loop
from telemetry.unittest import tab_test_case
AUDIO_1_LOOP_CHECK = 'window.__hasEventCompleted("#audio_1", "loop");'
VIDEO_1_LOOP_CHECK = 'window.__hasEventCompleted("#video_1", "loop");'
class LoopActionTest(tab_test_case.TabTestCase):
def se... |
#!/usr/bin/env python
import time
import binascii
from bitcoin.core import COutPoint, CTxIn, CTxOut, CTransaction, CBlock
coinbase = "04ffff001d0104455468652054696d65732030332f4a616e2f32303039204368616e63656c6c6f72206f6e206272696e6b206f66207365636f6e64206261696c6f757420666f722062616e6b73"
scriptPubKeyHex = "4104678af... |
import json
import logging
from community_csdt.src.models import database
from community_csdt.src.models.register import register_public, register_student
class RegisterAccount(object):
def __init__(self, parent, name):
self.__parent__ = parent
self.__name__ = name
def __getitem__(self, key):... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Built-in modules #
# Internal modules #
# First party modules #
from plumbing.graphs import Graph
from plumbing.cache import property_cached
###############################################################################
class Multiplot(Graph):
"""
Similar to... |
__author__ = 'Robert Meyer'
import os # To allow file paths working under Windows and Linux
from pypet import Environment, Result, Parameter
def multiply(traj):
"""Example of a sophisticated simulation that involves multiplying two values.
:param traj:
Trajectory containing
the parameters i... |
"""
Django settings for osmaxx project.
For more information on this file, see
https://docs.djangoproject.com/en/1.10/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.10/ref/settings/
"""
# flake8: noqa
import os
from datetime import timedelta
import environ
fr... |
'''@file deepclustering_2and3spk_loss.py
contains the DeepclusteringFull2and3SpkLoss'''
import tensorflow as tf
import loss_computer
from nabu.neuralnetworks.components import ops
class Deepclustering2and3SpkLoss(loss_computer.LossComputer):
'''A loss computer that calculates the loss'''
def __call__(self, t... |
#!/usr/bin/python3
from flask import Flask, request, abort
import json
import requests
import hmac
import hashlib
import codecs
import logging, sys
bot_email = "<EMAIL>"
bot_name = "UC RSS Feed"
bearer = "N2NlY2MyODUtMzJmMi00YTY2LWFhNmUtNTU3ZGFjNGRmM2Y3YjE2MWRjNGQtZTc5"
bat_signal = "https://upload.wikimedia.org/wi... |
from GeoHealthCheck.probe import Probe
class HttpGet(Probe):
"""
Do HTTP GET Request, to poll/ping any Resource bare url.
"""
NAME = 'HTTP GET Resource URL'
DESCRIPTION = 'Simple HTTP GET on Resource URL'
RESOURCE_TYPE = '*:*'
REQUEST_METHOD = 'GET'
CHECKS_AVAIL = {
'GeoHealt... |
import mock
import mox
from oslo.config import cfg
from webob import exc
from nova.api.openstack.compute import extensions
from nova.api.openstack.compute import plugins
from nova.api.openstack.compute.plugins.v3 import block_device_mapping
from nova.api.openstack.compute.plugins.v3 import servers as servers_v3
from n... |
import datetime
QUIET = False
class Log:
NO_COLOR = False
LOG_IN_FILE = False
FILE = None
DEBUG = False
@classmethod
def set_nocolor_policy(cls, no_color):
cls.NO_COLOR = no_color
@classmethod
def set_debug_policy(cls, debug):
cls.DEBUG = debug
... |
"""
The goal for this module is to show that usually in our MQTT communication we will send messages to one recipient and
that same recipient will be sending messages back to us. This module also runs only on your PC and has very few todo
items. You will simply be setting your name and you will be selecting one perso... |
"""Some utility functions."""
def PowersetList(initial_set):
"""Computes the power set of a given set.
If the input is null, it returns the empty set.
"""
# The power set of the empty set has one element, the empty set.
result = [[]]
if initial_set:
for x in initial_set:
result.extend([subset +... |
import os
from tempfile import mkdtemp
from unittest import TestCase
from benchbase.main import main
import benchbase.sqlitext as aggregate
class FunctionalTestCase(TestCase):
@classmethod
def setUpClass(cls):
cls._test_dir = mkdtemp('_benchbase')
cls._db = os.path.join(cls._test_dir, 'bb.db'... |
from django.test import TestCase
from .requester import get_team_json, get_event_json
from .models import Team, Event
import requests_mock
import requests
from concurrent.futures import Future, ThreadPoolExecutor
from util.strutils import TemplateLike
import TBAW.resource_getter as resource_getter
# save() is inten... |
import numpy as np
import math
import abc
class KernelComputerType(object):
LINEAR = "linear"
POLYNOMIAL = "polynomial"
SQUARED_EXPONENTIAL = "squared exponential"
class KernelComputer(object):
__metaclass__ = abc.ABCMeta
def compute_kernel(self, vector_1, vector_2):
raise NotImplemente... |
import datetime
import os
import random
import string
import time
import unittest
from google.appengine.ext import db
from mapreduce import control
from mapreduce import hooks
from mapreduce import model
from mapreduce import test_support
from testlib import testutil
def random_string(length):
"""Generate a random... |
"""URL file for image based pages."""
from django.conf.urls import url
from django.contrib.auth.decorators import login_required
from imager_images.views import (LibraryView,
SinglePhotoView,
SingleAlbumView,
PhotoCreate,... |
from __future__ import absolute_import
import logging
from rest_framework import serializers, status
from rest_framework.response import Response
from sentry.api.base import DocSection
from sentry.api.bases.project import ProjectEndpoint
from sentry.api.decorators import sudo_required
from sentry.api.serializers imp... |
"""
Server side: open a socket on a port, listen for a message from a client,
and send an echo reply; forks a process to handle each client connection;
child processes share parent's socket descriptors; fork is less portable
than threads--not yet on Windows, unless Cygwin or similar installed;
"""
import os, time, sys... |
#!/usr/bin/python -u
#
# Indexes the examples and build an XML description
#
import string
import glob
import sys
try:
import libxml2
except:
sys.exit(1)
sys.path.insert(0, "..")
from apibuild import CParser, escape
examples = []
extras = ['examples.xsl', 'index.html', 'index.py']
tests = []
sections = {}
symb... |
# -*- coding: utf-8 -*-
#
# script for updating pdf files
# update.py updates the database (from the doctree)
# This script *must* complete successfully (exit code 0) before running update.py
# so that we can be sure that main.tex at least compiles under latex
import os, re, time, shutil, logging, subprocess
from dja... |
from __future__ import absolute_import, division, print_function
import re
from .core import common_subexpression
from .expressions import Expr
from .reductions import Reduction, Summary, summary
from ..dispatch import dispatch
from .expressions import dshape_method_list
from datashape import dshape, Record, Map, Un... |
import os
import json
import shutil
import tarfile
import unittest
from gpi import installer
class InstallerTest(unittest.TestCase):
def setUp(self):
self.current_dir = os.path.dirname(os.path.realpath(__file__))
self.test_dir = os.path.join(self.current_dir, 'testdir')
self.plugin_dir =... |
import re
import numpy as np
import pytest
from astropy.time import Time, conf, TimeYearDayTime
iso_times = ['2000-02-29', '1981-12-31 12:13', '1981-12-31 12:13:14', '2020-12-31 12:13:14.56']
isot_times = [re.sub(' ', 'T', tm) for tm in iso_times]
yday_times = ['2000:060', '1981:365:12:13:14', '1981:365:12:13', '202... |
# -*- coding: utf8 -*-
"""
Copyright 2014 Ryan Brown <<EMAIL>>
This file is part of taskforge.
taskforge is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of
the License, or (at your option... |
from django.db import models
from djangoratings.fields import RatingField
class Agency(models.Model):
name = models.CharField(max_length=100)
logo = models.ImageField(null=True, blank=True, upload_to="agencies_logos", height_field="logo_height", width_field="logo_width")
logo_width = models.PositiveInteger... |
'''
@author: xiaowing
@license: Apache Lincese 2.0
'''
import requests, json
from flask import render_template, session, request, redirect, abort, make_response
from app import app
import sys
sys.path.append('..')
import tinyssosdk
from tinyssosdk import tinyssocl
Tinysso_Server="http://localhost:5... |
"""Tests for tensorflow_graphics.datasets.features.voxel_feature."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import numpy as np
import tensorflow as tf
import tensorflow_datasets as tfds
from tensorflow_graphics.datasets.features import ... |
import sys
import os
import spinalcordtoolbox.metadata
from spinalcordtoolbox.reports.qc import generate_qc
from spinalcordtoolbox.utils.shell import SCTArgumentParser, Metavar, ActionCreateFolder, display_viewer_syntax
from spinalcordtoolbox.utils.sys import init_sct, run_proc, printv, __data_dir__, set_global_loglev... |
"""
python解释器扫描到class定义时只是扫描语义, 调用的type()函数创建的类
type函数可以返回一个类
metaclass-元类,可以定义一个类的模板
"""
# 定义将被绑定的函数,得带self
def fn(self, name='world'):
print('Hello, %s' % name)
# 使用type动态构造一个Hello类:
# 1.类名; 2.继承的父类集合,tuple类型;3.class的方法名称与函数的绑定,或者属性与值绑定,类型是dict
Hello = type('Hello', (object,), dict(hello=fn, fr='from type'))
... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('django_apogee', '0001_initial'),
('duck_utils', '__first__'),
]
operations = [
migrations.CreateModel(
n... |
#!/usr/bin/python -O
import json
import os
import re
import sys
import urllib2
from dreampylib.dreampylib import DreampyLib
import subprocess
CONF_PATH = '/etc/dreamhostdns.conf'
def getIP(ip_sources):
proc = subprocess.Popen(['ifconfig'], stdout=subprocess.PIPE)
proc.wait()
out = proc.stdout.read()
... |
import numpy as np
from lifetmm.TransferMatrix import TransferMatrix
def example1():
"""
Recreate calculations and plots in https://www.photonics.com/EDU/Handbook.aspx?AID=25501
"""
# Emission wavelength
lam0 = 850
# n @ lam0
n_h = 2.5
n_l = 1.46
n_s = 1.52
# Number of n_l la... |
from hashlib import sha1
from werkzeug.http import is_resource_modified
from flask import Response, request
from grano.core import app
class NotModified(Exception):
pass
@app.errorhandler(NotModified)
def handle_not_modified(exc):
return Response(status=304)
def generate_etag(keys):
args = sorted(se... |
from goldfinchlib.controllers import controller
import tweepy
import logging
import traceback
import os
import cPickle
class TwitterController(controller.Controller):
'''Makes use of the twitter API through 'tweepy'
http://github.com/joshthecoder/tweepy
'''
def __init__(self, cache_dir, config=None):
... |
from copy import deepcopy
from itertools import combinations
from .utility import *
from .representation import UGM, DGM
from .factors import Factor
from .data_preparation import DiscreteDataPreparer
class Inferencer:
def fit(self, graphical_model, **options):
raise NotImplementedError()
def prob(sel... |
from __future__ import unicode_literals
from decimal import Decimal
from django.core.urlresolvers import reverse
from model_mommy import mommy
from base.utils import BaseTestCase
class DashboardViewTest(BaseTestCase):
from dashboard.views import dashboard
view_function = dashboard
def test_view_redi... |
import errno
import re
import socket
import time
from mcrouter.test.MCProcess import Memcached
from mcrouter.test.McrouterTestCase import McrouterTestCase
from mcrouter.test.mock_servers import ConnectionErrorServer
from mcrouter.test.mock_servers import CustomErrorServer
from mcrouter.test.mock_servers import SleepSe... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
This is a script written to add the template "orphan" to pages.
These command line parameters can be used to specify which pages to work on:
¶ms;
-xml Retrieve information from a local XML dump (pages-articles
or pages-meta-current, see... |
#
"""Sliver manager API.
This module exposes an XMLRPC interface that allows PlanetLab users to
create/destroy slivers with delegated instantiation, start and stop
slivers, make resource loans, and examine resource allocations. The
XMLRPC is provided on a localhost-only TCP port as well as via a Unix
domain socket th... |
import cairo
from gi.repository import Gdk
"""
A pen tool. Draws a stroke with a certain color and size.
"""
_last_point = None
_current_coords = None
_current_stroke = None
linewidth = 1.5
color = (0,0,128,255)
def press(widget, event):
"""
Mouse down event. Draw a point on the pointer location.
Po... |
{
'name': 'Budgets Management',
'category': 'Accounting',
'description': """
This module allows accountants to manage analytic and crossovered budgets.
==========================================================================
Once the Budgets are defined (in Invoicing/Budgets/Budgets), the Project Manager... |
"""
mbed CMSIS-DAP debugger
Copyright (c) 2006-2015 ARM Limited
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable ... |
__author__ = 'Russell Dias // inversezen.com'
# Py3k port done by Senthil (<EMAIL>)
__date__ = '05/12/2010'
__version__ = '0.0.1'
import random
from math import log
def gcd(u, v):
""" The Greatest Common Divisor, returns
the largest positive integer that divides
u with v without a remainder.
"... |
# -*- coding: utf-8 -*-
# future imports
from __future__ import absolute_import
# local imports
from .members import all_current_committee_chairs
from .members import all_current_members
from .members import all_current_members_by_given_constituency_id
from .members import all_current_members_by_given_party_id
from .... |
# routines for interacting with PIMAIM data / filetypes
import numpy as np # type: ignore
from vasppy.poscar import Poscar
from vasppy.cell import Cell
from vasppy.units import angstrom_to_bohr
def lines_to_numpy_array( data ):
return np.array( [ [ float( s ) for s in line.split() ] for line in data ] )
def rea... |
"""An SVG writer."""
__author__ = 'Paul Ross'
__date__ = '2011-07-10'
__rights__ = 'Copyright (c) 2008-2017 Paul Ross'
from cpip import ExceptionCpip
from cpip.util import XmlWrite
from cpip.plot import Coord
class ExceptionSVGWriter(ExceptionCpip):
"""Exception class for SVGWriter."""
pass
def dimToTx... |
"""
L{epsilon.expose} is a module which allows a system that needs to expose code
to a network endpoint do so in a manner which only exposes methods which have
been explicitly designated. It provides utilities for convenient annotation
and lookup of exposed methods.
"""
from epsilon.structlike import record
from eps... |
import cv2
import numpy as np
import matplotlib.pyplot as plt
# Plot result
plt.figure('IceQueen Q-Learning')
plt.xlabel('Numero de lanzamiento') # etiqueta eje x
plt.ylabel('Sumatorio de exitos') # etiqueta eje y
from Q_utils import *
from Q_space import *
from random import randint
from Const import *
print '\tEsp... |
import asyncio
import warnings
from typing import Optional
from mitmproxy import controller, ctx, eventsequence, flow, log, master, options, platform
from mitmproxy.flow import Error
from mitmproxy.proxy2 import commands
from mitmproxy.proxy2 import server
from mitmproxy.utils import asyncio_utils, human
class Async... |
from distutils.core import setup, Extension
from distutils.command.install_data import install_data
import os, sys
#Pete Shinner's distutils data file fix... from distutils-sig
#data installer with improved intelligence over distutils
#data files are copied into the project directory instead
#of willy-nilly
class smar... |
"""Page compiler plugin for nbconvert."""
from __future__ import unicode_literals, print_function
import io
import os
import sys
try:
from nbconvert.exporters import HTMLExporter
import nbformat
current_nbformat = nbformat.current_nbformat
from jupyter_client import kernelspec
from traitlets.confi... |
# -*- coding: utf-8 -*-
import functools
from logging import getLogger
from django.conf import settings
from django.core.management import BaseCommand # noqa
import taskcluster
from ...tasks import get_or_create_pool
from ...models import Task
LOG = getLogger("taskmanager.management.commands.scrape_group")
def p... |
import numpy as np
import string
import random
import matplotlib.pyplot as mpl
class Passenger:
def __init__(self, rowNumber, seatLetter):
self.rowNumber = float(rowNumber)
self.seatLetter = seatLetter
self.hasWaited = False
def checkPosition(self, position):
return position == self.rowNumber
def __re... |
from datetime import datetime
import os
from django.test import SimpleTestCase
from zentral.contrib.munki.utils import iter_certificates, is_ca, prepare_ms_tree_certificates
class TestMunkiTreeCertificates(SimpleTestCase):
@classmethod
def setUpClass(cls):
super().setUpClass()
tlsdir = os.path... |
# template for "Stopwatch: The Game"
import simplegui
# define global variables
t = 0 # Time
x = 0 # number of stops for integer(as 1.0, 2.0, etc.)
y = 0 # Total number of stops
# define helper function format that converts time
# in tenths of seconds into formatted string A:BC.D
def format(t):
a = t//600
... |
# -*- coding: utf-8 -*-
import time
from slackclient import SlackClient
import re
import os
from chatterbot import ChatBot
BOT_ID = "U6J3Z0HGS"
slack_client = SlackClient(os.environ["SLACK_BOT_TOKEN"])
def handle_command(command, channel):
response = "Don't know what you do you mean"
attachments_json = []
... |
# -*- coding: utf-8 -*-
from .defines import (
MODE_VERSION_1, MODE_VERSION_2, defregister_machine, defzone)
# -- Start backports from pyalienfx
_m11xr1_zones = (
defzone(0x6000, "Power Button", alias='power', is_power=True),
defzone(0x0001, "Keyboard: Right", alias='kbd-right'),
defzone(0x0020, "Spe... |
# -*- coding: utf-8 -*-
from lxml import etree
import requests
from datetime import datetime
from .item import PinboardItem
class Source(object):
pass
class PinboardSource(Source):
"""Pinboard (https://pinboard.in/) data source.
Fetches bookmarks from Pinboard.
"""
URL = "https://api.pinboard.... |
# coding: utf-8
import json
from logging import getLogger
from elasticsearch import Elasticsearch
from elasticsearch.exceptions import NotFoundError
logger = getLogger(__name__)
class ElasticsearchReader(object):
def __init__(self,
index,
hosts=None,
source... |
"""Ino (http://inotool.org/) based arduino build wrapper."""
import argparse
import io
import logging
import os
import shutil
import subprocess
import sys
import tempfile
from ino.environment import Environment
from ino.commands.build import Build
from ino.exc import Abort
from b3.steps.step_base import StepBase
c... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Module description
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Provides some programming control flow recipes.
Compatibility
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
- Python2: Yes
- Python3: ... |
import os
import sys
import hashlib
import transaction
from sqlalchemy import engine_from_config
from pyramid.paster import (
get_appsettings,
setup_logging,
)
from pyramid.scripts.common import parse_vars
from ..models import (
DBSession,
Base,
UserType,
User,
)
def usage(argv):... |
# All models of the MVC architecture go here.
import requests
import json
class TrackDownloader(object):
"""Downloads songs from pleer.com"""
def __init__(self, identifier, key, query=None, download_dir=None):
"""
:param identifier: Id of Pleer API access.
:type identifier: int
... |
"""implementation of the RFC00001-event-log-spec proposal"""
# Registering the serializers for eventlib
import ejson.serializers # pyflakes:ignore
# Imports to register and expose things in the "eventlib" namespace.
from .api import log, handler, external_handler, BaseEvent # pyflakes: ignore
__version__ = ... |
import sqlite3,os
class SQLPreferences():
__conn = None
def __init__(self, dbname):
self.__conn = sqlite3.connect(os.path.expanduser(dbname))
if self.__conn == None:
print 'Unable to open database'
sys.exit(1)
with self.__conn:
cur = self.__conn.cur... |
import unittest
import logging
from flask import redirect, request, session
logging.basicConfig(format='%(asctime)s:%(levelname)s:%(name)s:%(message)s')
logging.getLogger().setLevel(logging.DEBUG)
DEFAULT_ADMIN_USER = 'jbp'
DEFAULT_ADMIN_PASSWORD = 'jbp'
# DEFAULT_ADMIN_USER = 'admin'
# DEFAULT_ADMIN_PASSWORD = 'g... |
# f = open(os.path.join(self.searchlight_out,'errf.txt'), 'a')
# f.write(text + "\n")
# f.close()
# @staticmethod
# def t_est(rate, jobs, divs):
# t = int(rate*(divs-jobs))
# t_day = t / (60*60*24)
# t -= t_day*60*60*24
# t_hr = t / (60*60)
# ... |
# -*- coding: utf-8 -*-
from tutorial.items import JdPicture
from scrapy.contrib.spiders import CrawlSpider, Rule
from scrapy.contrib.linkextractors import LinkExtractor
from scrapy.log import log
class JdSpider(CrawlSpider):
name = "jd_spider"
allowed_domains = [
"www.jd.com",
"channel.jd.com... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.