content string |
|---|
"""
Websocket client for protocol version 13 using the Tornado IO loop.
http://tools.ietf.org/html/rfc6455
Based on the websocket server in tornado/websocket.py by Jacob Kristhammar.
"""
import array
import base64
import functools
import hashlib
import logging
import os
import re
import socket
import struct
import sy... |
"""{
"title": "devices <argument> <name>",
"text": "You can get more info about your devices using arguments like `find`, `value`, `available` or `list`. To get more help about each argument, type `sdbot devices help`",
"mrkdwn_in": ["text"],
"color": "#E83880"
}"""
import re
import json
from datetime i... |
import requests
import re
import json
import sys
import datetime
import logging
from logging.handlers import TimedRotatingFileHandler
import ConfigParser
# Importing db manager
sys.path.insert(0, '../../resource-contextualization-import-db/abstraction')
from DB_Factory import DBFactory
# Importing utils
sys.path.in... |
import time
import threading
from random import choice
from roqba.static.movement_probabilities import ORNAMENTS
from roqba.static.scales_and_harmonies import (ALL_STRICT_HARMONIES,
BASE_HARMONIES,
HARMONIC_INTERVALS,
... |
import bpy
import sys
import os
import stat
import time
##--------------------------OVERRIDES-----------------------------
## PARA ESCENAS NUEVAS
bpy.types.Scene.overrides = bpy.props.StringProperty(default="[]")
## ------------------------------------ APPLY AND RESTORE OVERRIDES -----------------------------------... |
# gamelist.py
#
# Similar to `runnerlist.py`, but lists games instead of runners.
#
import handler
import logging
from google.appengine.runtime import DeadlineExceededError
class GameList( handler.Handler ):
def get( self ):
try:
user = self.get_user( )
if user == self.OVER_QUOTA_... |
#!/usr/bin/python3
import numpy as np
from pathlib import Path
import requests
import cv2
import os
import time
import datetime
import sys
from collections import deque
import iproc
from amscommon import read_sun, read_config
def custom_settings (mode, config):
file = open("/home/pi/fireball_camera/cam_calib/"+mode... |
"""Handler to make calls against the AdWords API."""
import time
from demo import VERSION
from googleads.adwords import AdWordsClient
from googleads.common import ZeepServiceProxy
from googleads.errors import GoogleAdsError
from googleads.oauth2 import GoogleRefreshTokenClient
class APIHandler(object):
"""Handle... |
""" Wrapper of couchdbkit Document and Properties for django. It also
add possibility to a document to register itself in CouchdbkitHandler
"""
import re
import sys
from django.conf import settings
from django.db.models.options import get_verbose_name
from django.utils.translation import activate, deactivate_all, get_... |
from distutils.core import setup
from actstream import __version__
setup(name='django-activity-stream',
version=__version__,
description='Generate generic activity streams from the actions on your '
'site. Users can follow any actors\' activities for personalized streams.',
long_description=ope... |
import contextlib
import logging
import pytest
asyncio = pytest.importorskip("asyncio")
aiohttp = pytest.importorskip("aiohttp")
import vcr # noqa: E402
from .aiohttp_utils import aiohttp_app, aiohttp_request # noqa: E402
def run_in_loop(fn):
with contextlib.closing(asyncio.new_event_loop()) as loop:
... |
import numpy as np
from scipy.stats import norm
from models_helpers import *
from models_dists import *
class ssm(object):
#=========================================================================
# Define model settings
#=========================================================================
nPar ... |
from __future__ import absolute_import, unicode_literals
import sys
import threading
from celery.bin import events
from django.core.management.commands import runserver
from djcelery.app import app
from djcelery.management.base import CeleryCommand
ev = events.events(app=app)
class WebserverThread(threading.Thre... |
__author__ = 'jnelson'
class Tag:
"""
A Tag is a String data type that does not get full-text indexed.
Each Tag is equivalent to its String counterpart. Tags merely exist for the
client to instruct Concourse not to full text index the data. Tags are stored
as Strings within Concourse. And any val... |
import threading
import Queue
from time import sleep
from virtualisation.misc.log import Log as L
__author__ = 'Marten Fischer (<EMAIL>)'
class StoppableThread(threading.Thread):
"""Thread class with a stop() method. The thread itself has to check
regularly for the stopped() condition."""
def __init__(se... |
import xbmc
import json
import xbmcaddon
import xbmcgui
__addon__ = xbmcaddon.Addon('script.lazytv')
__addonid__ = __addon__.getAddonInfo('id')
def lang(id):
san = __addon__.getLocalizedString(id).encode( 'utf-8', 'ignore' )
return san
plf = {"jsonrpc": "2.0","id": 1, "metho... |
class Solution(object):
def bfs(self, s, edges, n):
from collections import deque
queue = deque([(s, 1)])
vis = [0 for i in range(n)]
vis[s] = 1
ret1, ret2 = None, None
while len(queue) > 0:
pos, step = queue.popleft()
# print pos, step
ret1, ret2 = pos, step
if pos in edges:
for nei in edg... |
"""
cellulose.descriptors
Copyright 2006 by Matthew Marshall <<EMAIL>>
This module provides descriptor classes for using cells as if they were class
instance attributes.
"""
from cells import InputCell, ComputedCell
import types
class CellDescriptor(object):
cell_class = None # Subclass should override this
... |
try:
from urllib.parse import quote
except ImportError:
from urllib2 import quote # type: ignore
from azure.core import MatchConditions
from ._models import (
ContainerEncryptionScope,
DelimitedJsonDialect)
from ._generated.models import (
ModifiedAccessConditions,
SourceModifiedAccessConditi... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import xlrd
import datetime
import sys
filename = "file/timesheet.xlsx"
bk = xlrd.open_workbook(filename)
shxrange = range(bk.nsheets)
print(str(shxrange))
try:
sh = bk.sheet_by_name("Sheet1")
except:
print("no sheet in %s named Sheet1" % filename)
#获取行列数
nrows, n... |
from entity import Entity
#avoid reference leaks
import copy
__doc__ = """
Foundational library used by ROMEO to determine relationships
"""
__author__ = "Justin Venus <<EMAIL>>"
def _processKeyValues(adict):
"""inspect dictionaries and lists to determine if relationships exist"""
pending = [adict]
pendl... |
from PyQt4 import QtCore, QtGui
class ImageViewer(QtGui.QMainWindow):
def __init__(self):
super(ImageViewer, self).__init__()
self.printer = QtGui.QPrinter()
self.scaleFactor = 0.0
self.imageLabel = QtGui.QLabel()
self.imageLabel.setBackgroundRole(QtGui.QPalette.Base)
... |
#Adapted from PIC
# This is sample code for learning the basics of the algorithm.
# It's not meant to be part of a production anti-spam system!
# Terrible for a large dataset
import sys
import os
import glob
import re
import math
import sqlite3
from decimal import *
DEFAULT_THRESHOLD = 0.7
def get_words(doc):
""... |
from setuptools import setup, find_packages
from codecs import open
from os import path
__version__ = '0.0.4'
here = path.abspath(path.dirname(__file__))
# Get the long description from the README file
with open(path.join(here, 'README.md'), encoding='utf-8') as f:
long_description = f.read()
# get the dependen... |
import numpy as np
from pandas import *
import tephi
import matplotlib.pyplot as plt
from bng import *
import re
r = re.compile("([a-zA-Z]+)([0-9]+)") # search for letters and numbers only
for i in ['Tfaffdata.csv', 'fitz.csv','eckman.csv']:
a= read_csv(i)
a= a[:-1] #remove last column
a['time']= a['GPS ... |
# -*- coding:utf8 -*-
# File : policy_opt.py
# Email : <EMAIL>
#
# This file is part of TensorArtist.
from .opr import vectorize_var_list
from tartist import random
from tartist.app.rl.utils.math import normalize_advantage
from tartist.core.utils.meta import notnone_property
from tartist.core.utils.nd import nd_ba... |
from model import Track
from log import Log
from mathutil import FindLocalMaximums,Mean,GeodeticCourse
from conversions import TimeDeltaToSeconds
from options import options
class MaxSpd:
def __init__(self,spd,dst,time,ptfrom,ptto,ptfromid,pttoid,course,type):
self.spd=spd
self.dst=dst
self... |
from climate.manager import exceptions
from climate import tests
from climate.utils.openstack import base
class TestBaseStackUtils(tests.TestCase):
def setUp(self):
super(TestBaseStackUtils, self).setUp()
self.base = base
self.service_type = 'fake_service'
self.url = 'http://%s-... |
from sys import setrecursionlimit
from collections import defaultdict
from itertools import imap
def dfs(G, prev_id, u, stk, lookup, result):
for i, v in G[u]:
if ~i == prev_id:
continue
if v not in lookup:
lookup[v] = len(lookup)+1
stk.append((i, v))
... |
#!/usr/bin/env python
from __future__ import division
import numpy as np
import numpy.matlib as npm
import numpy.linalg as npl
from cvxopt import matrix, solvers
class Controller:
""" Define control law """
def __init__(self, number, T):
""" Initialise the controller """
self.u = n... |
import re
from srttimeadjuster.srtdataset import SrtDataSet
# def test():
# streamer = SrtStreamer("/home/hoo/Desktop/lesrivierespourpres-1cd (modified).srt", "/home/hoo/Desktop/testSrtOut.srt", timedelta(seconds=-5))
# streamer.streamConvert()
class SrtStreamer:
""" simple class to read from an SRT file, con... |
from urllib import parse
import pkg_resources
from spring.cbgen_helpers import backoff, quiet, timeit
cb_version = pkg_resources.get_distribution("couchbase").version
if cb_version[0] == '2':
from couchbase import experimental, subdocument
from couchbase.bucket import Bucket
from couchbase.n1ql import N1... |
#! env python
from __future__ import print_function
from scapy.all import *
from random import Random
from threading import Thread
SOURCE_MAC = '08:00:27:0e:d5:be'
SOURCE_IP = 'fd17:625c:f037:303:a00:27ff:fe0e:d5be'
# debian 6
#TARGET_MAC = '08:00:27:96:8a:f5'
#TARGET_IP = 'fd17:625c:f037:303:a00:27ff:fe96:8af5'
# ... |
import logging
from opentrons import config
from .endpoints import (networking, control, settings, update,
deck_calibration)
log = logging.getLogger(__name__)
class HTTPServer(object):
def __init__(self, app, log_file_path):
self.app = app
self.log_file_path = log_file_p... |
"""
Support for Axis devices.
For more details about this component, please refer to the documentation at
https://home-assistant.io/components/axis/
"""
import logging
import voluptuous as vol
from homeassistant.components.discovery import SERVICE_AXIS
from homeassistant.const import (
ATTR_LOCATION, ATTR_TRIPPE... |
from django.contrib import admin
from django.utils.translation import ugettext_lazy as _
from threadedcomments.models import ThreadedComment, FreeThreadedComment
class ThreadedCommentAdmin(admin.ModelAdmin):
fieldsets = (
(None, {'fields': ('content_type', 'object_id')}),
(_('Parent'), {'fie... |
"""QuizReports API Version 1.0.
This API client was generated using a template. Make sure this code is valid before using it.
"""
import logging
from datetime import date, datetime
from .base import BaseCanvasAPI
from .base import BaseModel
class QuizReportsAPI(BaseCanvasAPI):
"""QuizReports API Version 1.0."""
... |
from xtcli import *
#import unittest
import unittest2
import xmlrunner
class xtclTestCase(unittest2.TestCase):
def setUp(self):
self.xtcCnx = XTCConnector()
def tearDown(self):
self.xtcCnx = None
def testServerName(self):
""" check that an empty server parameter generate an exception """
#self.assertRais... |
import logging
from collections import OrderedDict
from typing import List
from .utils import random_password
from .rgw import RGWAdmin
from .exceptions import NoSuchKey
log = logging.getLogger(__name__)
class AttributeMixin(object):
attrs: List[str] = []
def __str__(self):
try:
from q... |
#coding:utf8
'''
#=============================================================================
# Desc: 数据包类
# Email: <EMAIL>
# HomePage: http://www.yiwuye.com
# LastChange: 2013-10-31 22:52:47
# History:
#=============================================================================
'''
impor... |
#!/usr/bin/env python2
# vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai
from __future__ import (unicode_literals, division, absolute_import,
print_function)
__license__ = 'GPL v3'
__copyright__ = '2011, Kovid Goyal <<EMAIL>>'
__docformat__ = 'restructuredtext en'
from calibre.ebooks.metada... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Third party libraries
import tornado.web
# Engine libraries
from engine.search import DefaultSearch
class SearchHandler(tornado.web.RequestHandler):
def initialize(self, database, parser, options, logger):
"""
Initializes the database with parameters... |
import logging
import os
import shutil
import subprocess
import sys
from scripts.lib.zulip_tools import run, run_as_root, ENDC, WARNING
from scripts.lib.hash_reqs import expand_reqs
ZULIP_PATH = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
VENV_CACHE_PATH = "/srv/zulip-venv-cache"
if '... |
# this is a dict of pool specific keys/values. As this fills up and more
# fx build factories are ported, we might deal with this differently
config = {
"staging": {
# if not clobberer_url, only clobber 'abs_work_dir'
# if true: possibly clobber, clobberer
# see PurgeMixin for clobber() con... |
from __future__ import (absolute_import, division, generators, nested_scopes, print_function,
unicode_literals, with_statement)
import logging
import os
import shutil
import six.moves.urllib.parse as urllib_parse
from pants.base.exceptions import TaskError
from pants.fs.archive import archiver... |
from temboo.core.choreography import Choreography
from temboo.core.choreography import InputSet
from temboo.core.choreography import ResultSet
from temboo.core.choreography import ChoreographyExecution
import json
class DeleteMessage(Choreography):
def __init__(self, temboo_session):
"""
Create a... |
from . import AWSObject, AWSProperty
from .validators import positive_integer
def validate_authorizer_ttl(ttl_value):
""" Validate authorizer ttl timeout
:param ttl_value: The TTL timeout in seconds
:return: The provided TTL value if valid
"""
ttl_value = int(positive_integer(ttl_value))
if tt... |
""" -*- coding: utf-8 -*- """
from pprint import pprint
from python2awscli import bin_aws
from python2awscli import must
class BaseRDS(object):
def __init__(self, name, region, engine, size, username, password, gb, zone, groups, public=True):
self.id = None # DbiResourceId
self.name = name # DB... |
"""Affinity Propagation clustering algorithm."""
# Gael Varoquaux <EMAIL>
# License: BSD 3 clause
import numpy as np
from ..base import BaseEstimator, ClusterMixin
from ..utils import as_float_array, check_array
from ..utils.validation import check_is_fitted
from ..metrics import euclidean_distances
from ..m... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import sys
import requests
from requests.compat import is_py3, is_py2
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
if sys.argv[-1] == 'publish':
os.system('python setup.py sdist upload')
sys.exit()
if... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
__author__ = 'Kubert'
# 从使用者的角度来说,aiohttp相对比较底层,编写一个URL的处理函数往往需要
# 1。编写一个用@asyncio.coroutine装饰的函数
# 2.传入的参数需要自己从request中获取
# 3.最后,需要自己构造Response对象
# 这些重复的工作可以由框架完成。
import asyncio, os, inspect, logging, functools
from urllib import parse
from aiohttp import web
from ... |
import bpy
import os
MS = True
AT = True
bpy.context.scene.render.image_settings.file_format = "PNG"
bpy.context.scene.render.image_settings.color_mode = "RGBA"
bpy.context.scene.render.image_settings.color_depth = "8"
bpy.context.scene.view_settings.view_transform = "sRGB EOTF"
bpy.context.scene.view_settings.gamma... |
import django
from django.test import TestCase
from .models import Person
class LiveQuerySetTests(TestCase):
names = (
'Graham Chapman',
'John Cleese',
'Terry Gilliam',
)
def setUp(self):
# Create some soft-deleted records.
for name in self.names[:2]:
... |
#!/usr/bin/env python
from setuptools import setup, find_packages
from codecs import open
from os import path
here = path.abspath(path.dirname(__file__))
with open(path.join(here, 'README.rst'), encoding='utf-8') as f:
long_description = f.read()
import pycdl
requires = []
setup(
name='pycdl',
vers... |
#encoding:utf-8
import json
import sys
import random
import string
import datetime
from flask import render_template,request,redirect,session, flash ,jsonify
from . import app #user模块下的变量,在__init__.py 中定义
from modules.modules import User,Assets,Logs,Performs
#
reload(sys)
sys.setdefaultencoding('utf8')
#解决字... |
"""Data Flow Operations."""
# pylint: disable=g-bad-name
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensorflow.python.framework import ops
from tensorflow.python.ops import control_flow_ops
# go/tf-wildcard-import
# pylint: disable=wildcard-import
... |
"""Harvest process for the WorkInStartups Source."""
import logging
from collections import defaultdict
from remotes.decorators import periodically
from .workinstartups import WorkInStartups
logger = logging.getLogger(__name__)
class Harvester(object):
"""Simple Harvester to gather WorkInStartups posts."""
... |
# -*- coding: utf-8 -*-
import gio
import gtk
import glib
import os
type_ico_load = gtk.ICON_LOOKUP_USE_BUILTIN
get_theme = gtk.icon_theme_get_default()
default_applications_icon = 'applications-internet'
def __get_icon_for_app__(app):
'''
Получение иконки в формате gtk.gdk.Pixbuf по имени в теме либо абсол... |
# 153. Find Minimum in Rotated Sorted Array QuestionEditorial Solution My Submissions
# Total Accepted: 111472
# Total Submissions: 295421
# Difficulty: Medium
# Suppose a sorted array is rotated at some pivot unknown to you beforehand.
#
# (i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2).
#
# Find the minimum elem... |
"""
Pipetypes make up the core functionality of our system.
Once we understand how each one works, we’ll have a better basis for understanding
how they’re invoked and sequenced together in the interpreter.
"""
from functools import partial
from functools import wraps
class GenerativeBase(object):
def _generate(s... |
"""
Runs a program, checking syntax. Does not depend on
the SciSheets context.
"""
from block_execution_controller import BlockExecutionController
from CodeGeneration.statement_accumulator import StatementAccumulator
import exceptions
CONTROLLER = "_program_executer_controller"
class ProgramExecuter(object):
"""... |
"""
image.py
This module provides a simple interface to create a window, load an image and experiment
with image based algorithms. Many of which require pixel-by-pixel manipulation. This
is a educational module, its not intended to replace the excellent Python Image Library, in fact
it uses PIL.
The module and its... |
"""Test for volume availability zone."""
import datetime
import mock
from oslo_utils import timeutils
from cinder.tests.unit import volume as base
import cinder.volume
class AvailabilityZoneTestCase(base.BaseVolumeTestCase):
def setUp(self):
super(AvailabilityZoneTestCase, self).setUp()
self.ge... |
from popserver.lib import model_setup
from popserver.model import *
from popserver.lib.cache.pylons import PopegoDBCachePersistence, PylonsTagManager
from utils.decorator import retry
from popserver.services.sync import updateAccount
import sys
import traceback
# turn off alchemy warnings
import warnings
warnings.fi... |
import demistomock as demisto
from CommonServerPython import *
from CommonServerUserPython import *
""" IMPORTS """
from typing import Dict, Callable, Optional, Any
from collections import OrderedDict
import traceback
import requests
from sixgill.sixgill_request_classes.sixgill_auth_request import SixgillAuthRequest
... |
import os
import pygame
from pygame.constants import RLEACCEL
class Utils(object):
def __init__(self):
pass
@staticmethod
def load_image(name, colorkey=None):
fullname = os.path.join('img', name) + '.png'
try:
image = pygame.image.load(fullname)
except pygame.e... |
from itertools import izip_longest
from django.template.base import Library
from django.conf import settings
register = Library()
"""
for x in x_list
for x,y in xy_list
for x, y in xy_list
for x, y in xy_list reversed
for x in x_list reversed; y in y_list
for x in x_list; y in y_list reversed
"""
from django.templat... |
"""Python representations of C declarations."""
import textwrap
from dm_control.autowrap import codegen_util
from dm_control.autowrap import header_parsing
class CDeclBase:
"""Base class for Python representations of C declarations."""
def __init__(self, **attrs):
self._attrs = attrs
for k, v in attrs.i... |
FUNCTION( 'void* nom_list_scan_start_routine( void* arg )', """
FRAME__LIST_SCAN_1 frame = $C(FRAME__LIST_SCAN_1,arg) ;
JUMP__value( $CA(frame), frame->source ) ;
return NULL ;
""" )
FUNCTION( 'void nom_list_scan_async( FRAME__LIST_SCAN_1 frame )', """
nom_call_async( nom_list_scan_start_routine, $CAST(void*,f... |
from __future__ import annotations
from . import Task, Housekeeping
from . import toposort
import unittest
import os.path
class TestHousekeeping(unittest.TestCase):
def test_run(self):
class TestTask(Task):
run_count = 0
def run_main(self, stage):
TestTask.run_coun... |
from test.picardtestcase import PicardTestCase
from picard.util import tracknum_from_filename
class TracknumTest(PicardTestCase):
def test_matched_tracknum_01(self):
self.assertEqual(tracknum_from_filename('1.mp3'), 1)
def test_matched_tracknum_02(self):
self.assertEqual(tracknum_from_filen... |
import rospy
import argparse
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from modules.drivers.proto import mobileye_pb2
from mobileye_data import MobileyeData
from view_subplot import ViewSubplot
mobileye = MobileyeData()
def update(frame_number):
view_subplot.show(mobileye)
def mo... |
"""Tests for the venv builder module."""
import os
import shutil
import tempfile
import unittest
from datetime import datetime, timedelta
from unittest.mock import Mock, patch, call
from pkg_resources import parse_requirements
import logassert
from fades import FadesError, REPO_PYPI, REPO_VCS
from fades import cach... |
from Cheetah.Template import Template
from morphforge.simulation.neuron.simulationdatacontainers.mhocfile import MHocFileData
from morphforge.simulation.neuron.simulationdatacontainers.mhocfile import MHOCSections
from morphforge.simulation.neuron.core.neuronsimulationenvironment import NEURONEnvironment
from morphfor... |
import time
import subprocess
from subprocess import PIPE
import requests
import ray
from ray import serve
from ray.cluster_utils import Cluster
num_redis_shards = 1
redis_max_memory = 10**8
object_store_memory = 10**8
num_nodes = 5
cluster = Cluster()
for i in range(num_nodes):
cluster.add_node(
redis_p... |
from flask import Flask, request, render_template, flash, redirect, url_for, jsonify, Response
app = Flask(__name__)
from cStringIO import StringIO
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.login import (LoginManager, login_user, logout_user, user_logged_in, current_user, user_logged_out, login_requi... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
""" Business logic - gets request in from Slack, does stuff, sends requests back to Slack.
Notes for developers who want to add or change functionality: You're in the right module.
* If you were to run this behind a server (Flask would work well) instead of behind AWS ... |
import json
from coalib.bearlib.abstractions.Linter import linter
from dependency_management.requirements.NpmRequirement import NpmRequirement
@linter(executable='htmlhint',
output_format='regex',
output_regex=r'(?P<filename>.+):(?P<line>\d+):(?P<column>\d+):\s*'
r'(?P<message>.... |
from sys import stdout
factories = {
"AnalogBar" : "Panel",
"AnimatingImagePanel" : "Panel",
"Button" : "Label",
"CAvatarImagePanel" : "ImagePanel",
"CBitmapImagePanel" : "Panel",
"CCommentaryModelPanel" : "EditablePanel",
"CControllerMap" : "Panel",
"CIconPanel" : "Panel",
"CModelPanel" : "... |
"""Use the DSSP program to calculate secondary structure and accessibility.
You need to have a working version of DSSP (and a license, free for academic
use) in order to use this. For DSSP, see U{http://www.cmbi.kun.nl/gv/dssp/}.
The DSSP codes for secondary structure used here are:
- H Alpha helix (4-12)... |
#! /usr/bin/env python
import xmlrpclib
import datetime
import sys, os
import getopt
import ConfigParser
CONFIG_FILE = '/usr/local/etc/alogger_ws.cfg'
def parse_logs(date, cfg, debug=False):
filename = date.strftime('%Y%m%d')
try:
f = open('%s/%s' % (cfg['LOG_DIR'], filename), 'r')
except:
... |
from __future__ import print_function, division, absolute_import
# Copyright (c) 2016 Red Hat, Inc.
#
# This software is licensed to you under the GNU General Public License,
# version 2 (GPLv2). There is NO WARRANTY for this software, express or
# implied, including the implied warranties of MERCHANTABILITY or FITNES... |
import numpy as np
# @todo: document inputs and outputs
# format_data: gives an array with all the datas formatted and another with the output only
#
# params:
# filename the name of the file to read
# objective the column number of the objective starting from 0
# new_objective the ne... |
class CONF:
def __init__(self):
self.TABLE_NAME = 'table_name'
self.TABLET_NUM = 'tablet_number'
self.KEY_SIZE = 'key_size(B)' # Bytes
self.VALUE_SIZE = 'value_sizeB(B)' # Bytes
self.KEY_SEED = 'key_seed'
self.VALUE_SEED = 'value_seed'
self.STEP = 's... |
"""
=====================================
Sparse matrices (:mod:`scipy.sparse`)
=====================================
.. currentmodule:: scipy.sparse
SciPy 2-D sparse matrix package for numeric data.
Contents
========
Sparse matrix classes
---------------------
.. autosummary::
:toctree: generated/
bsr_matr... |
from simpleline import App
from simpleline.render.screen import UIScreen
from simpleline.render.screen_handler import ScreenHandler
from simpleline.render.widgets import TextWidget, CenterWidget, CheckboxWidget
class HelloWorld(UIScreen):
def __init__(self):
# Set title of the screen.
super().__i... |
import pytest
from django.core.urlresolvers import reverse
from todo.models import Todo
pytestmark = pytest.mark.django_db
@pytest.fixture
def todo_data(bob_barker):
return {
'user': bob_barker.id,
'completed': False,
'name': 'My Todo Item',
}
def test_list(client, bob_barker, incomplete... |
from sympy import (
adjoint, conjugate, DiracDelta, Heaviside, nan, pi, sign, sqrt,
symbols, transpose, Symbol, Piecewise, I, S, Eq, oo,
SingularityFunction, signsimp
)
from sympy.utilities.pytest import raises
from sympy.core.function import ArgumentIndexError
from sympy.utilities.exceptions import SymP... |
import importlib, time, sys, json, kodi_utils, sqlite3, globals, urllib, urlparse
import multiprocessing, gevent, logging, thread
logger = logging.getLogger('TVMLServer')
def progress_stop(responses, stop, _id):
try:
import setproctitle
setproctitle.setproctitle('python TVMLServer (progress dialog... |
from envi.archs.msp430.regs import *
checks = [
# INV
(
'INV R15',
{ 'regs': [(REG_R15, 0x5a5a)], 'flags': [(SR_N, 0), (SR_Z, 0), (SR_C, 0), (SR_V, 0)], 'code': "3fe3", 'data': "" },
{ 'regs': [(REG_R15, 0xa5a5)], 'flags': [(SR_N, 1), (SR_Z, 0), (SR_C, 1), (SR_V, 0)], 'code': "3fe3", 'd... |
# -*- coding: utf-8 -*-
import urwid
import json
from pyquery import PyQuery
import riot.ui.builtin_widgets as builtin
def test_cache_widget():
text = PyQuery('<text/>')
text_w1 = builtin.generate_widget(text)
text_w2 = builtin.generate_widget(text)
assert text_w1 == text_w2
def test_generate_text_wi... |
#!/usr/bin/python
# coding=utf-8
import urllib2
import time
import json
class Pullwave(object):
def __init__(self, word1, word2):
self.word1 = word1
self.word2 = word2
def get_data(self):
date = time.strftime("%Y-%m-%d", time.localtime())
url = 'http://www.pullwave.com/get.php?json=1&auth_usr=free_vip&w1=... |
#!/usr/bin/env python3
#######################
# POTATO Setup Script (From ACE3) #
#######################
import os
import sys
import shutil
import platform
import subprocess
import winreg
######## GLOBALS #########
MAINDIR = "z"
PROJECTDIR = "potato"
##########################
def main():
FULLDIR = "{}\\{}".... |
from msrest.serialization import Model
class ImageStorageProfile(Model):
"""Describes a storage profile.
:param os_disk: Specifies information about the operating system disk used
by the virtual machine. <br><br> For more information about disks, see
[About disks and VHDs for Azure virtual
mac... |
from rest_framework import viewsets
from rest_framework.authentication import SessionAuthentication
from rest_framework.permissions import IsAuthenticated
from rest_framework.exceptions import ValidationError, ParseError
from .models import Category, Feed, Subscription, Item
from .serializers import CategorySerializer... |
from django import forms
from django.core.exceptions import ValidationError
from eventex.subscriptions.models import Subscription
from eventex.subscriptions.validators import validate_cpf
class SubscriptionFormOld(forms.Form):
name = forms.CharField(label='Nome')
cpf = forms.CharField(label='CPF', validators=... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Tests for `hbase_table` module.
"""
import pytest
from HBaseBoard.hbase_table import HBaseTable
from HBaseBoard.hbase_wrapper import HBaseWrapper
class TestHBaseTableClass(object):
def setup(self):
self.hb_wrapper = HBaseWrapper()
self.hb_wrapper... |
from builtins import str
import time
import os, sys
from django.db.models import Q
# setting django environment
from django.core.wsgi import get_wsgi_application
from config import *
sys.path.append(SPOKEN_PATH)
os.environ["DJANGO_SETTINGS_MODULE"] = "spoken.settings"
application = get_wsgi_application()
from youtube... |
#!/usr/bin/env python
# http://www.rabbitmq.com/tutorials/tutorial-two-python.html
# and https://github.com/rabbitinaction/sourcecode/blob/master/python/chapter-5/hello_world_mirrored_queue_consumer.py
import pika
import argparse
argp = argparse.ArgumentParser()
argp.add_argument('-s', '--server', metavar='server',
... |
from CIM14.ENTSOE.Equipment.Core.Curve import Curve
class ReactiveCapabilityCurve(Curve):
"""Reactive power rating envelope versus the synchronous machine's active power, in both the generating and motoring modes. For each active power value there is a corresponding high and low reactive power limit value. Typica... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.