code stringlengths 1 199k |
|---|
from twisted.trial import unittest
from twistedchecker.checkers.docstring import DocstringChecker
class DocstringTestCase(unittest.TestCase):
"""
Test for twistedchecker.checkers.docstring
"""
def test_getLineIndent(self):
"""
Test of twistedchecker.checkers.docstring._getLineIndent.
... |
from tilequeue.query.fixture import make_fixture_data_fetcher
from tilequeue.query.pool import DBConnectionPool
from tilequeue.query.postgres import make_db_data_fetcher
from tilequeue.query.rawr import make_rawr_data_fetcher
from tilequeue.query.split import make_split_data_fetcher
from tilequeue.process import Source... |
"""empty message
Revision ID: 4986e64643f4
Revises: 175003d01257
Create Date: 2015-04-15 12:16:41.965765
"""
revision = '4986e64643f4'
down_revision = '175003d01257'
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import postgresql
def upgrade():
### commands auto generated by Alembic - plea... |
from django.db.backends.mysql.compiler import SQLCompiler as BaseSQLCompiler
from django.db.backends.mysql.compiler import SQLInsertCompiler, \
SQLDeleteCompiler, SQLUpdateCompiler, SQLAggregateCompiler, \
SQLDateCompiler, SQLDateTimeCompiler
class SQLCompiler(BaseSQLCompiler):
STRAIGHT_INNER = 'STRAIGHT_JO... |
import io
import math
import sys
import unittest
class Vector:
def __init__(self, x, y, z):
self.x = x
self.y = y
self.z = z
def subtract(self, other):
x = self.x - other.x
y = self.y - other.y
z = self.z - other.z
return Vector(x, y, z)
def dot_produc... |
from app import create_app
app = create_app()
if __name__ == "__main__":
app.run(host="0.0.0.0", port=5000, debug=True) |
from __future__ import print_function
from collections import OrderedDict
import numpy as np
import six
from acq4.devices.DAQGeneric.taskGUI import DAQGenericTaskGui
from acq4.devices.Device import Device, DeviceTask
from pyqtgraph import siFormat
from pyqtgraph.debug import Profiler
from acq4.util import Qt
from acq4.... |
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from django.http import Http404, JsonResponse, HttpResponseForbidden
from django.shortcuts import render, redirect, get_object_or_404
from .forms import PlaylistForm
from .models import Playlist
def form_data(user, for... |
import uctypes
ACCEL_CONFIG = {
'x_self_test' : uctypes.BFUINT8 | 0 | 7 << uctypes.BF_POS | 1 << uctypes.BF_LEN,
'y_self_test' : uctypes.BFUINT8 | 0 | 6 << uctypes.BF_POS | 1 << uctypes.BF_LEN,
'z_self_test' : uctypes.BFUINT8 | 0 | 5 << uctypes.BF_POS | 1 << uctypes.BF_LEN,
'range' : uctyp... |
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "like.settings")
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv) |
import math
import time
def retry(tries, delay=1, backoff=2):
"""Retries a function or method until it returns True.
delay sets the initial delay, and backoff sets how much the delay should
lengthen after each failure. backoff must be greater than 1, or else it
isn't really a backoff. tries must be at least 0, ... |
import unittest, tempfile, uuid, os, shutil, sys
class Test_CreateRemoveTempLocation(unittest.TestCase):
def __init__(self, *args, **kwargs):
super(Test_CreateRemoveTempLocation, self).__init__(*args, **kwargs)
self._tmpTestFolder = None
def setUp(self):
self._tmpTestFolder = os.path.joi... |
from fsm import Machine
states = ["q1", "q2", "q3"]
alphabet = ["0","1"]
transitions = {
"q1": {"0": "q1", "1": "q2"},
"q2": {"0": "q3", "1": "q2"},
"q3": {"0": "q2", "1": "q2"},
}
start = "q1"
end = ["q2"]
machine = Machine.from_arguments(states, alphabet, transitions, start, end)
machine.run(123) # fail
m... |
'''
Ugly - will be improved soon
'''
from datetime import datetime,timedelta
def archive_timestamp(timestamp):
'''
'''
_d=datetime.strptime(timestamp, '%Y%m%d%H%M%S')
return _d.strftime('%Y%m%d')
def way_date(date_input):
'''
'''
if isinstance(date_input, str):
return datetime.strpti... |
import pymodelica
from pymodelica.compiler_wrappers import ModelicaCompiler
mc = ModelicaCompiler()
source = mc.parse_model("CauerLowPassAnalog.mo")
indent_amount = 2
def dump(src, fid, indent=0):
ind = " " * (indent_amount * indent)
try:
fid.write(ind + src.getNodeName() + "\n")
except:
fid... |
from PyQt4 import QtCore, QtGui
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
def _fromUtf8(s):
return s
try:
_encoding = QtGui.QApplication.UnicodeUTF8
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig, _encoding)
exce... |
from TreeNode import TreeNode
class Solution(object):
def sortedArrayToBST(self, nums):
if not nums : return None
n = len(nums)
if n == 1:
return TreeNode(nums[0])
mid = TreeNode(nums[n // 2])
mid.left = self.sortedArrayToBST(nums[:n // 2])
mid.right = sel... |
"""
Created on Fri Jan 27 16:23:07 2017
@author: user
"""
from nltk.sentiment.vader import SentimentIntensityAnalyzer
import psycopg2
import sys
reload(sys) #Prevents errors with utf-8 encoding not working properly
sys.setdefaultencoding('utf8')
def SentimentAnalyzer(tweets):
sid = SentimentIntensityAnalyzer() #nee... |
'''
The following is from http://stackoverflow.com/a/2022629
Thanks to Longpoke
'''
import types
class Event(list):
"""Event subscription.
A list of callable objects. Calling an instance of this will cause a
call to each item in the list in ascending order by index.
Example Usage:
>>> def f(x):
... |
import time
import psycopg2
import os
import sys
if __name__ == "__main__":
try:
conn = psycopg2.connect("dbname='master' user='postgres' host='localhost' password='postgres'")
except Exception, e:
print "unable to connect"
sys.exit()
cur = conn.cursor()
for x in xrange(1,1000):
print x
cur.execute("IN... |
from item import Item
class Merchant:
def __init__(self, markup=1.2, markdown=0.8):
self.inventory = []
self.markup = markup
self.markdown = markdown
def add_item(self, item):
# Adds an item to the merchant's inventory
if (not isinstance(item, Item)):
raise Ty... |
from django.core.management.base import BaseCommand, CommandError
import __future__
from ModelTracker.models import History
import datetime
from django.apps import apps
def getModel(table_name):
return next((m for m in apps.get_models() if m._meta.db_table==table_name), None)
class Command(BaseCommand):
help = ... |
import re
import os
import md5
import __main__
PYGMENTS_CACHE_DIR = os.path.abspath(os.path.join(os.path.dirname(__main__.__file__), '../../.pygments-cache'))
if not os.path.exists(PYGMENTS_CACHE_DIR):
os.makedirs(PYGMENTS_CACHE_DIR)
from pygments.formatters import HtmlFormatter
from docutils import nodes
from docu... |
import urllib2
import lxml.html
import numpy
import scipy
import scipy.misc
import scipy.cluster
import urlparse
import struct
import operator
import gzip
import datetime
import requests
import httplib
from PIL import BmpImagePlugin, PngImagePlugin, Image
from socket import error as SocketError
from boto.s3.key import ... |
"""
Binary class deconstruct, reconstruct packet
"""
import copy
class Binary(object):
@staticmethod
def deconstruct_packet(packet):
"""
Replaces every bytearray in packet with a numbered placeholder.
:param packet:
:return: dict with packet and list of buffers
"""
... |
from enum import Enum
""" Constantes concernant les tactiques. """
class Flags(Enum):
INIT = 0
WIP = 1
FAILURE = 2
SUCCESS = 3
PASS_TO_PLAYER = 4
def is_complete(p_status_flag):
return p_status_flag == Flags.FAILURE or p_status_flag == Flags.SUCCESS |
import os
from datetime import timedelta
basedir = os.path.abspath(os.path.dirname(__file__))
class Config:
###########################################################################
# [ Application ]
###########################################################################
APP_TITLE = 'WebApp'
A... |
"""
merged implementation of the cache provider
the name cache was not chosen to ensure pluggy automatically
ignores the external pytest-cache
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import json
import os
from collections import OrderedDict
import... |
"""
This module contains input, output and algorithms for creating
texture atlases.
""" |
from __future__ import division,print_function,unicode_literals
import os
import bctest
import buildenv
if __name__ == '__main__':
bctest.bctester(os.environ["srcdir"] + "/test/data",
"navcoin-util-test.json",buildenv) |
import pylogging
import os
logs_path = os.path.dirname(os.path.abspath(__file__)) + '/logs/'
logger = pylogging.PyLogging(LOG_FILE_PATH = logs_path)
def customAction1(type, msg):
# Custom Action Goes Here
pass
actionIden1 = logger.addAction(customAction1)
def customAction2(type, msg):
# Custom Action Goes Here
pass... |
from .utils import ShellParser
class Parser(ShellParser):
"""Extract text from postscript files using ps2ascii command.
"""
def extract(self, filename, **kwargs):
stdout, _ = self.run(['ps2ascii', filename])
return stdout |
class Node:
def __init__(self,data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def push(self, newdata): #in front
newnode = Node(newdata)
newnode.next = self.head
self.head = newnode
def insertAfter(self, prevnode, newdata):
newnode = Node(newdata)
newn... |
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('mainapp', '0016_auto_20181202_2205'),
('mainapp', '0016_auto_20181221_1432'),
]
operations = [
] |
from multiprocessing import Process
import pytest
from .mock_server.server import start
server_process = None
@pytest.hookimpl
def pytest_sessionstart(session):
global server_process
server_process = Process(target=start)
server_process.start()
@pytest.hookimpl
def pytest_sessionfinish(session):
if serv... |
import cPickle, os, re
def main():
#base_dir = "../data/ct/"
base_dir = "/home/eguney/data/ct/"
file_name = base_dir + "ct.csv"
output_data(base_dir, file_name)
return
def output_data(base_dir, file_name):
drug_to_ctids = get_interventions(base_dir, include_other_names=True) #False)
print le... |
import peewee
import tornado.web
import tornado.gen
from windseed.settings import env, db
from windseed.base import handler
from windseed.apps.admin import urls
from windseed.apps.admin.models import User
from windseed.apps.web.models import Record
class Handler(handler.Handler):
def get_current_user(self):
... |
import tensorflow as tf
hello = tf.constant('Hello, Tensorflow')
sess = tf.Session()
print(sess.run(hello))
node1 = tf.constant(3.0, tf.float32) # 숫자, 데이터타입
node2 = tf.constant(4.0) # 숫자, 데이터타입
node3 = tf.add(node1, node2) # 숫자, 데이터타입
print(node1)
print(node2)
print(node3)
sess = tf.Session()
print('sess.run(node1, ... |
import numpy as np
import matplotlib.pyplot as plt
from scipy.constants import c, e, m_p
import matplotlib.pyplot as plt
plt.switch_backend('TkAgg')
plt.ion()
from PyCOBRA_accelerator import TwissMap
from PyCOBRA_beam import Bunch, gaussian_generator
R = 6911./(2*np.pi)
energy = 26e9
gamma = np.sqrt(1 + (e*energy/(m_p*... |
import numpy as np
import pytoolkit as tk
def test_print_classification_multi():
y_true = np.array([0, 1, 1, 1, 2])
prob_pred = np.array(
[
[0.75, 0.00, 0.25],
[0.25, 0.75, 0.00],
[0.25, 0.75, 0.00],
[0.25, 0.00, 0.75],
[0.25, 0.75, 0.00],
... |
from readSVCsig import readSVCdata
from readSVCsig import readSVCheader
from readSVCsig import readSVCsig |
from argparse import ArgumentParser
from os.path import dirname
from os.path import isfile
import sys
from mako import exceptions
from mako.lookup import TemplateLookup
from mako.template import Template
def varsplit(var):
if "=" not in var:
return (var, "")
return var.split("=", 1)
def _exit():
sys... |
import json
import gspread
from oauth2client.service_account import ServiceAccountCredentials
from nessrest import ness6rest
import getpass
scopes = ['https://spreadsheets.google.com/feeds']
credentials = ServiceAccountCredentials.from_json_keyfile_name('API-xxxxxxxxxxxx.json', scopes)
gc = gspread.authorize(credential... |
"""
Django-environ allows you to utilize 12factor inspired environment
variables to configure your Django application.
"""
import json
import logging
import os
import re
import sys
import warnings
from django.core.exceptions import ImproperlyConfigured
from six.moves import urllib_parse as urlparse
from six import stri... |
"""
run tests against a webserver running in the same reactor
NOTE: this test uses port 8888 on localhost
"""
import os
import ujson as json
import cyclone.httpclient
from twisted.internet import defer
from twisted.application import internet
from twisted.trial.unittest import TestCase
from twisted.python import log
fr... |
i = 0
upper_range=10
for i in range(upper_range):
print(str(i+1)+ " this is a loop") |
import re
import requests
import base64
import struct
import random
from sklearn.cluster import KMeans
from sklearn.preprocessing import scale
from dateutil.parser import parse
class Tweet(object):
def __init__(self, status):
self.screen_name = status['screen_name']
self.text = status['text']
... |
import logging
from amqpstorm import Connection
from amqpstorm import Message
logging.basicConfig(level=logging.INFO)
with Connection('localhost', 'guest', 'guest') as connection:
with connection.channel() as channel:
# Declare a queue called, 'simple_queue'.
channel.queue.declare('simple_queue')
... |
import ctypes
class C_struct:
"""Decorator to convert the given class into a C struct."""
# contains a dict of all known translatable types
types = ctypes.__dict__
@classmethod
def register_type(cls, typename, obj):
"""Adds the new class to the dict of understood types."""
cls.types[typename] = obj
def __call... |
import numpy as num
def integral(x,y):
"""
ROUTINE: INTEGRAL
USEAGE: RESULT = INTEGRAL( X, Y )
PURPOSE: Integrate tabulated data using Simpson's rule
with 3-point Lagragian interpolation. Data may be
regularly sampled in X, or irregularly sampled.
INPUT:
X ... |
from __future__ import unicode_literals, absolute_import
from django import forms
from django.utils.translation import ugettext_lazy as _
from .models import *
from common.forms import BaseModelForm
logger = logging.getLogger(__name__)
class ClientForm(BaseModelForm):
class Meta:
model = Client
fiel... |
import gdsfactory as gf
yaml = """
instances:
mmi1:
component: mmi1x2
settings:
width_mmi: 4.5
length_mmi: 10
mmi2:
component: mmi1x2
settings:
width_mmi: 4.5
length_mmi: 5
straight:
component: straight
placements:
mmi2:
x: 100
... |
class Repository(object):
def __init__(self, obj):
self._wrapped_obj = obj
self.language = obj[u'language'] or u'unknown'
self.name = obj[u'full_name']
def __getattr__(self, attr):
if attr in self.__dict__:
return getattr(self, attr)
else:
return g... |
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Deleting model 'Positions'
db.delete_table(u'positions_positions')
# Adding model 'Position'
db.create_table(u'positi... |
"""Utilities for getting directory tree."""
import os
from pathlib import Path
import crayons
from nuke.utils import parse_ignore_file
def fg(text, color):
"""Set text to foregound color."""
return "\33[38;5;" + str(color) + "m" + text + "\33[0m"
def bg(text, color):
"""Set text to background color."""
... |
from collections import Counter
import numpy as np
STARTING_LABEL = '*' # Label of t=-1
STARTING_LABEL_INDEX = 0
def default_feature_func(_, X, t):
"""
Returns a list of feature strings.
(Default feature function)
:param X: An observation vector
:param t: time
:return: A list of feature s... |
"""
Functions to spot hemy regions
"""
import os.path as op
import datetime
from collections import defaultdict, Counter
from tabulate import tabulate
from scipy import stats
import numpy as np
import pybedtools
import pysam
import vcf
from bcbio.distributed.transaction import file_transaction
from bcbio.provenance imp... |
import unittest
import SocketServer, socket
import random, time
import threading
import cStringIO
from datetime import datetime
from shapy import register_settings
register_settings('tests.emulation.settings')
from shapy.emulation.shaper import Shaper
from tests.mixins import ShaperMixin, ServerMixin
from tests.utils i... |
import urllib
from urllib2 import urlopen, quote
import urllib2
import json
import time
import datetime
import csv
import unicodedata
import sys
timestring = time.time()
formatted_timestring = datetime.datetime.fromtimestamp(timestring).strftime('%Y_%m_%d')
search = sys.argv[1]
api_key = 'YOUR_API_KEY'
def query_threat... |
"""Test behavior of headers messages to announce blocks.
Setup:
- Two nodes, two p2p connections to node0. One p2p connection should only ever
receive inv's (omitted from testing description below, this is our control).
Second node is used for creating reorgs.
Part 1: No headers announcements before "sendheaders"
a... |
""" Git Parent model """
from django.db import models
class GitParentEntry(models.Model):
""" Git Parent """
project = models.ForeignKey('gitrepo.GitProjectEntry', related_name='git_parent_project')
parent = models.ForeignKey('gitrepo.GitCommitEntry', related_name='git_parent_commit')
son = models.Forei... |
from character import Trait, Perk
__author__ = "Johannes Hackbarth"
ALL_RACES = {"Deathclaw", "Dog", "Ghoul", "Half Mutant", "Human", "Robot", "Super Mutant"}
ANIMALS = {"Deathclaw", "Dog"}
ROBOTS = {"Robot"}
TRAIT_LIST = [
Trait("Fast Metabolism",
"Your metabolic rate is twice normal. This means that you... |
from gdsfactory.port import csv2port
def test_csv2port(data_regression):
import gdsfactory as gf
name = "straight"
csvpath = gf.CONFIG["gdsdir"] / f"{name}.ports"
ports = csv2port(csvpath)
data_regression.check(ports) |
import logging
import struct
import threading
import serial
import serial.tools.list_ports
COMMAND_TO_CHANNEL = {
'F': 0x00,
'W': 0x01,
'H': 0x02,
'C': 0x03
}
class SerialPort(object):
def __init__(self, port_name):
self.port_name = port_name
self.serial_port = None
self.serial_lock = None
self.log_thread ... |
import json
from jaspyx.visitor import BaseVisitor
class Types(BaseVisitor):
def visit_Num(self, node):
self.output(json.dumps(node.n))
def visit_Str(self, node):
self.output(json.dumps(node.s))
def visit_List(self, node):
self.group(node.elts, prefix='[', infix=', ', suffix=']')
... |
import sys
import gc
import pygame
from pygame.locals import *
from input import *
import snd
TICKS_PER_SECOND = 25
GAMETICKS = 1000 / TICKS_PER_SECOND
def set_game_speed( slowdown ):
global TICKS_PER_SECOND
global GAMETICKS
TICKS_PER_SECOND = int( 25 * slowdown )
GAMETICKS = 1000 / TICKS_PER_SECOND
cla... |
import os
import threading
import random
import time
import json
import copy
import errno
import traceback
from functools import partial
from collections import defaultdict
from numbers import Number
from decimal import Decimal
import sys
from .i18n import _
from .util import (NotEnoughFunds, PrintError, UserCancelled,... |
import asyncio
import aiohttp
import async_timeout
import atexit
import re
import json
from .. import exception
from ..api import _methodurl, _which_pool, _fileurl, _guess_filename
_loop = asyncio.get_event_loop()
_pools = {
'default': aiohttp.ClientSession(
connector=aiohttp.TCPConnector(limit=1... |
import argparse
import os
import sys
import numpy as np
import matplotlib.pyplot as plt
from perf.errsim import *
def plot_x_vs_pmf(params, show=True, fpath=None):
def plot(ax, x, param, **plotargs):
if param['pb'] is None:
param['pb'] = param['pe']
label = 'BSC pe={pe} m={m} n={n}'... |
"""
Unit tests for the Grammar class and for the GrammarAnalyzer class.
Tests each grammar in the "grammars" folder against a variety of strings.
"""
import unittest
from grammar import Grammar
from grammaranalyzer import GrammarAnalyzer
class TestGrammar(unittest.TestCase):
def test_nonexistent_file(self):
# Ensure... |
import re
import datetime
from pymongo import MongoClient
from bson import ObjectId
from .exception import RecorderException, StructureException
__all__ = ['get_database', 'Recorder', 'Structure']
def get_database(db_name, host, port=27017):
return MongoClient(host, port)[db_name]
class Structure(dict):
__store... |
import graphene
from graphene_django.types import DjangoObjectType
from django.contrib.auth import (get_user_model, authenticate,
login as auth_login, logout as auth_logout,
update_session_auth_hash)
from django.contrib.auth.forms import (UserCreationFor... |
import asyncio
import sys
import json
from electrum_ltc.network import Network
from electrum_ltc.util import create_and_start_event_loop, log_exceptions
from electrum_ltc.simple_config import SimpleConfig
from electrum_ltc import constants
try:
fname1 = sys.argv[1]
fname2 = sys.argv[2] if len(sys.argv) > 2 else... |
from indicator import Indicator
from gi.repository import Gtk
def main():
xf_indicator = Indicator()
Gtk.main() |
from django.http import JsonResponse
from user.models import User
from django.db.models import Q
from django.apps import apps
def user_filter(request, *args, **kwargs):
# 将来的にはpostで、結果に含めるタグを選択できるようにしたい。
query = Q()
user = request.user
tags = user.follow_tag.all()
if len(tags) > 0:
Tag = app... |
from flask.blueprints import Blueprint
import logging
from flask_login import login_required, current_user
from waitlist.ts3.connection import send_poke
from flask import jsonify
bp = Blueprint('api_ts3', __name__)
logger = logging.getLogger(__name__)
@bp.route("/test_poke")
@login_required
def test_poke():
send_po... |
from util import hash256, hash_pks
from copy import deepcopy
class AggregationInfo:
"""
AggregationInfo represents information of how a tree of aggregate
signatures was created. Different tress will result in different
signatures, due to exponentiations required for security.
An AggregationInfo is r... |
import csv
import logging
import ntpath
import re
import sys
from uuid import UUID
from django.conf import settings
from django.contrib.auth.hashers import make_password
from django.core.exceptions import ValidationError
from django.core.management.base import CommandError
from django.utils import translation
from djan... |
import matplotlib, os, errno
if not('DISPLAY' in os.environ):
matplotlib.use("Agg")
import matplotlib.pyplot as plt
import numpy as np
def visualize_history(hi, show=True, save=False, save_path='', show_also='', custom_title=None):
# Visualize history of Keras model run.
'''
Example calls:
hi = mode... |
from __future__ import absolute_import, unicode_literals
from django.core.urlresolvers import reverse
from django.views.generic import DetailView, ListView, RedirectView, UpdateView
from django.contrib.auth.mixins import LoginRequiredMixin
from .models import User
class UserDetailView(LoginRequiredMixin, DetailView):
... |
from django.db import models
from django.contrib.auth.models import User
from video.models import Video
class Comment(models.Model):
author = models.ForeignKey(User)
video = models.ForeignKey(Video)
content = models.TextField()
time = models.DateTimeField(auto_now=True, auto_now_add=True) |
'''
Created on 16 Sep 2016
@author: rizarse
'''
import jks, textwrap, base64
from os.path import expanduser
import os.path
import atexit
import shutil
from os import makedirs
class JksHandler(object):
def __init__(self, params):
pass
@staticmethod
def writePkAndCerts(ks, token):
uid = None
... |
"""
homeassistant.components.sensor.netatmo
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
NetAtmo Weather Service service.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/sensor.netatmo/
"""
import logging
from datetime import timedelta
from homeassistant.compon... |
__author__ = 'mwagner'
from PyQt4.Qt import Qt
from PyQt4.QtGui import QDialog, QIcon
from ..view.Ui_VertexDialog import Ui_VertexDialog
from ..model.VertexToolsError import *
class VertexDialog(QDialog, Ui_VertexDialog):
def __init__(self, plugin, parent=None):
super(VertexDialog, self).__init__(parent)
... |
'''
ÏÂÀý չʾÁË traceback Ä£¿éÔÊÐíÄãÔÚ³ÌÐòÀï´òÓ¡Òì³£µÄ¸ú×Ù·µ»Ø(Traceback)ÐÅÏ¢, ÀàËÆÎ´²¶»ñÒ쳣ʱ½âÊÍÆ÷Ëù×öµÄ.
'''
import traceback
try:
raise SyntaxError, "example"
except:
traceback.print_exc() |
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... |
from office365.directory.identities.identity_set import IdentitySet
from office365.entity import Entity
class CallRecord(Entity):
"""Represents a single peer-to-peer call or a group call between multiple participants,
sometimes referred to as an online meeting."""
@property
def join_web_url(self):
... |
import time
import numpy.numarray as na
import math
import os
import sys
import yaml
import m3.unit_conversion as m3u
from m3qa.calibrate import *
from m3qa.calibrate_sensors import *
from m3qa.calibrate_actuator_ec_r2 import *
import m3.actuator_ec_pb2 as aec
import m3qa.config_head_s2r2 as s2r2
config_default_s2_j0={... |
year = 2015
print(year) |
from lintreview.review import Problems
from lintreview.review import Comment
from lintreview.tools.shellcheck import Shellcheck
from lintreview.utils import in_path
from unittest import TestCase
from unittest import skipIf
from nose.tools import eq_
shellcheck_missing = not(in_path('shellCheck'))
class Testshellcheck(T... |
import sys
sys.path.append('../')
import Graffity
import numpy
import PlotTools
import glob
import astropy.io.fits as pyfits
from scipy import optimize
from os import walk
from os.path import join
def fitGaussian(x, y):
errfunc = lambda p, x, y: numpy.abs(p[0]*numpy.exp(-(x**2.0)/(2*p[1]**2.0)) - y)
coeffs = [3... |
"""Initial Structure (Creating test and page tables)
Revision ID: 6aab1ac34c3
Revises: None
Create Date: 2015-07-19 12:58:04.968533
"""
revision = '6aab1ac34c3'
down_revision = None
from alembic import op
import sqlalchemy as sa
def upgrade():
### commands auto generated by Alembic - please adjust! ###
op.creat... |
from msrest.serialization import Model
class EventsApplicationInfo(Model):
"""Application info for an event result.
:param version: Version of the application
:type version: str
"""
_attribute_map = {
'version': {'key': 'version', 'type': 'str'},
}
def __init__(self, *, version: str=... |
from httoop.status.types import StatusException
from httoop.uri import URI
class RedirectStatus(StatusException):
u"""REDIRECTIONS = 3xx
A redirection to other URI(s) which are set in the Location-header.
"""
location = None
def __init__(self, location, *args, **kwargs):
if not isinstance(location, (type(None),... |
from typing import Sequence
from numbers import Number
from tabulate import tabulate
class Matrix(Sequence):
def __init__(self, matrix: Sequence[Sequence[float]]):
assert (isinstance(matrix, Sequence) and
isinstance(matrix, Sequence)), "Wrong data"
self.__matrix = [[float(x) for x in... |
class MemoryStorage(object):
"""
Simple(dummy) in-memory storage
In production better to use some database. Written to describe the api and testing
"""
def __init__(self, config):
# configuration of channels and services provided by application
self.config = config
# Storage ... |
from pyvisdk.thirdparty import Enum
PerfFormat = Enum(
'csv',
'normal',
) |
from app import db
import datetime
from geoalchemy2 import Geometry
from sqlalchemy.dialects import postgresql
from sqlalchemy.dialects.postgresql import UUID
from sqlalchemy import Column
import sqlalchemy
from slugify import slugify
from flask.ext.login import UserMixin
class User(UserMixin, db.Model):
__tablenam... |
from flask import Flask, render_template, send_from_directory, request
from settings import getDatabaseString
import os
import time
import psycopg2
app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = 'uploads'
def genFilename(s):
arr_s = s.split('.')
t = time.strftime("%d-%m-%Yh%Hm%Ms%S", time.localtime())
... |
from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar, Union
import warnings
from azure.core.async_paging import AsyncItemPaged, AsyncList
from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error
from azure.core.pip... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.