content stringlengths 4 20k |
|---|
from django.conf import settings
from django.contrib.gis.geos import GEOSGeometry
from rest_framework import serializers
from rest_framework.fields import empty
from rest_framework.utils import model_meta
from issues.api.utils import XMLDict
from issues.excs import MultipleJurisdictionsError
from issues.extensions imp... |
# -*- coding:utf-8 -*-
# Created by Vaayne at 2016/07/23 08:17
from gevent.monkey import patch_all
patch_all()
from gevent.pool import Pool
from .spider import Spider
from bs4 import BeautifulSoup
class FlyerTea(Spider):
def __init__(self):
super().__init__()
self.category = '信用卡'
self.spi... |
import collections
import datetime
import os.path
import tempfile
from django.conf import settings
from django.utils.functional import cached_property
import freezegun
import mock
import pytest
import six
from babel import Locale
from olympia import amo
from olympia.addons.models import Addon
from olympia.amo.tests... |
#!/usr/bin/python
from libbuild import *
import os, sys, winreg, argparse
POLICY_TAG_AND_PUSH = 0
POLICY_TAG = 1
POLICY_REUSE = 2
class PushAction(argparse.Action):
def __call__(self, parser, namespace, values, option_string=None):
setattr(namespace, self.dest, POLICY_REUSE)
setattr(namespace, "tag", values)
p... |
# coding: utf-8
from __future__ import unicode_literals
import calendar
import re
import time
from .amp import AMPIE
from .common import InfoExtractor
from .youtube import YoutubeIE
from ..compat import compat_urlparse
class AbcNewsVideoIE(AMPIE):
IE_NAME = 'abcnews:video'
_VALID_URL = r'''(?x)
... |
from __future__ import (absolute_import, division, print_function,
unicode_literals)
import six
import warnings
import numpy as np
from numpy.testing import assert_almost_equal
from nose.tools import eq_
from matplotlib.transforms import Bbox
import matplotlib
import matplotlib.pyplot as plt
... |
from mitmproxy.models import decoded
from plugins.extension.plugin import PluginTemplate
"""
Description:
This program is a core for wifi-pumpkin.py. file which includes functionality
plugins for Pumpkin-Proxy.
Copyright:
Copyright (C) 2015-2016 Marcos Nesster P0cl4bs Team
This program is free softwar... |
import thread
import curses
from time import sleep
from math import floor
"""
append_cmd_bar
"""
def append_cmd_bar(scr, options):
yx = scr.getmaxyx()
x = yx[1] - 1
yx = (yx[0], x)
bars = []
for i, option in enumerate(options):
if len(option['name']) > yx[1]:
# trim if long... |
# -*- coding: utf-8 -*-
"""This file is part of the TPOT library.
TPOT was primarily developed at the University of Pennsylvania by:
- Randal S. Olson (<EMAIL>)
- Weixuan Fu (<EMAIL>)
- Daniel Angell (<EMAIL>)
- and many more generous open source contributors
TPOT is free software: you can redistribu... |
from .switcher import SwitcherNode
from ebu_tt_live.documents import EBUTT3Document, EBUTT3DocumentSequence
class HandoverNode(SwitcherNode):
"""
The handover node implements the functionality described in EBU-3370. It is a specialised case
of the switching node basing its decisions on the handover-relate... |
#python library
import matplotlib.pyplot as plt
import numpy as np
from numpy.random import *
#chainer library
import chainer
import chainer.functions as F
import chainer.links as L
from chainer import training
from chainer import serializers
#python script
import network_structure as nn
import get_dataset as d
impor... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @author: Debroux Léonard <<EMAIL>>
# @author: Kevin Jadin <<EMAIL>>
import sys, os
import configparser
from setup import Setup
from datasets import readDataset
import argparse
import logging as log
from utils import Utils
def getValueForKey(dictionary, key):
if ... |
"""Proxy camera platform that enables image processing of camera data."""
import asyncio
from datetime import timedelta
import io
import logging
from PIL import Image
import voluptuous as vol
from homeassistant.components.camera import (
PLATFORM_SCHEMA,
Camera,
async_get_image,
async_get_mjpeg_stream... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import struct
import socket
from fdfs_client.exceptions import (
FDFSError,
ConnectionError,
ResponseError,
InvaildResponse,
DataError
)
## define FDFS protol constans
TRACKER_PROTO_CMD_STORAGE_JOIN = 81
FDFS_PROTO_CMD_QUIT = 8... |
# coding=utf-8
from __future__ import print_function
import os.path
from functools import wraps
from operator import attrgetter
try:
from urlparse import urlparse
except ImportError:
from urllib.parse import urlparse
from db import DB
from IPython.core.magic import Magics, magics_class, line_magic
def get_... |
"""
https://leetcode.com/problems/longest-palindromic-substring/
Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.
Example:
Input: "babad"
Output: "bab"
Note: "aba" is also a valid answer.
Example:
Input: "cbbd"
Output: "bb"
"""
class Solutio... |
from PyQt5 import QtCore, QtNetwork
import logging
import json
from config import Settings
logger = logging.getLogger(__name__)
class ApiBase(QtCore.QObject):
def __init__(self, route):
QtCore.QObject.__init__(self)
self.url = QtCore.QUrl(Settings.get('api') + route)
self.manager = QtNet... |
import random
import threading
from twisted.python import failure
from twisted.python import threadable
from twisted.internet import error, address, abstract
from BTL.circular_list import CircularList
from BTL.Lists import QList
from BTL.decorate import decorate_func
debug = False
class HookedFactory(object):
... |
"""Various helper functions implemented by pytube."""
import functools
import gzip
import json
import logging
import os
import re
import warnings
from typing import Any, Callable, Dict, List, Optional, TypeVar
from urllib import request
from pytube.exceptions import RegexMatchError
logger = logging.getLogger(__name__... |
DJANGOSOLR_ID_FIELD = 'id'
DJANGOSOLR_TYPE_FIELD = 'type'
DJANGOSOLR_FIELD_MAPPING = {
'django.db.models.fields.AutoField': 'djangosolr.documents.fields.IntegerField',
'django.db.models.fields.IntegerField': 'djangosolr.documents.fields.IntegerField',
'django.db.models.fields.BigIntegerField': 'djangosolr.... |
"""
This script visualizes the connectivity of the C. elegans nervous system.
"""
display.setViewDimensions(3)
display.setShowNeuronNames(True)
display.setLabelsFloatOnTop(True) # in case the user switches to 2D
# Load the base network.
if not any(network.neurons()):
execfile('Neurons.py')
# Remove unconnected... |
import ctypes
from itertools import chain
from numpy import array, dot, ravel
from math import radians, pi, sin, cos
from pi3d.constants import *
from pi3d.Buffer import Buffer
from pi3d.Light import Light
from pi3d.util import Utility
from pi3d.util.Loadable import Loadable
class Shape(Loadable):
"""inherited by... |
import sublime
import sublime_plugin
from ..core import ContextHelper
###----------------------------------------------------------------------------
class OverrideAuditToggleOverrideCommand(ContextHelper,sublime_plugin.TextCommand):
"""
Swap between editing an override or diffing it based on the current s... |
"""Generate high-scoring boards in the game of Boggle. A good domain for
iterative-repair and related search tehniques, as suggested by Justin Boyan."""
import random, time, bisect, math, string
##_____________________________________________________________________________
cubes16 = ['FORIXB', 'MOQABJ', 'GURILW', ... |
from resources.common import RadialOptions
from services.sui.SUIService import MessageBoxType
from services.SurveyService import createSurveyRangeSUIWindow
from services.sui.SUIWindow import Trigger
from java.util import Vector
import sys
def createRadial(core, owner, target, radials):
#(byte parentId, short optionId... |
from __future__ import absolute_import
import logging
from . import utils
_UDEVADM = utils.CommandPath("udevadm", "/sbin/udevadm", "/usr/sbin/udevadm")
class Error(Exception):
def __init__(self, rc, out, err):
self.rc = rc
self.out = out
self.err = err
def __str__(self):
ret... |
"""
sentry.utils.cursors
~~~~~~~~~~~~~~~~~~~~
:copyright: (c) 2010-2014 by the Sentry Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
from __future__ import absolute_import
import six
from collections import Sequence
class Cursor(object):
def __init__(self, value, offset=0,... |
from __future__ import absolute_import
import pickle
from kombu import Connection, Exchange, Producer, Queue, binding
from kombu.exceptions import NotBoundError
from .case import Case, Mock, call
from .mocks import Transport
def get_conn():
return Connection(transport=Transport)
class test_binding(Case):
... |
from spack import *
import os
import glob
class Ompss(Package):
"""OmpSs is an effort to integrate features from the StarSs programming
model developed by BSC into a single programming model. In
particular, our objective is to extend OpenMP with new directives
to support asynchronous parallel... |
"""Puts the check_parallel system under test"""
# Copyright (c) 2020-2021 Pierre Sassoulas <<EMAIL>>
# Copyright (c) 2020 Frank Harrison <<EMAIL>>
# Copyright (c) 2021 Marc Mueller <<EMAIL>>
# Licensed under the GPL: https://www.gnu.org/licenses/old-licenses/gpl-2.0.html
# For details: https://github.com/PyCQA/pylint/... |
"""
urlresolver XBMC Addon
Copyright (C) 2011 t0mm0, JUL1EN094
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 v... |
"""
Jupyter notebook converter to rst file
author: Atsushi Sakai
"""
import subprocess
import os.path
import os
import glob
NOTEBOOK_DIR = "../"
def get_notebook_path_list(ndir):
path = glob.glob(ndir + "**/*.ipynb", recursive=True)
return path
def convert_rst(rstpath):
with open(rstpath, "r") as ... |
import avango.osg
import avango.shade
import avango.display
import sys
argv = avango.display.init(sys.argv)
view = avango.display.make_view()
view.EnableTrackball.value = True
def make_sphere():
dependencies = []
image_loader = avango.osg.nodes.LoadImage(Filename="pattern.dds")
dependencies.append(image_l... |
"""
Tests for the wrapping layer that provides the XBlock API using XModule/Descriptor
functionality
"""
from nose.tools import assert_equal # pylint: disable=E0611
from unittest.case import SkipTest
from mock import Mock
from xblock.field_data import DictFieldData
from xblock.fields import ScopeIds
from xmodule.x_... |
from __future__ import unicode_literals
import re
from django.apps import apps
from django.core.serializers import serialize
from django.utils import timezone
class Anonymizer(object):
def __init__(self, *args, **kwargs):
super(Anonymizer, self).__init__(*args, **kwargs)
@staticmethod
def anony... |
import pytest
import ulmo
import test_util
def test_get_stations():
stations_file = 'usace/swtwc/shefids.html'
with test_util.mocked_urls(stations_file):
stations = ulmo.usace.swtwc.get_stations()
test_stations = [
{'code': u'DSNT2', 'description': u'Lake Texoma, Denison Dam'},
{... |
"""
Ephemeral Elliptic Curve Diffie-Hellman (ECDH) key exchange
RFC 5656, Section 4
"""
from hashlib import sha256, sha384, sha512
from paramiko.message import Message
from paramiko.py3compat import byte_chr, long
from paramiko.ssh_exception import SSHException
from cryptography.hazmat.backends import default_backend
... |
"""
VGG_A Benchmark
https://github.com/soumith/convnet-benchmarks
./vgg_a.py
./vgg_a.py -d f16
"""
from neon import NervanaObject
from neon.util.argparser import NeonArgparser
from neon.initializers import Gaussian
from neon.layers import Conv, Pooling, GeneralizedCost, Affine
from neon.optimizers import GradientDesc... |
import unittest
from waldur_core.logging import serializers, loggers
class HookSerializerTest(unittest.TestCase):
def setUp(self):
self.events = loggers.get_valid_events()[:3]
def test_valid_web_settings(self):
serializer = serializers.WebHookSerializer(data={
'event_types': self... |
from datetime import datetime, timedelta
import re
from openerp import api, fields, models, _
from openerp.osv import osv
def delta_now(**kwargs):
dt = datetime.now() + timedelta(**kwargs)
return fields.Datetime.to_string(dt)
class ResUsers(models.Model):
_inherit = 'res.users'
password_write_date =... |
#!/usr/bin/env python3
"""."""
import time
import logging
# from scipy.interpolate import UnivariateSpline
# import numpy as np
from labtoolkit.GenericInstrument import GenericInstrument
from labtoolkit.IEEE488 import IEEE488
from labtoolkit.SCPI import SCPI
class EnviromentalChamber(GenericInstrument):
def __in... |
import collections
import os
import subprocess
import textwrap
BASEDIR = os.path.split(os.path.realpath(__file__))[0] + "/../../"
if __name__ == "__main__":
os.chdir(BASEDIR)
opt_file = open("cinder/opts.py", 'w')
opt_dict = collections.OrderedDict()
dir_trees_list = []
REGISTER_OPTS_STR = "CONF.... |
"""Exporter programmatic API."""
from __future__ import absolute_import, print_function
from zenodo.modules.records.fetchers import zenodo_record_fetcher
from zenodo.modules.records.serializers import json_v1
from .streams import BZip2ResultStream
from .writers import BucketWriter, filename_factory
EXPORTER_BUCKET_... |
import collections
import logging
import sys
import pytest
pytest_plugins = 'aiohttp.pytest_plugin'
_LoggingWatcher = collections.namedtuple("_LoggingWatcher",
["records", "output"])
class _CapturingHandler(logging.Handler):
"""
A logging handler capturing all (raw... |
import types
from pyasn1.type import univ
from pysnmp.proto import rfc1155, rfc1157, error
from pysnmp import nextid
# Shortcuts to SNMP types
Integer = univ.Integer
OctetString = univ.OctetString
Null = univ.Null
ObjectIdentifier = univ.ObjectIdentifier
IpAddress = rfc1155.IpAddress
NetworkAddress = rfc1155.NetworkA... |
from rest_framework import permissions
from rest_framework import exceptions
from ovp_organizations.models import Organization, OrganizationInvite
class OwnsOrIsOrganizationMember(permissions.BasePermission):
def has_object_permission(self, request, view, obj):
if request.user.is_authenticated:
if obj.owne... |
"""wxView.py - a simple view for ZODB files
TODO:
-Support ZEO
-Rewrite/extend to use the builtin HTTP server a la pydoc
"""
import UserDict
import UserList
import locale
import os
import os.path
import sys
import wx
import ZODB
from ZODB import FileStorage, DB
from persistent import Persistent
from BTrees... |
"""
A tool for quickly and easily updating information on live MTG Streams
By: Jeff Hoogland
"""
import sys, os
from PySide.QtGui import *
from PySide.QtCore import *
from ui_mainWindow import Ui_mainWindow
##Dialog windows broken out into seperate files to manage things easier
from lifeWindow import lifeWindow
cla... |
from __future__ import print_function
import logging
import sys
import gphoto2 as gp
def main():
logging.basicConfig(
format='%(levelname)s: %(name)s: %(message)s', level=logging.WARNING)
callback_obj = gp.check_result(gp.use_python_logging())
camera = gp.Camera()
camera.init()
text = cam... |
"""
A collection of utility functions used by aseba_prep.py and aseba_reformat.py
"""
from __future__ import print_function
from __future__ import division
from builtins import str
from builtins import range
from past.utils import old_div
import pandas as pd
import re
def process_demographics_file(filename):
"""
... |
"""Self-test suite for Crypto.Cipher.ARC2"""
import unittest
from Crypto.Util.py3compat import b, bchr
from Crypto.Cipher import ARC2
# This is a list of (plaintext, ciphertext, key[, description[, extra_params]]) tuples.
test_data = [
# Test vectors from RFC 2268
# 63-bit effective key length
('000000... |
import contextlib
import os
import sys
import shlex
import pytest
from conda_build.conda_interface import PY3
from conda_build.metadata import MetaData
from conda_build.utils import on_win
def get_root_dir():
import conda_build
conda_build_dir = os.path.realpath(os.path.dirname(conda_build.__file__))
r... |
"""
A place for code to be called from core C-code.
Some things are more easily handled Python.
"""
from __future__ import division, absolute_import, print_function
import re
import sys
from numpy.compat import asbytes, basestring
from .multiarray import dtype, array, ndarray
import ctypes
from .numerictypes import... |
import click
import logging
import requests
from requests.adapters import HTTPAdapter
from six.moves.http_client import HTTPConnection
import sys
import types
from girder_client import GirderClient, __version__
_logger = logging.getLogger('girder_client.cli')
class GirderCli(GirderClient):
"""
A command line... |
#!/usr/bin/env python3
"""
Pandoc filter to process code blocks with class "ly" containing
Lilypond notation. Assumes that Lilypond and Ghostscript are
installed, plus [lyluatex](https://github.com/jperon/lyluatex) package for
LaTeX, with LuaLaTeX.
"""
import os
from sys import getfilesystemencoding, stderr
from sub... |
#!/usr/bin/env python
import sys, re, time
import getopt, os, urllib, subprocess as sub
import urllib2
import json
import nltk
import pprint
from weathercom import get_weathercom
from tree import traverse
from google_api import get_google_asr
from tts import tts
# city? idk wut is this whole dame things. lol
lo = ""... |
"""This module provides a discovery mechanism for LIGO_LW XML trigger
files written on the LIGO Data Grid according to the conventions in
LIGO-T1300468.
"""
import glob
import os.path
import re
import datetime
import warnings
from collections import OrderedDict
try:
from urllib.parse import urlparse
except Import... |
from cupy._math import ufunc
sinh = ufunc.create_math_ufunc(
'sinh', 1, 'cupy_sinh',
'''Elementwise hyperbolic sine function.
.. seealso:: :data:`numpy.sinh`
''')
cosh = ufunc.create_math_ufunc(
'cosh', 1, 'cupy_cosh',
'''Elementwise hyperbolic cosine function.
.. seealso:: :data:`num... |
"""
Unit Tests for Auth Systems
"""
import unittest
import models
from django.db import IntegrityError, transaction
from django.test.client import Client
from django.test import TestCase
from django.core import mail
from auth_systems import AUTH_SYSTEMS
class UserModelTests(unittest.TestCase):
def setUp(self... |
# -*- coding: utf-8 -*-
"""Exception classes, generated from the Telepathy spec
Copyright © 2005-2010 Collabora Limited
Copyright © 2005-2009 Nokia Corporation
This library 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 Fre... |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'badblocks-gui.ui'
#
# by: PyQt4 UI code generator 4.10.4
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore, QtGui
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
def _fromUtf8(s)... |
#!/usr/bin/env python3
from aiohttp import web
import aiohttp
import asyncio
import math
data = open('kotek.jpg', 'rb').read()
speed = 50 * 1000
chunk_size = 1000
chunk_timeout = chunk_size / speed
content_type = 'image/jpeg'
class SlowResponse(web.StreamResponse):
def __init__(self, *, status, reason, body, cont... |
#!/usr/bin/python
"""
Bulk moves open Ship problems described by a query, predicate, or a milestone
to a destination milestone.
"""
import sys
import argparse
import traceback
def prompt(msg=None, resp=False):
if msg is None:
msg = 'Confirm'
if resp:
msg = '%s [%s]|%s: ' % (msg, 'y', 'n')
else:
ms... |
from wataru.logging import getLogger
import sys
import os
import os.path
import re
from importlib.machinery import SourceFileLoader
import wataru.settings as settings
import yaml
logger = getLogger(__name__)
DEFAULT_PATH = os.path.join(settings.WATARU_BASE_DIR_PATH, 'rules', 'themes', 'default')
DEFAULT_NAME = 'def... |
'''
Created on Mar 6, 2011
@author: eplaster
'''
from suds import MethodNotFound
import logging
import os.path
import suds
import urllib
log = logging.getLogger(__name__)
log.setLevel(logging.INFO)
WSDL_DIR = os.path.join(os.path.abspath(os.path.dirname(__file__)), 'wsdl')
class SudsClientFactory(object):
_clie... |
from test_framework.test_framework import crimsonTestFramework
from test_framework.util import *
class BIP65Test(crimsonTestFramework):
def __init__(self):
super().__init__()
self.num_nodes = 3
self.setup_clean_chain = False
def setup_network(self):
self.nodes = []
self... |
# NOTE - It is a known issue that the keyboard-related functions don't work on Ubuntu VMs in Virtualbox.
import pyautogui
import sys
import os
from Xlib.display import Display
from Xlib import X
from Xlib.ext.xtest import fake_input
import Xlib.XK
BUTTON_NAME_MAPPING = {'left': 1, 'middle': 2, 'right': 3, 1: 1, 2: 2... |
from collections import OrderedDict
from distutils import util
import os
import re
from typing import Callable, Dict, Optional, Sequence, Tuple, Type, Union
import pkg_resources
from google.api_core import client_options as client_options_lib # type: ignore
from google.api_core import exceptions as core_exceptions ... |
import csp
startd = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]#'K']
puzzle = [['E','L','F'],['E','L', 'F'],['F','O','O','L']]
domains = {
'E': startd,
'L': startd,
'F': startd,
'O': startd,
'S1': [0,10],
'S2': [0,10],
'S3': [0,10],
'C1': [0,1],
'C2': [0,1],
'C3': [0,1],
}
E= domains[0][0]
L... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from runner.koan import *
class AboutComprehension(Koan):
def test_creating_lists_with_list_comprehensions(self):
feast = ['lambs', 'sloths', 'orangutans', 'breakfast cereals',
'fruit bats']
comprehension = [delicacy.capitalize() for... |
from __future__ import absolute_import
import posixpath
import errno
from urlparse import urlparse
from django.contrib.auth.models import User
from aws.conf import has_s3_access
from aws.s3 import S3A_ROOT
from aws.s3.s3fs import S3FileSystemException
class ProxyFS(object):
def __init__(self, filesystems_dict,... |
import uuid
from mongoengine import Document, StringField, IntField, ListField
from mongoengine import UUIDField
from django.conf import settings
from crits.core.crits_mongoengine import CritsBaseAttributes, CritsSourceDocument
from crits.core.crits_mongoengine import CritsDocument, CritsSchemaDocument
from crits.cor... |
import json
import webob.exc
import webob.dec
from webob import Request
from nova import test
from nova.api import openstack
from nova.api.openstack import faults
from nova.tests.api.openstack import fakes
class APITest(test.TestCase):
def _wsgi_app(self, inner_app):
# simpler version of the app than ... |
from __future__ import print_function, unicode_literals
import re
from sickbeard import logger, tvcache
from sickbeard.bs4_parser import BS4Parser
from sickrage.helper.common import convert_size, try_int
from sickrage.providers.torrent.TorrentProvider import TorrentProvider
class Torrent9Provider(TorrentProvider):
... |
import MySQLdb as mdb
import logging
from openerp.tools.config import config
logger = logging.getLogger(__name__)
class mysql_connector(object):
""" Contains all the utility methods needed to talk with a MySQL server
which connection settings are stored in the object mysql.config.settings.
""... |
"""
Copyright (c) 2011,2012 George Dahl
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,
... |
import sys
import time
from boto import dynamodb2
from boto.dynamodb2.table import Table
from boto.dynamodb2.fields import HashKey, RangeKey, GlobalAllIndex
DEFAULT_REGION = 'ap-northeast-1'
class DynamoDBSample():
def __init__(self, region=DEFAULT_REGION):
try:
self.conn = dynamodb2.connect_... |
''' statemanager.py '''
import abc
import socket
import subprocess
HERON_EXECUTION_STATE_PREFIX = "{0}/executionstate/"
HERON_PPLANS_PREFIX = "{0}/pplans/"
HERON_SCHEDULER_LOCATION_PREFIX = "{0}/schedulers/"
HERON_TMASTER_PREFIX = "{0}/tmasters/"
HERON_TOPOLOGIES_KEY = "{0}/topologies"
# pylint: disable=too-many-publ... |
from __future__ import absolute_import
from django import forms
from django.contrib import messages
from django.http import HttpResponseRedirect
from django.utils.translation import ugettext_lazy as _
from sentry.models import (
ApiKey, AuditLogEntry, AuditLogEntryEvent
)
from sentry.web.forms.fields import Origi... |
from django.template import RequestContext
from django.shortcuts import render_to_response
from django.contrib.auth.decorators import login_required
from django.db.models import Q
from django.contrib.auth.models import User
from django.http import HttpResponse
import json
from .models import *
@login_required(login_u... |
'''
Created on 2016
@author: Graham Reid
I imagine that this will be the thing that people are most interested in. It is
just a super simple example of building a word cloud using Andreas Mueller's
word cloud generating code which can be found at:
https://github.com/amueller/word_cloud
'''
import pickle
import nump... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('model', '0003_auto_20151111_0942'),
]
operations = [
migrations.CreateModel(
name='RunnableJob',
fie... |
import get_clean as gc
import get_code as gd
import test as test
import numpy as np
import pandas as pd
import tushare as ts
good=[]
total=0
can_try=0
test_try=0
diff_list=[]
def cal(code):
try:
a=gc.getData(code)
except:
print('{} is wrong'.format(code))
else:
print('{} is running'.fo... |
"""Support for deCONZ switches."""
from homeassistant.components.fan import (
DOMAIN,
SPEED_HIGH,
SPEED_LOW,
SPEED_MEDIUM,
SPEED_OFF,
SUPPORT_SET_SPEED,
FanEntity,
)
from homeassistant.core import callback
from homeassistant.helpers.dispatcher import async_dispatcher_connect
from .const imp... |
#-------------------------------------------------------------------------
# Copyright (c) Microsoft. All rights reserved.
#
# 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://w... |
import os
import numpy
import re
import shutil
import time
import expdir
import sys
import vecquantile
def quant_probe(directory, blob, quantiles=None, batch_size=None):
'''
Adds a [blob]-sort directory to a probe such as conv5-sort,
where the directory contains [blob]-[unit].mmap files for
each unit ... |
#!/usr/bin/env python
import sys
from docutils.core import publish_doctree
from datetime import datetime
class ParseSection(object):
@property
def date(self):
return datetime.strptime(self._meta.get("date"), "%Y-%m-%d")
@property
def unixtime(self):
return int(self.date.strftime("%s... |
import unittest
from lewis.devices.linkam_t95.devices.device import SimulatedLinkamT95
from lewis.devices.linkam_t95.devices.states import DefaultStartedState
from lewis.devices.linkam_t95.interfaces.stream_interface import LinkamT95StreamInterface
from utils import assertRaisesNothing
class TestSimulatedLinkamT95(... |
#!/usr/bin/env python
import csv
from vzgutil.NamedTuple import NamedTuple
from vzgutil.RawFixUtil import fixForSQL
from struct import unpack
from weather.WeatherStation import *
def getWeatherStationInfo_ISH(filename):
print ('Reading '+filename)
wstns = []
wstnfile = open(filename, 'r')
# Eat u... |
import re
import os.path
import hashlib
import logging
import functools
import collections
from debian.deb822 import Dsc
from diffoscope.changes import Changes
from diffoscope.difference import Difference
from .utils.file import File
from .utils.container import Container
logger = logging.getLogger(__name__)
clas... |
# -*- coding: utf-8 -*-
import sys
import threading
from tweepy import API
from tweepy import OAuthHandler
from tweepy import Status
from tweepy.error import TweepError
class TwitterService:
def __init__(self, config: dict):
#
# Twitter related
self._consumer_key = config[... |
import os
import bcrypt
import importlib
from pyinfraboxutils import get_logger, get_env, print_stackdriver
from pyinfraboxutils.db import connect_db
logger = get_logger("migrate")
def get_files(current_schema_version):
dir_path = os.path.dirname(os.path.realpath(__file__))
migration_path = os.path.join(dir_... |
from Screen import Screen
from Components.ActionMap import NumberActionMap
from Components.config import config, ConfigNothing
from Components.Label import Label
from Components.SystemInfo import SystemInfo
from Components.ConfigList import ConfigListScreen
from Components.Sources.StaticText import StaticText
from enig... |
"""Train the model."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import keras
import tensorflow as tf
from ricga import configuration
from ricga import ricga_model
FLAGS = tf.app.flags.FLAGS
tf.flags.DEFINE_string("input_file_pattern", "/home/meteo... |
from collections import Counter
import matplotlib
import matplotlib.pyplot as plt
from numpy import abs, arange, argsort, histogram, hstack, percentile, zeros
from numpy.linalg import norm
from mdla import multivariate_sparse_encode, reconstruct_from_code
matplotlib.use("Agg")
# TODO: use sum of decomposition weig... |
# pylint: disable=function-redefined
from __future__ import unicode_literals
from prompt_toolkit.enums import DEFAULT_BUFFER
from prompt_toolkit.filters import CLIFilter, Always, HasSelection, Condition
from prompt_toolkit.keys import Keys
from prompt_toolkit.utils import suspend_to_background_supported
from .utils i... |
#!/usr/bin/env python
## Generic Utility Functions:
def raw_input_enter():
print 'PRESS ENTER...'
raw_input()
def ellipsis_cut(s,
n=60,
):
s=unicode(s)
if len(s)>n+1:
return s[:n].rstrip()+u"..."
else:
return s
def terminal_siz... |
# -*- coding: utf-8 -*-
"""Patch wxPython to keep a better compatibility across different versions.
The phoenix version of wx.Python is the reference. When a feature have been
modified or is missing in the classic version, the 'classic' lib is patched to
look like the 'phoenix' one.
"""
import wx
# In 'classic' ver... |
import requests
import json
class SearchEngine():
def __init__(self, config):
self.config = config
def getResource(self, resourceId, collectionId):
url = '%s/document/get_doc/%s/%s' % (self.config['SEARCH_API'], collectionId, resourceId)
resp = requests.get(url)
if resp.status_code == 200:
return json.l... |
import sys
import tempfile
import gnupg
import syslog
def failure(why):
syslog.syslog(syslog.LOG_ERR, "firmware verification failed: "+why)
sys.exit(1)
syslog.openlog("OneRNG");
state = 0
public_key = """\
-----BEGIN PGP PUBLIC KEY BLOCK-----
Version: GnuPG v1
mQINBFPXhxIBEADHeR56yhuF77hOErNk6LXTvbNIViVBG/Ss6cHJcn... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.