content stringlengths 4 20k |
|---|
from . import Boolean
from . import Column
from . import GenericTable
from . import String
from . import Text
from . import Integer
from . import DateTime
from pyfaf.storage.jsontype import JSONType
import json
class PeriodicTask(GenericTable):
__tablename__ = "periodictasks"
id = Column(Integer, primary_key=... |
import paddle.v2.framework.core
import unittest
class TestScope(unittest.TestCase):
def test_create_destroy(self):
paddle_c = paddle.v2.framework.core
scope = paddle_c.Scope()
self.assertIsNotNone(scope)
scope_with_parent = scope.new_scope()
self.assertIsNotNone(scope_with_... |
__metaclass__ = type
import re
from BeautifulSoup import BeautifulSoup
from lazr.restful.fields import Reference
from zope.formlib.interfaces import (
IBrowserWidget,
IInputWidget,
WidgetInputError,
)
from zope.interface import (
implements,
Interface,
)
from lp.app.validators import Laun... |
"""Test the Roku config flow."""
from homeassistant.components.roku.const import DOMAIN
from homeassistant.config_entries import SOURCE_IMPORT, SOURCE_SSDP, SOURCE_USER
from homeassistant.const import CONF_HOST, CONF_NAME, CONF_SOURCE
from homeassistant.data_entry_flow import (
RESULT_TYPE_ABORT,
RESULT_TYPE_CR... |
import os
from subprocess import Popen, call, PIPE
import random
import time
from pprint import pprint
import json
from typeclassifier import TypeClassifier
class MusicControl:
def __init__(self, xmlDir):
self.classifier = TypeClassifier("fastText/voiceai-music.bin", "fastText/fasttext")
self.cvlc_loaded = Fals... |
from openerp import pooler
from openerp.exceptions import Warning as UserError
from openerp.tools.translate import _
# TODO migrate
def validate(cr, uid, ids, context=None):
strErro = u''
pool = pooler.get_pool(cr.dbname)
if context is None:
context = {}
for inv in pool.get('account.invoice... |
from django import forms
from base.models.organization_address import OrganizationAddress
class OrganizationAddressForm(forms.ModelForm):
class Meta:
model = OrganizationAddress
fields = [
"label",
"location",
"postal_code",
"city",
"cou... |
from . import request
from . import keys
CALLBACK_ENDPOINT = 'http://ec2-54-193-39-226.us-west-1.compute.amazonaws.com/callback'
class ChangeOrgApi(object):
def __init__(self, request_obj=None):
self.base_url = 'http://api.change.org'
if not request_obj:
request_obj = request.ChangeOrg... |
from invenio.ext.sqlalchemy import db
from invenio_upgrader.api import op
from sqlalchemy.dialects import mysql
depends_on = []
def info():
return "Short description of upgrade displayed to end-user"
def do_upgrade():
""" Implement your upgrades here """
op.create_table(
'pages',
db.Co... |
#!/usr/bin/env python
"""Handles depgraph. Generates the dependency graph for the given rules."""
__author__ = '<EMAIL> (Pramod Gupta)'
__copyright__ = 'Copyright 2012 Room77, Inc.'
import itertools
import os
import subprocess
import sys
import time
from pygraph.classes import digraph # $ sudo easy_install python... |
"""Assemble an SQL query.
Using a basic pattern for JOINs with variant annotation databases, assemble
templated SQL into a full query that can but run to create an annotated
"all possible SNPs" table.
"""
from __future__ import absolute_import
import argparse
import logging
import sys
from jinja2 import Environment... |
# -*- coding: iso-8859-1 -*-
""" crypto.cipher.ccm
CCM block cipher mode
The CCM class can wrap any BlockCipher to create a 'CCM' mode
that provides encryption with a strong integrity check. The
integrity check can optionally include unencrypted 'addAuthData'.
CCM requires a nonce that MUST NEVER... |
from rbnics.backends.basic.basis_functions_matrix import BasisFunctionsMatrix
from rbnics.backends.basic.copy import copy
from rbnics.backends.basic.evaluate import evaluate
from rbnics.backends.basic.export import export
from rbnics.backends.basic.functions_list import FunctionsList
from rbnics.backends.basic.gram_sch... |
import os
import re
from typing import List, Tuple
import pandas as pd
import sqlalchemy as sa
from boadata.core.data_conversion import ChainConversion
from boadata.core.data_object import DataObject
from boadata.data.pandas_types import PandasDataFrameBase
@DataObject.register_type()
# @OdoConversion.enable_to("pa... |
from collections import defaultdict
import kevlar
from kevlar.assemble import assemble_fml_asm
from kevlar.localize import localize
from kevlar.call import call
import khmer
import re
def alac(pstream, refrfile, threads=1, ksize=31, maxreads=10000, delta=50,
seedsize=31, maxdiff=None, inclpattern=None, exclp... |
from setuptools import setup, find_packages, Command
import os
class RunTestsCommand(Command):
description = "Test command to run testr in virtualenv"
user_options = []
def initialize_options(self):
self.cwd = None
def finalize_options(self):
self.cwd = os.getcwd()
def run(self):
... |
import os
from setuptools import setup, find_packages
MAIN_MODULE = 'agent'
# Find the agent package that contains the main module
packages = find_packages('.')
agent_package = ''
for package in find_packages():
# Because there could be other packages such as tests
if os.path.isfile(package + '/' + MAIN_MODUL... |
from timeit import default_timer as timer
import threading
import pyautogui
import keyboard
import time
import logging
import sched
from copy import copy
import _globals
from ability import Ability
from ability import cooldown_actions
from world import World
class Combo(Ability):
cooldown_start = None
coold... |
# -*- coding: UTF-8 -*-
"""
Lastship Add-on (C) 2019
Credits to Lastship, Placenta and Covenant; our thanks go to their creators
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, e... |
#!/usr/bin/env python2
import argparse
import os
import subprocess
from lib import builder
from lib import promote
from lib.builder import WORKING_DIR
parser = argparse.ArgumentParser(
description="A tool to build the rpms for a single git project in koji. "
"This does not process external_deps.... |
#! /usr/bin/python2
import os
import time
import argparse
import subprocess
argparser = argparse.ArgumentParser()
argparser.add_argument( "-cp", "--cuda-path",
dest = "cuda_path",
type = str,
required = True,
help... |
# -*- coding: utf-8 -*-
# (c) 2009-2010 Ruslan Popov <<EMAIL>>
# (c) 2010 Maxim M. <<EMAIL>>
from django.conf import settings
from django.db import models
from django.utils import simplejson
from django.utils.translation import ugettext_lazy as _
from django.contrib.auth.models import User
from django.contrib.contentt... |
"""
Test the `ipaserver/plugins/config.py` module.
"""
from ipalib import errors
from ipatests.test_xmlrpc.xmlrpc_test import Declarative
import pytest
@pytest.mark.tier1
class test_config(Declarative):
cleanup_commands = [
]
tests = [
dict(
desc='Try to add an unrelated objectclas... |
import copy
from oslo_config import cfg
from mistral.db.v2.sqlalchemy import api as db_api
from mistral import exceptions as exc
from mistral.lang import parser as spec_parser
from mistral.lang.v2 import tasks
from mistral.lang.v2 import workflows
from mistral.services import workflows as wf_service
from mistral.test... |
import itertools
class TestConfiguration(object):
def __init__(self, version, architecture, build_type):
self.version = version
self.architecture = architecture
self.build_type = build_type
@classmethod
def category_order(cls):
"""The most common human-readable order in wh... |
from helpers import *
from database import get
def C_LIST(S, DB, sender, args):
roomlist = get(DB, "SELECT id,name FROM rooms")
if len(args) == 0: # List all the rooms.
body = "Rooms: " # Rooms
for n, room in enumerate(roomlist):
if n < len(roomlist) - 1:
body += room[1] + " (" + str(room[0]) + "), "
... |
from openerp import netsvc
from openerp.osv import orm
class sale_order_line(orm.Model):
"""Pass agreement PO into state confirmed when SO is confirmed"""
_inherit = "sale.order.line"
def button_confirm(self, cr, uid, ids, context=None):
"""Override confirmation of request of quotation to suppo... |
"""
Copyright (C) 2004-2015 Pivotal Software, Inc. All rights reserved.
This program and the accompanying materials are made available under
the terms of the 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
... |
import os
import sys
import pwd
import grp
def main():
command = sys.argv[1]
uname = sys.argv[2]
eval(command)(uname, *sys.argv[3:])
def init(uname):
home = os.path.join('/home', uname)
ssh = os.path.join(home, '.ssh')
os.mkdir(home)
os.mkdir(ssh)
u = pwd.getpwnam(uname)
g = grp.... |
"""
Question:
Implement strStr().
Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
Update (2014-11-02):
The signature of the function had been updated to return the index instead of the pointer. If you still see your function signature returns a... |
"""Machinery for exps, cs, varlocs data -- common to nomials and programs"""
from collections import defaultdict
import numpy as np
from ..small_classes import HashVector
from ..keydict import KeySet
from .map import NomialMap
from ..repr_conventions import _repr
from ..varkey import VarKey
class NomialData(object):
... |
"""Unit test for spectrogram module
"""
import pytest
import numpy
from numpy import testing as nptest
from astropy import units
from gwpy.spectrogram import Spectrogram
from test_array import Array2DTestCase
__author__ = 'Duncan Macleod <<EMAIL>>'
# -------------------------------------------------------------... |
import pytest
from django.urls import reverse
@pytest.mark.django_db
def test_dashboard_bplan_list_view(bplan_factory, project_factory,
organisation, client):
bplan_1 = bplan_factory(organisation=organisation)
bplan_2 = bplan_factory(organisation=organisation)
bplan_3 = ... |
from builtins import str
from builtins import object
from .nurest_login_controller import NURESTLoginController
from .nurest_push_center import NURESTPushCenter
from bambou import bambou_logger
from contextlib import contextmanager
import requests
import sys
class NURESTSession(object):
""" Authenticated session... |
from datetime import datetime
from openerp.osv import fields, orm
from openerp.tools import DEFAULT_SERVER_DATETIME_FORMAT
from openerp.tools.translate import _
from openerp import pooler
import logging
_logger = logging.getLogger(__name__)
class EasyReconcileOptions(orm.AbstractModel):
"""Options of a reconcili... |
# ------------------------------------------------------------------------
# coding=utf-8
# ------------------------------------------------------------------------
from __future__ import absolute_import, unicode_literals
import django
from django.core.exceptions import ImproperlyConfigured
from django.db import mode... |
# -*- coding: utf-8 -*-
"""
End-to-end tests for the Account Settings page.
"""
from unittest import skip
from nose.plugins.attrib import attr
from bok_choy.web_app_test import WebAppTest
from ...pages.lms.account_settings import AccountSettingsPage
from ...pages.lms.auto_auth import AutoAuthPage
from ...pages.lms.da... |
#!/env/python3
import sys
import argparse
import tabix
import os
import csv
import gzip
from common import *
#==========================================================================
def wgs_signature(file):
with gzip.open(file,'r') as file:
reader = csv.reader(io.TextIOWrapper(file, newline=""), delimiter=... |
from opus_core.database_management.engine_handlers.abstract_engine import AbstractDatabaseEngineManager
class MySQLServerManager(AbstractDatabaseEngineManager):
def __init__(self, server_config):
AbstractDatabaseEngineManager.__init__(self, server_config)
def get_connection_string(self, database_n... |
from gtool.core.types.core import CoreType
class Ref(CoreType):
"""
Ref expects an absolute reference in the form of /node1/node2. The reference must start with a / and end with an alpha value
"""
def isReference(self, ref):
separator = '/'
emptysplit = ''
if separator not in ... |
from willie import module
#the response types
type1 = {'YES': 0 , 'NO': 0}
type2 = {'A': 0 , 'B': 0, 'C': 0, 'D': 0}
response = None
@module.commands('vote')
@module.example('.vote start (1/2) | .vote end | .vote [option] | .vote results')
def vote(bot, trigger):
if triggger.group(2).lower() == 'start 1':
... |
#!/usr/bin/env python
import types, sys, os, math, json
import transform_notime, utilities
#
# global search counter
#
search_counter = 0
#
# run bitcode file with the current
# search configuration
# return 1 bitcode file is valid
# 0 bitcode file is invalid
# -1 some internal transformation error ... |
from sqlalchemy import Column, ForeignKey, Integer, String, Boolean
from sqlalchemy.orm import relationship, backref
from .database import Base
from .component import Component
from .function import Function
__author__ = 'Andreas Krakau'
__date__ = '$19-jan-2016 13:57:42$'
class Rule(Base):
__tablename__ = 'rul... |
import os, time
class logfile:
"""
log files may be used to have your scripts print progress so they
can be verified and troubleshooted
this simple class has just three methods,
__init__() opens up or creates a new logfile.(automatic)
entry() addes entries to the logfile with datestamps
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from runner.koan import *
import random
class DiceSet:
def __init__(self):
self._values = None
@property
def values(self):
return self._values
def roll(self, n):
# Needs implementing!
# Tip: random.randint(min, max) can b... |
{ 'sequence': 500,
"name" : "Invoice Reopen",
"version" : "1.1",
"author" : "Camptocamp SA",
"category": 'Accounting & Finance',
'complexity': "normal",
"description": """
Allows reopeing of unpaid invoices.
=====================================
This module allows to reopen (set to draft) unpaid invoices.
To comply w... |
import textwrap
from collections import OrderedDict
import pytest
import numpy as np
from numpy.testing import assert_array_equal
from ..nddata import NDData
from ..nduncertainty import NDUncertainty, StdDevUncertainty
from ... import units as u
from ...utils import NumpyRNGContext
class FakeUncertainty(NDUncertain... |
"""
owtf.utils.http
~~~~~~~~~~~~~~~
"""
import collections
import types
try: # PY3
from urllib.parse import urlparse
except ImportError: # PY2
from urlparse import urlparse
def derive_http_method(method, data):
"""Derives the HTTP method from Data, etc
:param method: Method to check
:type met... |
'''
Created on Jun 2, 2013
@author: Nathan Schneider (nschneid)
'''
from __future__ import print_function, division
import os, sys, codecs
from labeledSentence import LabeledSentence
import morph
USTRINGS = {}
def uintern(unicode_string):
'''Simulate built-in intern(), but in a way that works for unicode string... |
import os
from unittest import TestCase
import pytest
from ..file_comparison_panda import FileComparisonPanda
from ..file_comparison_exceptions import (
UnsupportedFileType, FileDoesNotExist, PermissionDeniedOnFile)
class TestFileComparison(TestCase):
test_files_path = os.path.dirname(__file__)
def test... |
#!/usr/bin/env python2
import logging
import argparse
import numpy as np
import pandas as pd
import cv2
def read_motion_vector(filename):
""" read the motion vector file under csv format
:param filename: input path to input csv file
:return: data under DataFrame format (see pandas lib)
"""
loggin... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Copyright (c) 2014,掌阅科技
All rights reserved.
摘 要: database.py
创 建 者: WangLichao
创建日期: 2015-01-26
"""
# pylint: disable=invalid-name, bare-except
from lib.db.retrydb import MyRetryDB
from peewee import Model as _Model
from peewee import DoesNotExist
from peewee impo... |
class MessageTrigger(HTMLObject):
'''MessageTrigger.
'''
nabar = None
room = None
@IN.register('MessageTrigger', type = 'Themer')
class MessageTriggerThemer(HTMLObjectThemer):
'''MessageTrigger themer'''
def theme_attributes(self, obj, format, view_mode, args):
obj.css.append('messenger-trigger i-panel... |
"""
Python Interchangeable Virtual Instrument Library
Copyright (c) 2012-2017 Alex Forencich
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... |
# -*- coding: utf-8 -*-
'''Test requests' interaction with vcr'''
import pytest
import vcr
from assertions import assert_cassette_empty, assert_is_json
requests = pytest.importorskip("requests")
@pytest.fixture(params=["https", "http"])
def scheme(request):
'''Fixture that returns both http and https.'''
r... |
import struct
__all__ = ["BadMessageError", "PROTOCOL_REVISION",
"KEEP_ALIVE", "CLIENT_HELLO", "PROTOCOL_UNSUPPORTED",
"SERVER_HELLO_COMPLETE", "ENTRY_ASSIGNMENT", "FIELD_UPDATE"]
# The definitions of all of the protocol message types
class BadMessageError(IOError):
pass
PROTOCOL_REVISION ... |
import logging
from ...bloodstone.scenes.imageplane import VtkImagePlane
from ...bloodstone.scenes.multisliceimageplane import VtkMultiSliceImagePlane
from ...bloodstone.scenes.gui.qt.component.qvtkwidget import QVtkWidget
from volumeview import VolumeView
from PySide import QtGui, QtCore
from sliceview import SliceV... |
from __future__ import absolute_import
import mock
from st2common.models.db.liveaction import LiveActionDB
from st2common.models.db.notification import NotificationSchema, NotificationSubSchema
from st2common.persistence.liveaction import LiveAction
from st2common.transport.publishers import PoolPublisher
from st2comm... |
from Generic import GenericThread
import datetime
import threading
import Queue
class OutputThread(GenericThread):
"""
Genreric -> OutputThread
This thread is here to prevent SSHThreads from simultaneously writing to the same file and mucking it all up.
Essentially, it allows sshpt to write results t... |
"""Script to build binary components of the SDK.
This script builds binary components of the Native Client SDK, create tarballs
for them, and uploads them to Google Cloud Storage.
This prevents a source dependency on the Chromium/NaCl tree in the Native
Client SDK repo.
"""
import argparse
import datetime
import glo... |
import unittest
import Gaffer
import GafferUI
import GafferUITest
class SplinePlugGadgetTest( GafferUITest.TestCase ) :
def testSelection( self ) :
g = GafferUI.SplinePlugGadget()
n = Gaffer.Node()
p = Gaffer.SplineffPlug()
n.addChild( p )
p1 = p.pointPlug( p.addPoint() )
p2 = p.pointPlug( p.add... |
import datetime
import iso8601
import mock
from oslo_utils import timeutils
from nova import context
from nova import db
from nova.objects import bandwidth_usage
from nova import test
from nova.tests.unit.objects import test_objects
class _TestBandwidthUsage(test.TestCase):
def setUp(self):
super(_Test... |
"""
Start point for the Backend.
"""
import logging
import multiprocessing
import signal
from leap.bitmask.backend.leapbackend import LeapBackend
from leap.bitmask.backend.utils import generate_zmq_certificates
from leap.bitmask.config import flags
from leap.bitmask.logs.utils import create_logger
from leap.bitmask.ut... |
import datetime
import json
import pydicom
import pydicom.valuerep
import pydicom.multival
import pydicom.sequence
import six
from girder import events
from girder.api import access
from girder.api.describe import Description, autoDescribeRoute
from girder.api.rest import Resource
from girder.constants import AccessT... |
# !/usr/bin/env python
# encoding: utf-8
"""
pyQms
-----
Python module for fast and accurate mass spectrometry data quantification
:license: MIT, see LICENSE.txt for more details
Authors:
* Leufken, J.
* Niehues, A.
* Sarin, L.P.
* Hippler, M.
* Leidel, S.... |
"""为项目创建执行环境."""
import json
import subprocess
from string import Template
from typing import Dict, Any
import chardet
from pmfp.const import (
GOLBAL_PYTHON_VERSION,
ENV_PATH,
JS_ENV_PATH,
PROJECT_HOME,
GO_ENV_PATH,
PMFP_GOLANG_ENV_TEMP
)
from pmfp.utils import (
get_golang_version
)
from .... |
"""
This experiment is set up in the following way:
1) We choose n users (set U) from k subreddits (set R) listed who have written at least c characters in each r
2) We train n*k models for authorship; i.e. for each user u in U, we gather a sample of text of size c for u from R
3) We test each document d from D_r with ... |
import os
import re
import time
import numpy as np
from os.path import join as pjoin
import dataLoader as dl
import cPickle as pickle
from joblib import Parallel, delayed
from decoder.decoder_config import SPACE, SCAIL_DATA_DIR,\
INPUT_DIM, RAW_DIM, DATASET, DATA_SUBSET, SPECIALS_LIST
from cluster.config import... |
import argparse
import os
import time
import math
import numpy as np
import random
import sys
import shutil
import json
import string
import torch
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
from torch.autograd import Variable
from utils import to_gpu, Corpus, batchify, train_ngr... |
import os
from setuptools import setup, find_packages
version = '0.3.1'
def read(f):
return open(os.path.join(os.path.dirname(__file__), f)).read().strip()
with open('requirements.txt', 'r') as f:
install_reqs = [
s for s in [
line.strip('\r\n') for line in f
] if not s.startswi... |
import json
import jsonpickle
from datetime import datetime
__author__ = 'mstipanov'
class DateFormatIso8601(object):
@classmethod
def strftime(cls, d):
s = "%04d-%02d-%02dT%02d:%02d:%02d.%03d" % (
d.year, d.month, d.day, d.hour, d.minute, d.second, d.microsecond / 1000)
tzinfo =... |
"""Support KNX devices."""
import logging
import voluptuous as vol
from xknx import XKNX
from xknx.devices import ActionCallback, DateTime, DateTimeBroadcastType, ExposeSensor
from xknx.dpt import DPTArray, DPTBinary
from xknx.exceptions import XKNXException
from xknx.io import DEFAULT_MCAST_PORT, ConnectionConfig, Co... |
# encoding: utf-8
import sys
from ConsoleWriter import ConsoleWriter
class UnixConsoleWriter(ConsoleWriter):
def __init__(self):
self.reset_color(self.std_out_handle)
self.reset_color(self.std_err_handle)
__FOREGROUND_BLACK = 0x0
__FOREGROUND_BLUE = 0x01 # text color contains blue.
... |
from django.shortcuts import render,get_object_or_404,redirect
from .models import Post
from .forms import PostForm
from django.core.urlresolvers import reverse
from django.contrib.auth.decorators import login_required
from django.core.paginator import Paginator,EmptyPage,PageNotAnInteger
from haystack.forms import Se... |
#!/usr/bin/env python
# This is a helper script to generate tests for Bats
import argparse
import pprint
import traceback
import yaml
TEMPLATE_KEYS = ['shell', 'script_name', 'description', 'hostgroup', 'playbook', 'commands', 'assert_type', 'partial', 'regexflag', 'expected']
DOC_HEADER = """#!/usr/bin/env bats
l... |
from django.conf import settings
DISABLE_QUERYSET_CACHE = getattr(settings, 'DISABLE_QUERYSET_CACHE', False)
BLACKLIST = getattr(settings, 'MAN_IN_BLACKLIST',
getattr(settings, 'JOHNNY_TABLE_BLACKLIST', []))
BLACKLIST = set(BLACKLIST)
MIDDLEWARE_KEY_PREFIX = getattr(settings, 'JOHNNY_MIDDLEWARE_KEY_PREFI... |
from typing import Any
from django.core.management.base import CommandParser
from zerver.lib.actions import bulk_remove_subscriptions
from zerver.lib.management import ZulipBaseCommand
from zerver.models import get_stream
class Command(ZulipBaseCommand):
help = """Remove some or all users in a realm from a stre... |
'''
ExpEYES program for voltammetric studies.
Voltammetric studies to plot voltammograms are done using costly apparatus in research labs.
ExpEYES can be effectly used for this purpose.
ExpEYES program developed as a part of GSoC-2015 project
Project Tilte: Sensor Plug-ins, Add-on devices and GUI Improvements for Ex... |
from __future__ import absolute_import, division, print_function, unicode_literals
import sys
import itertools
import subprocess
from PIL import Image
from resizeimage import resizeimage
import os
MAX_SIZE = 3000
import argparse
def main():
parser = argparse.ArgumentParser()
parser.add_argument('directori... |
# Always prefer setuptools over distutils
from setuptools import setup, find_packages
# Read in long_description from README.rst. By using a separate file, instead
# of translating README.md, we can use different content on PyPI than on
# GitHub.
with open('README.rst') as readme_file:
long_description = readme_f... |
""" This code was authored by Raymond Hettiger. """
import collections
import functools
from itertools import ifilterfalse
from heapq import nsmallest
from operator import itemgetter
class Counter(dict):
'Mapping where default values are zero'
def __missing__(self, key):
return 0
def lru_cache(maxsiz... |
"""Post Processor Module."""
from __future__ import unicode_literals
import logging
import os.path
from . import app
logger = logging.getLogger(__name__)
class PostProcessor(object):
"""Post Processor Scheduler Action."""
def __init__(self):
"""Init method."""
self.amActive = False
d... |
import json
import pyramid.httpexceptions as http
import random
import utils
from campaign import logger, LOG
from campaign.auth.default import DefaultAuth
from dateutil import parser
from pyramid.request import Request
from pyramid.testing import DummyRequest
from time import time
class checkService(object):
"""... |
#!/usr/bin/env python
import glob
import os
import subprocess
import sys
from distutils.command.build_ext import build_ext
from setuptools import setup, find_packages, Extension
# top level bindings directory
BINDINGS_DIR = os.path.dirname(os.path.abspath(__file__))
# top level repo directory
TOPDIR = os.path.dirnam... |
"""
Real-time updates on reddit.
In addition to the standard reddit API, WebSockets play a huge role in reddit
live. Receiving push notification of changes to the thread via websockets is
much better than polling the thread repeatedly.
To connect to the websocket server, fetch
[/live/*thread*/about.json](#GET_live_{t... |
#coding=utf-8
__author__ = 'popka'
import main
class LinkContainer(object):
links = []
def __init__(self):
pass
def add(self, array):
"""
Если не лох - переделай. Так пиздец как плохо.
Даже страшно подумать, как это плохо!
Возможно надо вставить сет, но проверит... |
def add_etmy_channels():
from gcm.data import channels as chn
channels = [chn.add_channel("H1", "HPI-ETMY", "SENSCOR_Y_FIR_IN1_DQ"),
chn.add_channel("H1", "HPI-ETMY", "BLND_L4C_Y_IN1_DQ"),
chn.add_channel("H1", "ISI-ETMY", "ST1_BLND_Y_L4C_CUR_IN1_DQ"),
chn.add_cha... |
import os
import gtk, gtk.glade
from windows.SimpleGladeApp import SimpleGladeApp
from windows import preferences
from classes import project, messagebox
# init the foreign language
from language import Language_Init
class frmAddFiles(SimpleGladeApp):
def __init__(self, path="AddFiles.glade", root="frmAddFiles", d... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os
import re
import sys
sys.dont_write_bytecode = True
from ruamel import yaml
from doit.task import clean_targets
from sota.utils.shell import call, rglob
from sota.constants import *
DOIT_CONFIG = {
'verbosity': 2,
'default_tasks': ['post'],
}
def tas... |
# -*- coding: utf-8 -*-
from storm.expr import And, In
from storm.locals import Unicode, Storm, Bool
from globaleaks import LANGUAGES_SUPPORTED_CODES, models
from globaleaks.rest import errors
from globaleaks.models.config import NodeFactory, NotificationFactory, PrivateFactory
from globaleaks.utils.utility import lo... |
from PyQt4 import QtGui, QtCore
class NodeType:
"""
Types of nodes in the hierarchy.
"""
region = 1
sensor = 2
class Node:
"""
Node that represents region/sensors and their params.
"""
#region Constructor
def __init__(self, name, type):
"""
Initializes a new instance ... |
# coding=utf-8
import cairo
from blueman.bluez.Network import Network
from blueman.plugins.ManagerPlugin import ManagerPlugin
from blueman.Functions import create_menuitem
from blueman.main.DBusProxies import AppletService
from blueman.services import *
from _blueman import rfcomm_list
import gi
gi.require_version("Gt... |
"""BIG-IP® Advanced Firewall Manager™ (AFM®) module.
REST URI
``http://localhost/mgmt/tm/security/nat``
GUI Path
``Security --> Network Address Translation``
REST Kind
``tm:security:nat:*``
"""
from f5.bigip.mixins import CheckExistenceMixin
from f5.bigip.mixins import CommandExecutionMixin
from f5.bigip... |
from collections import OrderedDict
from typing import Dict, Type
from .base import BigQueryReadTransport
from .grpc import BigQueryReadGrpcTransport
from .grpc_asyncio import BigQueryReadGrpcAsyncIOTransport
# Compile a registry of transports.
_transport_registry = OrderedDict() # type: Dict[str, Type[BigQueryRead... |
from abc import ABCMeta, abstractmethod, abstractproperty
from collections import namedtuple
# Trigger = namedtuple('Trigger', 'match, function, a_dict, requires')
class Trigger(namedtuple('Trigger', 'match, function, param_dict, requires')):
def __new__(cls, match, function, param_dict=None, requires=None):
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Python packaging."""
import os
import sys
from setuptools import setup
# Tox integration.
from setuptools.command.test import test as TestCommand
class Tox(TestCommand):
"""Test command that runs tox."""
def finalize_options(self):
TestCommand.finali... |
import weakref
from . address import number, Address
from . receiver import Receiver
from .. util import deprecated
class Editor(Receiver):
"""
A `Editor` is a `Receiver` which gets and sets `Address`es, perhaps using an
an optional `EditQueue` for the setting.
When the `set_project` method is called... |
# -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Deleting field 'Entry.permalink'
db.delete_column(u'feeds_entry', 'permalink')
def backwards(self, o... |
#!/usr/bin/env python
import random
import simpleSat
import sys
import argparse
class Generator():
def __init__(self):
args = self.getArgs()
self.gamma = args.gamma
self.nVariables = args.nvariables
self.nClauses = args.nclauses
self.length = args.length
self... |
from openerp import fields
from .common import SaleOrderCreateEventSetup
str2date = fields.Date.from_string
class TestSaleOrderCreateEventOnly(SaleOrderCreateEventSetup):
def setUp(self):
super(TestSaleOrderCreateEventOnly, self).setUp()
def test_change_session_date(self):
self.sale_order.a... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.