code stringlengths 1 199k |
|---|
from PlugIns.PlugIn import PlugIn
class CypherPlug(PlugIn):
def __init__(self, sample=None):
PlugIn.__init__(self, sample)
def getPath(self):
return "particular_header.cypher"
def getName(self):
return "cypher"
def getVersion(self):
return 1
def process(self):
... |
import os
import os.path
import re
import stat
safe_chars = ('ABCDEFGHIJKLMNOPQRSTUVWXYZ'
'abcdefghijklmnopqrstuvwxyz'
'0123456789' '_.-')
def quote_hex(s, safe=''):
"""
Replace potentially unsafe characters in 's' with their %XX hexadecimal
counterparts. You can pass additional ... |
from datetime import datetime
import rfGengou
from . import PluginBase
__all__ = ['Gengo']
class Gengo(PluginBase):
def execute(self, args):
if len(args) == 0:
target = datetime.now()
elif len(args) == 1:
target = datetime.strptime(args[0], '%Y/%m/%d')
else:
... |
// Copyright (c) 2014 Dyffy, Inc.
import time
import json
import pprint
import hashlib
import struct
import re
import base64
import httplib
import sys
from multiprocessing import Process
ERR_SLEEP = 15
MAX_NONCE = 1000000L
settings = {}
pp = pprint.PrettyPrinter(indent=4)
class SidecoinRPC:
OBJID = 1
def __init__(sel... |
import pdq
cpusPerServer = 4
emailThruput = 2376 # emails per hour
scannerTime = 6.0 # seconds per email
pdq.Init("Spam Farm Model")
nstreams = pdq.CreateOpen("Email", float(emailThruput)/3600)
nnodes = pdq.CreateNode("spamCan", int(cpusPerServer), pdq.MSQ)
pdq.SetDemand("spamCan", "Email", scannerTime)
pdq.Solve... |
import pymongo
def delete_repeat_data():
client = pymongo.MongoClient('localhost', 27017)
db = client.admin
collection = db.taplist
for url in collection.distinct('game_id'): # 使用distinct方法,获取每一个独特的元素列表
num = collection.count({"game_id": url}) # 统计每一个元素的数量
print num, "===== aawa =====... |
import argparse
from osgb import osgb_to_lonlat
from osgb.convert import eastnorth_to_osgb
from utils.database import insert_into_db, empty_table, execute_sql
def read_stations(filename):
with open(filename, 'r') as input_file:
for line in input_file.readlines()[1:]:
splits = line.strip().split(... |
"""
Tests for install.py for SUSE based Linux distributions
"""
import os
import shutil
from unittest import mock
import pytest
from install import Cmd, CmdError, RemoteFileNotFoundError
pytestmark = pytest.mark.skipif(
not pytest.helpers.helper_is_suse(),
reason="Tests for openSUSE/SUSE"
)
def test_rpm_downloa... |
from typing import TYPE_CHECKING
import warnings
from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error
from azure.core.paging import ItemPaged
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import HttpRe... |
import rdflib
from rdflib.term import URIRef, Variable
from PyOpenWorm.dataObject import DataObject, InverseProperty
from PyOpenWorm.context import Context
from PyOpenWorm.context_store import ContextStore
from .DataTestTemplate import _DataTest
try:
from unittest.mock import MagicMock, Mock
except ImportError:
... |
extensions = ['apilinks_sphinxext']
templates_path = ['_templates']
source_suffix = '.rst'
master_doc = 'index'
project = u'Wokkel'
copyright = u'2003-2012, Ralph Meijer'
version = '18.0.0'
release = '18.0.0'
exclude_patterns = ['_build', 'listings']
pygments_style = 'sphinx'
apilinks_base_url = 'api/'
html_theme = 'de... |
'''
A drop-in replacement for optparse ( "import optparse_gui as optparse" )
Provides an identical interface to optparse(.OptionParser),
But displays an automatically generated wx dialog in order to enter the
options/args, instead of parsing command line arguments
'''
import sys, os, os.path, fnmatch, types, time
impor... |
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('posts', '0001_initial'),
]
operations = [
migrations.RemoveField(
model_name='post',
name='tags',
),
migrations.DeleteMod... |
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
import os
from figure3 import select, ket, exp
from matrix import ops
from measures import local_entropies_from_rhos, local_exp_vals_from_rhos
from mpl_toolkits.axes_grid1 import ImageGrid
from matplotlib import rc
rc("text", usetex=True)
font ... |
"""
This file should only work on Python 3.6 and newer.
Its purpose is to test a correct installation of Python 3.
"""
from random import randint
print("Generating one thousand random numbers...")
for i in range(1000):
random_number = randint(0, 100000)
print(f"Number {i} was: {random_number}") |
"""
TAGME implementation
@author: Faegheh Hasibi (faegheh.hasibi@idi.ntnu.no)
"""
import argparse
import math
from nordlys.config import OUTPUT_DIR
from nordlys.tagme import config
from nordlys.tagme import test_coll
from nordlys.tagme.query import Query
from nordlys.tagme.mention import Mention
from nordlys.tagme.luce... |
from django.shortcuts import render
from enfermeriaapp.models import Cola_Consulta, Cola_Enfermeria
from django.core.urlresolvers import reverse
from django.shortcuts import redirect
from django.utils import timezone
import time
from django.contrib import messages
from django.contrib.auth.decorators import login_requir... |
class InvalidAPIUsage(Exception):
status_code = 400
def __init__(self, message, status_code=None, payload=None):
Exception.__init__(self)
self.message = message
if status_code is not None:
self.status_code = status_code
self.payload = payload
def to_dict(self):
... |
import os, sys, multiprocessing, subprocess
from build_util import *
if __name__ == "__main__":
cfg = cfg_from_argv(sys.argv)
bi = build_info(cfg.compiler, cfg.archs, cfg.cfg)
print("Starting build project: " + build_cfg.project_name + " ...")
additional_options = "-DCFG_PROJECT_NAME:STRING=\"%s\"" % build_cfg.proj... |
import logging
import types
import dateutil.parser
import feedparser
import pytz
import http
from html_sanitizer import HTMLSanitizer
def getFeed(url):
current_feed = []
content = http.get(url)
feed = feedparser.parse(content) # even if content is None feedparser returns object with empty entries list
... |
"""Wrapper for netCDF readers."""
from __future__ import unicode_literals, division, print_function
import os.path
import warnings
import numpy as np
from collections import OrderedDict
from monty.dev import requires
from monty.collections import AttrDict
from monty.functools import lazy_property
from monty.string impo... |
class Solution(object):
def isPalindrome(self, x):
"""
:type x: int
:rtype: bool
"""
s=str(x)
l=list(s)
l.reverse()
sq=''
s1=sq.join(l)
if s==s1:
return True
else:
return False |
__author__ = 'http://www.python-course.eu/python3_inheritance.php'
class Person:
def __init__(self, first, last):
self.firstname = first
self.lastname = last
def Name(self):
return self.firstname + " " + self.lastname
class Employee(Person):
def __init__(self, first, last, staffnum):... |
from build import evaluate_callables
class WhenEvaluatingADictWithNoCallables:
def when_i_evaluate_the_dict(self):
self.result = evaluate_callables({"abc": 123, "def": 456, "xyz": 789})
def it_should_return_the_same_dict(self):
assert self.result == {"abc": 123, "def": 456, "xyz": 789}
class Whe... |
from .sub_resource import SubResource
class FrontendIPConfiguration(SubResource):
"""Frontend IP address of the load balancer.
Variables are only populated by the server, and will be ignored when
sending a request.
:param id: Resource ID.
:type id: str
:ivar inbound_nat_rules: Read only. Inbound... |
from decode import decode |
import sys, re
if sys.version_info < (3, 0):
import testcase
import modules.cssfuncs as funcs
else:
from . import testcase
from ..modules import cssfuncs as funcs
class TestFunctions(testcase.TestCase):
title = "CSS Functions"
def test_functions(self):
self.set_text( self.input() )
self.text_equals( self.inpu... |
"""Special exceptions for the ``command_interface`` app."""
class CommandError(Exception):
pass |
from django.apps import AppConfig
class MailinglistsConfig(AppConfig):
name = 'apps.mailinglists'
verbose_name = 'Mailinglists' |
import os
import pandas as pd
import seaborn as sns
dataDir = '..\\Test_Data\\'
pilotMarkerDataFile = 'Pilot.csv'
df = pd.read_csv( dataDir + '\\' + pilotMarkerDataFile,sep='\t', engine='python')
repr(df.head()) |
from django.http import Http404
from rest_framework import generics, permissions
from rest_framework.reverse import reverse
from rest_framework.response import Response
from rest_framework.views import APIView
from core.utils import filter_files_by_n_slashes
from .serializers import (FileBrowserPathListSerializer, File... |
import json
dic={}
with open('currentPlayerDump.json','r') as f:
data=json.load(f)
print data["resultSets"][0]["headers"]
print len(data["resultSets"][0]["rowSet"])
for obj in data["resultSets"][0]["rowSet"]:
if obj[0] not in dic:
dic[obj[0]]=obj[1]
with open('playerKey','w') as f1:
for key in dic:
f1.wr... |
import sys
from setuptools import setup, find_packages
from setuptools.command.test import test as TestCommand
class PyTest(TestCommand):
def finalize_options(self):
super().finalize_options()
self.test_args = []
self.test_suite = True
def run_tests(self):
import pytest
e... |
from contextlib import contextmanager
from fnmatch import fnmatch
import stat
from pyrsistent import pset
import attr
from filesystems import Path, exceptions
def _realpath(fs, path, seen=pset()):
"""
.. warning::
The ``os.path`` module's realpath does not error or warn about
loops, but we do, f... |
"""
Домашнее задание по уроку 2-2
«Работа с разными форматами данных»
Выполнил Мартысюк Илья PY-3
"""
import re
import glob
import chardet
from os.path import join
from xml.etree.cElementTree import XMLParser, parse
def open_data_file(path):
with open(path, 'rb') as encoding_detect_file:
file_text = encodin... |
from sqlalchemy import inspection, event, Column, Integer, ForeignKey
from sqlalchemy.orm import session, query
from sqlalchemy.sql import expression
from sqlalchemy.ext.declarative import declared_attr
import sqlalchemy
__all__ = [
'Base',
'TenantSession',
'TenantConflict',
'UnboundTenantError'
]
SQLA_... |
import unittest
from cwr.parser.encoder.dictionary import PublisherForWriterDictionaryEncoder
from cwr.interested_party import PublisherForWriterRecord
"""
Publisher for Writer record to dictionary encoding tests.
The following cases are tested:
"""
__author__ = 'Bernardo Martínez Garrido'
__license__ = 'MIT'
__status_... |
"""
ERP+
"""
__author__ = 'António Anacleto'
__credits__ = []
__version__ = "1.0"
__maintainer__ = "António Anacleto"
__status__ = "Development"
__model_name__ = 'balancete.Balancete'
import auth, base_models
from orm import *
from form import *
try:
from my_ano_fiscal import AnoFiscal
except:
from ano_fiscal i... |
import sublime, sublime_plugin
import os
import subprocess
import threading
class OpenGitbashHere(sublime_plugin.TextCommand):
def run(self, edit):
view = self.view
file_path = view.file_name()
dirname = os.path.dirname(file_path)
th = BashTerminalThread(dirname)
th.start()
... |
import _plotly_utils.basevalidators
class PatternValidator(_plotly_utils.basevalidators.FlaglistValidator):
def __init__(self, plotly_name="pattern", parent_name="volume.surface", **kwargs):
super(PatternValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
... |
import sys, os
import tweepy
consumer_file='twitter.consumer'
access_file='twitter.access'
def __load_auth(file):
if os.path.exists(file):
with open(file) as f:
tokens = f.readline().replace('\n','').replace('\r','').split(':')
if len(tokens) == 2:
return tokens[0],tokens[1]
... |
import math
import os
import struct
import sys
import wave
import cv2 as cv
import numpy as np
file_name = 'hificode.wav' # User-defined parameters
min_frequency = 500 # Lowest frequency (Hz) in soundscape
max_frequency = 5000 # Highest frequency (Hz)
sample_frequency = 44100 # Sample frequency (Hz)
image_to_soun... |
from __future__ import unicode_literals
from django.contrib.auth.models import User
from django.core.exceptions import ObjectDoesNotExist
from django.utils import six
from djblets.util.decorators import augment_method_from
from djblets.webapi.decorators import (webapi_login_required,
... |
from lib.utils import *
def _help():
usage = '''
Usage: set [options] (var) [value]
[options]:
-h Print this help.
-del (var) Delete variable
(var) if defined.
where (var) is a valid
global variable
if [value] is not given,
current value is returned
'''
print(usage)
def m... |
'''
- Leetcode problem: 210
- Difficulty: Medium
- Brief problem description:
There are a total of n courses you have to take, labeled from 0 to n-1.
Some courses may have prerequisites, for example to take course 0 you have to first take course 1, which is expressed as a pair: [0,1]
Given the total number of courses a... |
import logging
logging.basicConfig(filename='test-logfile.log', level=logging.DEBUG)
top = 50
for i in range(top):
print(i)
logging.info('Loop completed, reached %s' % top) |
import os
import pytest
BASE_DIR = os.path.abspath(os.path.dirname(__file__))
SITE_DIR = os.path.join(BASE_DIR, "site")
@pytest.fixture
def site_dir():
return SITE_DIR
@pytest.fixture
def output_exist():
return lambda path: os.path.exists(os.path.join(SITE_DIR, "deploy", path))
@pytest.fixture(autouse=True)
def... |
from ..request import Request
from ..query import Entity
from ..query import Entry
import json
class UserEntity(Entity):
"""UserEntity object used for upload user entities.
Detail information about user entities you can see at our site
https://docs.api.ai/docs/userentities"""
@property
def session_i... |
from simplequeue.lib.configuration import config
__all__ = ['config'] |
from __future__ import unicode_literals
import arrow
from django.db.models import DateTimeField, SubfieldBase
from .form_fields import ArrowField as ArrowFormField
class ArrowField(DateTimeField):
__metaclass__ = SubfieldBase
def to_python(self, value):
if isinstance(value, arrow.Arrow):
ret... |
import string
import os.path
from MolKit import Read
from AutoDockTools.DockingParameters import DockingParameters, DockingParameter4FileMaker, genetic_algorithm_list, \
genetic_algorithm_local_search_list4, local_search_list4,\
simulated_annealing_list4
def usage():
print "Usage: pr... |
from similarity.webpage import WebPage |
from aioredis.util import wait_convert, wait_ok, _NOTSET, _ScanIter
class GenericCommandsMixin:
"""Generic commands mixin.
For commands details see: http://redis.io/commands/#generic
"""
def delete(self, key, *keys):
"""Delete a key."""
fut = self.execute(b'DEL', key, *keys)
retu... |
from .engine import BloggingEngine
from .processor import PostProcessor
from .sqlastorage import SQLAStorage
from .storage import Storage
"""
Flask-Blogging is a Flask extension to add blog support to your
web application. This extension uses Markdown to store and then
render the webpage.
Author: Gouthaman Balaraman
Da... |
from django.conf.urls import patterns, include, url
from django.contrib import admin
from dashboard.views import QuestionApi
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'zuobiao.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
url(r'^admin/', include(admin.site.urls)),
url(... |
import os
import sys
import 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)
from smb... |
import requests
from urllib.parse import parse_qs, urlparse
from lxml.html import fromstring
_HEADERS = {
'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/41.0.2272.76 Chrome/41.0.2272.76 Safari/537.36',
'accept': 'text/html,application/xhtml+xml,application/... |
"""
Copyright (c) 2016 Gabriel Esteban
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
documentation files (the "Software"), to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute,... |
from __future__ import unicode_literals
from django.db import models
from modpacks.models.modpack import Modpack
class Server(models.Model):
""" Minecraft Server details for display on the server page """
name = models.CharField(verbose_name='Server Name',
max_length=200)
desc = models.TextField... |
from lexer import lang
from ..tree import Node
class Integer(Node):
datatype = lang.SEMANTIC_INT_TYPE
"""docstring for Integer."""
def __init__(self, symbol, token):
super().__init__(symbol, token)
def generate_code(self, **cond):
array, line = Node.assignated_array()
Node.array_... |
"""Ingest Stage IV Hourly Files.
1. Copies to hourly stage IV netCDF files
2. Copies hourly stage IV netCDF to hourly IEMRE
"""
import os
import datetime
import sys
import numpy as np
from scipy.interpolate import NearestNDInterpolator
import pygrib
from pyiem import iemre
from pyiem.util import utc, ncopen, lo... |
"""Clock for keeping track of the wall time.
"""
__all__ = ['ClockError', 'Clock', 'log']
import datetime
import logging
import time
from typing import Optional # noqa: F401. Used for mypy.
class ClockError(Exception):
"""Invalid clock operation."""
pass
class Clock:
"""Clock for keeping track of time.
... |
from __future__ import unicode_literals
from csacompendium.utils.abstractmodels import (
AuthUserDetail,
CreateUpdateTime,
)
from csacompendium.utils.createslug import create_slug
from csacompendium.utils.modelmanagers import (
model_instance_filter,
model_foreign_key_qs,
model_type_filter,
crea... |
from django.conf.urls import patterns, include, url
from django.contrib import admin
import views
urlpatterns = patterns('',
url(r'^add_model_abox', 'tadaa.views.add_model_abox'),
url(r'^add_model', 'tadaa.views.add_model'),
url(r'^list_models', 'tadaa.views.list_models', name='list_models'),
url(r'^abo... |
from docutils import nodes
from docutils.parsers.rst import Directive, directives
CODE = """\
<iframe width="{width}"
height="{height}"
src="http://www.youtube.com/embed/{yid}?rel=0&hd=1&wmode=transparent"
></iframe>"""
class Youtube(Directive):
""" Restructured text extension for inserting youtube embedded... |
from django.db import models
from django.utils import timezone
class TimeStampedModel(models.Model):
created_at = models.DateTimeField(default=timezone.now)
updated_at = models.DateTimeField(default=timezone.now)
class Meta:
abstract = True |
import os
import sys
import pandas as pd
import numpy as np
from numpy.random import poisson, uniform
from numpy import mean
import time
import math
po = True
teamsheetpath = sys.path[0] + '/teamcsvs/'
compstat = {'TDF': 'TDA', 'TDA': 'TDF', #Dictionary to use to compare team stats with opponent stats
'FGF'... |
from cogent.app.util import CommandLineApplication,\
CommandLineAppResult, ResultPath
from cogent.app.parameters import Parameter,ValuedParameter,Parameters
__author__ = "Shandy Wikman"
__copyright__ = "Copyright 2007-2012, The Cogent Project"
__contributors__ = ["Shandy Wikman"]
__license__ = "GPL"
__version__ = "... |
""" Assignment 1, Exercise 3, INF1340, Fall, 2015. Troubleshooting Car Issues.
This module contains one function diagnose_car(). It is an expert system to
interactive diagnose car issues.
"""
__author__ = 'Susan Sim'
__email__ = "ses@drsusansim.org"
__copyright__ = "2015 Susan Sim"
__license__ = "MIT License"
"""
"""
"... |
"""
Disjoint set.
Reference: https://en.wikipedia.org/wiki/Disjoint-set_data_structure
"""
class Node:
def __init__(self, data: int) -> None:
self.data = data
self.rank: int
self.parent: Node
def make_set(x: Node) -> None:
"""
Make x as a set.
"""
# rank is the distan... |
"""
.. module:: pilot
:platform: Unix
:synopsis: RADICAL-Pilot is a distributed Pilot-Job framework.
.. moduleauthor:: Ole Weidner <ole.weidner@rutgers.edu>
"""
__copyright__ = "Copyright 2013-2014, http://radical.rutgers.edu"
__license__ = "MIT"
from types import *
from states import *
from logentry im... |
import tensorflow as tf
from vdcnn import VDCNN
import numpy as np
import os
import time
import datetime
import cPickle as pkl
import tables
tf.flags.DEFINE_float("dropout_keep_prob", 0.5, "Dropout keep probability (default: 0.5)")
tf.flags.DEFINE_float("l2_reg_lambda", 0.0, "L2 regularizaion lambda (default: 0.0)")
tf... |
"""Use stochastic Lanczos quadrature to approximate spectral function sums of
any operator which has an efficient representation of action on a vector.
"""
import functools
from math import sqrt, log2, exp, inf, nan
import random
import warnings
import numpy as np
import scipy.linalg as scla
from scipy.ndimage.filters ... |
from twilio.rest import Client
account_sid = "ACCOUNT_SID"
auth_token = "your_auth_token"
client = Client(account_sid, auth_token)
number = client.lookups.phone_numbers("+15108675309").fetch(type="carrier")
print(number.carrier['type'])
print(number.carrier['name']) |
from part import *
from material import *
from section import *
from assembly import *
from step import *
from interaction import *
from load import *
from mesh import *
from optimization import *
from job import *
from sketch import *
from visualization import *
from connectorBehavior import *
import time
MODEL_NAME =... |
from pprint import pprint
from django import forms
from base.forms.custom import O2BaseForm
from base.forms.fields import (
O2FieldCorForm,
O2FieldModeloForm,
O2FieldRefForm,
)
class InfAdProdForm(forms.Form):
pedido = forms.CharField(
label='Pedido',
widget=forms.TextInput(attrs={'type'... |
from pprint import pprint
import lotes.models
def where_ende_disponivel(campo):
filter_local = ""
end_disp = list(lotes.models.EnderecoDisponivel.objects.filter(disponivel=True).values())
if len(end_disp) != 0:
filter_end = """--
AND l.local ~ '^("""
filter_sep = ""
for r... |
from dataclasses import dataclass
import io
import typing as T
import numpy as np
@dataclass(frozen=True)
class PolygonShape:
vertices: T.Tuple[T.Tuple[float]]
color: T.Text
@dataclass(frozen=True)
class Body:
x: float
y: float
angle: float
shapes: T.Tuple[PolygonShape]
@dataclass(frozen=True)
c... |
""" progressbar2 related utils"""
from codekit.codetools import warn
from public import public
from time import sleep
import progressbar
import functools
@public
def setup_logging(verbosity=0):
"""Configure progressbar sys.stderr wrapper which is required to play nice
with logging and not have strange formattin... |
import os
import shutil
def pre_read(dir):
try:
filelist = os.listdir(dir)
for file in filelist:
if os.path.isdir(file):
# exception directory
if str(file) == 'webMager' or str(file) == '_site':
continue
pre_read(file)
... |
from sys import argv, stderr
usage = \
"""
Usage: {program} <sample rate> <A4 freq.> [octaves=8]
e.g.: {program} 64000 442.0 5
""".format(program=argv[0])
if len(argv) < 3 or len(argv) > 4 :
print(usage, file = stderr)
exit(1)
A4 = 0
sample_rate = 0
octaves = 8
try:
A4 = float(argv[2])
except:
print("Er... |
from __future__ import print_function
__author__ = 'breddels'
import platform
import vaex.utils
import sys
import threading
import vaex.export
import vaex.utils
import vaex.promise
import vaex.settings
import vaex.remote
import psutil
from vaex.parallelize import parallelize
from vaex.ui.plot_windows import PlotDialog
... |
from __future__ import unicode_literals
from rest_framework import serializers
from rest_framework.reverse import reverse
from django.db.models import Q
from authentication.serializers import UserDisplaySerializer
from hub.models import PackageModel, DocumentModel, FileGroupModel, FileModel, TransformationModel, UrlMod... |
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_Form(object):
def setupUi(self, Form):
Form.setObjectName("Form")
Form.resize(800, 600)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred)
sizePolicy.setHorizontalStretch(0)
... |
"""Tornado handlers for kernel specifications.
Preliminary documentation at https://github.com/ipython/ipython/wiki/IPEP-25%3A-Registry-of-installed-kernels#rest-api
"""
import glob
import json
import os
pjoin = os.path.join
from tornado import web
from ...base.handlers import APIHandler, json_errors
from ...utils impo... |
"""Test template support in VTK-Python
VTK-python decides which template specializations
to wrap according to which ones are used in typedefs
and which ones appear as superclasses of other classes.
In addition, the wrappers are hard-coded to wrap the
vtkDenseArray and vtkSparseArray classes over a broad
range of types.... |
import tornado.ioloop
from awsutils.tornado.sqsclient import SQSClient
from test.settings import access_key, secret_key
sqsclient = SQSClient(endpoint='sqs.us-east-1.amazonaws.com', access_key=access_key, secret_key=secret_key, secure=False)
def renderResult(data):
print("message received", data)
sqsclient.sendMess... |
import scrapy
class TripadItem(scrapy.Item):
# define the fields for your item here like:
# name = scrapy.Field()
pass |
import os
from qmpy import *
from django.test import TestCase
peak_locations = []
class MiedemaTestCase(TestCase):
def setUp(self):
read_elements()
def test_methods(self):
## test that it generally works
self.assertEqual(Miedema("FeNi").energy, -0.03)
self.assertEqual(Miedema("Fe... |
import sys
import argparse
import collections
from functools import wraps
import logging
logger = logging.getLogger(__name__)
class CommandLine(object):
"""Create a command line interface for the application.
Can call any core method as action.
Careful: The function defintion order is reflected in the cli.
... |
import re
from .common import InfoExtractor
class GamekingsIE(InfoExtractor):
_VALID_URL = r'http://www\.gamekings\.tv/videos/(?P<name>[0-9a-z\-]+)'
_TEST = {
u"url": u"http://www.gamekings.tv/videos/phoenix-wright-ace-attorney-dual-destinies-review/",
u'file': u'20130811.mp4',
# MD5 is ... |
import collections
import re
class Jison:#extends
symbols = {}
terminals = {}
productions = {}
table = {}
default_actions = {}
version = '0.3.12'
debug = False
action_none = 0
action_shift = 1
action_deduce = 2
action_accept = 3
unput_stack = []
def trace(self):
"""trace"""
def __init__(self):
"""Setu... |
class Printer:
def __init__(self):
self._output = ''
def print_output(self, output):
self._output += output
def print_line(self, x1, y1, x2, y2, color=0, width=1):
self.print_output(_svg_line(x1, y1, x2, y2, color=color, width=width))
def print_circle(self, x, y, r, color=0, widt... |
import pytest
from flask_httpauth import HTTPBasicAuth
from kapsi_git_manager.kgm import app
from kapsi_git_manager import authentication as auth
password = "password"
username = "username"
def test_auth_simple():
""" this is the idiot test to check whether anything in you auth system works. """
assert isinstan... |
ur"""AsyncIO objects wrap the Win32 Overlapped API. They are instantiated by
passing a handle which has been opened for Overlapped IO. They can be waited
on by the functions in the :mod:`ipc` module and are True when complete,
False otherwise.
"""
import pywintypes
import winerror
import win32event
import win32file
fro... |
import asyncio
import demjson
from bot import user_steps, sender, get, downloader
from message import Message
client_id = ''#YOUR CLIENT ID
async def search(query):
global guest_client_id
search_url = 'https://api.soundcloud.com/search?q=%s&facet=model&limit=30&offset=0&linked_partitioning=1&client_id='+client_... |
"""
Anonymous token-based surveys
""" |
"""
moderation plugin for DecoraterBot.
"""
import regex
import discord
from discord.ext import commands
from DecoraterBotUtils import utils
class Moderation:
"""
Moderation Commands Extension to the
default DecoraterBot Moderation commands.
"""
def __init__(self):
self.moderation_text =... |
__all__ = ['pwnedapi', 'utils']
from .pwnedapi import HaveIBeenPwnedApi |
__version__ = '0.0.1'
__license__ = 'MIT' |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.