content stringlengths 4 20k |
|---|
from setuptools import setup
import os
PROJECT_ROOT, _ = os.path.split(__file__)
REVISION = '0.2.25'
PROJECT_NAME = 'JenkinsAPI'
PROJECT_AUTHORS = "Salim Fadhley, Aleksey Maksimov"
# Please see readme.rst for a complete list of contributors
PROJECT_EMAILS = '<EMAIL>, <EMAIL>'
PROJECT_URL = "https://github.com/salimfad... |
from contextlib import closing, nested
from Queue import Queue
import threading
import uuid
import logbook
import zmq
from zrpc.concurrency import Callback, DummyCallback
from zrpc.loadbal import LoadBalancer
from zrpc.server import Server
logger = logbook.Logger('zrpc.multiserver')
run_logger = logbook.Logger('zrp... |
import numpy as np
from typing import List
from Starfish import constants as C
def global_covariance_matrix(
wave: np.ndarray, temp: float, amplitude: float, lengthscale: float
) -> np.ndarray:
"""
A matern-3/2 kernel scaled by the planck function where the metric is defined as the velocity separation of... |
# -*- coding: utf-8 -*-
"""
@author: U{Ivan Herman<a href="http://www.w3.org/People/Ivan/">}
@license: This software is available for use under the
U{W3C® SOFTWARE NOTICE AND LICENSE<href="http://www.w3.org/Consortium/Legal/2002/copyright-software-20021231">}
@contact: Ivan Herman, <EMAIL>
@version: $Id: lite.py,v 1.1... |
"""A fake implementation of test-results.appspot.com."""
import io
import sys
import threading
if sys.version_info.major == 2: # pragma: python2
from SimpleHTTPServer import SimpleHTTPRequestHandler as HTTPRequestHandler
from SocketServer import TCPServer
else: # pragma: python3
assert sys.version_info... |
# -*- coding: utf-8 -*-
"""Test logentries module."""
#
# (C) Pywikibot team, 2015-2016
#
# Distributed under the terms of the MIT license.
#
from __future__ import absolute_import, unicode_literals
import datetime
import pywikibot
from pywikibot.logentries import LogEntryFactory
from pywikibot.tools import (
Me... |
# -*- coding: utf-8 -*-
import string
import itertools
import lxml
import wiseguy.html
import pegger as pg
from pegger import lazy
alphabet = pg.Words(string.lowercase+string.uppercase)
alphanumerics = pg.Words(string.lowercase+string.uppercase+string.digits)
identifier_parts = pg.Words(string.lowercase+string.up... |
from __future__ import unicode_literals
from wtforms.fields import StringField, TextAreaField, BooleanField
from wtforms.validators import DataRequired, Optional
from indico.util.i18n import _
from indico.web.forms.base import IndicoForm
from indico.web.forms.widgets import SwitchWidget
class FieldConfigForm(Indico... |
"""The Binomial distribution class."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensorflow.contrib.distributions.python.ops import distribution
from tensorflow.contrib.distributions.python.ops import distribution_util
from tensorflow.python.frame... |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
try:
from libcloud.compute.types import Provider
from libcloud.compute.providers im... |
from ..builder import DETECTORS
from .two_stage import TwoStageDetector
@DETECTORS.register_module()
class CascadeRCNN(TwoStageDetector):
r"""Implementation of `Cascade R-CNN: Delving into High Quality Object
Detection <https://arxiv.org/abs/1906.09756>`_"""
def __init__(self,
backbone,
... |
import os
import unittest
from telemetry import story
from telemetry.internal.results import base_test_results_unittest
from telemetry.internal.results import page_test_results
from telemetry import page as page_module
from telemetry.timeline import trace_data
from telemetry.value import failure
from telemetry.value i... |
"""bug 822304 priority jobs removal
Revision ID: 144f7ace11e7
Revises: 3a5471a358bf
Create Date: 2013-12-11 09:22:35.674934
"""
# revision identifiers, used by Alembic.
revision = '144f7ace11e7'
down_revision = '3a5471a358bf'
from alembic import op
from socorro.lib import citexttype, jsontype
from socorro.lib.migra... |
"""Check that required RPM packages are available."""
from openshift_checks import OpenShiftCheck
from openshift_checks.mixins import NotContainerizedMixin
class PackageAvailability(NotContainerizedMixin, OpenShiftCheck):
"""Check that required RPM packages are available."""
name = "package_availability"
... |
from a10sdk.common.A10BaseClass import A10BaseClass
class SamplingEnable(A10BaseClass):
"""This class does not support CRUD Operations please use parent.
:param counters1: {"enum": ["all", "good_recv", "periodic_sent", "rate_limit", "bad_hop_limit", "truncated", "bad_icmpv6_csum", "bad_icmpv6_code", "ba... |
"""Unit test utilities for gtest_xml_output"""
__author__ = '<EMAIL> (Sean Mcafee)'
import re
from xml.dom import minidom, Node
import gtest_test_utils
GTEST_OUTPUT_FLAG = '--gtest_output'
GTEST_DEFAULT_OUTPUT_FILE = 'test_detail.xml'
class GTestXMLTestCase(gtest_test_utils.TestCase):
"""
Base class f... |
"""
# PROBLEM 19
You are given the following information, but you may prefer to do some research for yourself.
1 Jan 1900 was a Monday.
Thirty days has September,
April, June and November.
All the rest have thirty-one,
Saving February alone,
Which has twenty-eight, rain or shine.
And on leap years, twenty-nine.
A leap... |
import warnings
from typing import Callable, Dict, Optional, Sequence, Tuple, Union
from google.api_core import grpc_helpers # type: ignore
from google.api_core import gapic_v1 # type: ignore
import google.auth # type: ignore
from google.auth import credentials as ga_credentials # type: ignore
from google.auth.tra... |
#!/usr/bin/env python
import sys
import psycopg2
from elasticsearch import Elasticsearch
import json
import logging
STATE_CODE_MAP = {
'AK': 'Alaska',
'AL': 'Alabama',
'AR': 'Arkansas',
'AS': 'American Samoa',
'AZ': 'Arizona',
'CA': 'California',
'CO': 'Colorado',
'CT': 'Connecticut',
... |
from osv import fields, osv
from tools.translate import _
#in this file, we mostly add the tag translate=True on existing fields that we now want to be translated
class account_account_template(osv.osv):
_inherit = 'account.account.template'
_columns = {
'name': fields.char('Name', size=128, required... |
from __future__ import absolute_import, print_function
import pytest
from selenium.webdriver.support.ui import WebDriverWait
from selenium.common.exceptions import TimeoutException
from bokeh.models import ColumnDataSource, Rect, BoxSelectTool, CustomJS
from tests.plugins.utils import warn
def has_no_console_error... |
# -*- coding: utf-8 -*-
"""
Unlink inactive enterprise learners of SAP Success Factors from related EnterpriseCustomer(s).
"""
from logging import getLogger
from django.core.management.base import BaseCommand
from integrated_channels.integrated_channel.management.commands import IntegratedChannelCommandMixin
from in... |
"""
Copyright 2008-2011 Free Software Foundation, Inc.
This file is part of GNU Radio
GNU Radio Companion 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 2
of the License, or (at your option) any l... |
import logging
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from django.template import Engine
from django.template.base import TemplateDoesNotExist
from django.template.loaders.app_directories import Loader as AppDirectoriesLoader
from django.template.loaders.filesystem imp... |
from django.core.management.base import LabelCommand
import sys
from corehq import Domain
class Command(LabelCommand):
help = "Purge ALL documents of a particular type. E.g. purge_docs MyDocType,AnotherOne"
def handle(self, doc_types, *args, **options):
input = raw_input('\n'.join([
'\n\... |
import glob
import os
import re
import shutil
import tempfile
import urlparse
import pyauto_functional # Must be imported before pyauto
import pyauto
class OmniboxTest(pyauto.PyUITest):
"""TestCase for Omnibox."""
def Debug(self):
"""Test method for experimentation.
This method will not run automatica... |
import unittest
import threading
from IECore import *
import os
class CachedReaderTest( unittest.TestCase ) :
def testConstructors( self ) :
# test default pool
r = CachedReader( SearchPath( "./", ":") )
self.assertTrue( r.objectPool().isSame( ObjectPool.defaultObjectPool() ) )
# test custom pool
pool =... |
"""
This is a sample implementation of a Twisted push producer/consumer system. It
consists of a TCP server which asks the user how many random integers they
want, and it sends the result set back to the user, one result per line,
and finally closes the connection.
"""
from __future__ import print_function
from sys i... |
"""Gradient exploring functions."""
import logging
import math
import pickle
import warnings
import os
from ..optimizer import optimizer
__all__ = [
'Explorer', 'Linear','register','create'
]
class Explorer(object):
def __init__(self, optimizer=None, explorer_params=None):
self.start_epoch = explorer_... |
import pytest
from ceph_deploy.cli import get_parser
class TestParserRepo(object):
def setup(self):
self.parser = get_parser()
def test_repo_help(self, capsys):
with pytest.raises(SystemExit):
self.parser.parse_args('repo --help'.split())
out, err = capsys.readouterr()
... |
from nova import db
from nova.objects import instance
from nova.objects import security_group
from nova.tests.unit.objects import test_objects
fake_secgroup = {
'created_at': None,
'updated_at': None,
'deleted_at': None,
'deleted': None,
'id': 1,
'name': 'fake-name',
'description': 'fake-d... |
import tensorflow as tf
from tensorflow.python.client import device_lib
import numpy as np
import util
import argparse
import os
import csv
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
input_feature_dim = 97
cond_step_dim = 8
cond_wafer_dim = 24
cond_dim = cond_step_dim + cond_wafer_dim
lstm_sequence_length = 20
lstm_hi... |
import unittest
import os
import platform
import re
import subprocess
from conans import tools
from conans.test.utils.tools import TestClient
from conans.test.utils.test_files import temp_folder
from conans.paths import CONANFILE
from conans.model.ref import ConanFileReference, PackageReference
conanfile_py = """
fr... |
__all__ = ['sources_list', 'newsApi_API', 'further_read_theNextWeb', 'invalid', 'thankyou', 'notready']
#functions
import json
from pprint import pprint
from urllib.request import urlopen
import binascii
from image_retriever import return_image
import re
from apikey import key
apiKey = key()
keys = {'1': "https://... |
from haystack import indexes
from geonode.maps.models import Map
class MapIndex(indexes.SearchIndex, indexes.Indexable):
text = indexes.CharField(document=True, use_template=True)
title = indexes.CharField(model_attr="title", boost=2)
# https://github.com/toastdriven/django-haystack/issues/569 - Necessary... |
from ..utils import appid, have_appserver
from google.appengine.ext.testbed import Testbed
from urllib2 import HTTPError, URLError
import logging
import time
REMOTE_API_SCRIPT = '$PYTHON_LIB/google/appengine/ext/remote_api/handler.py'
def auth_func():
import getpass
return raw_input('Login via Google Account ... |
import re
import sys
from .ansi import AnsiFore, AnsiBack, AnsiStyle, Style
from .winterm import WinTerm, WinColor, WinStyle
from .win32 import windll
if windll is not None:
winterm = WinTerm()
def is_a_tty(stream):
return hasattr(stream, 'isatty') and stream.isatty()
class StreamWrapper(... |
import re
import taboot
import sys
import tempfile
from argparse import ArgumentParser, ArgumentTypeError
from errors import TabootTaskNotFoundException
from os.path import isfile
from taboot.log import *
def resolve_types(ds, relative_to='taboot.tasks'):
"""
Recursively translate string representation of a t... |
from utilities import run
def install_packages():
"""Get required Ubuntu/Debian packages.
It is OK if they are already installed
"""
for package in ['apache2',
'subversion',
'trac',
'libapache2-svn',
'lib... |
from __future__ import unicode_literals
import json
from moto.core.responses import BaseResponse
from .models import glue_backend
from .exceptions import (
PartitionAlreadyExistsException,
PartitionNotFoundException,
TableNotFoundException
)
class GlueResponse(BaseResponse):
@property
def glue_... |
import rospy
from ez_utils.msg import TargetJoints
from control_msgs.msg import FollowJointTrajectoryActionGoal
from trajectory_msgs.msg import JointTrajectoryPoint
class JointsServer(object):
def __init__(self, controller_name):
self._joint_names = rospy.get_param(controller_name + '/joints')
self... |
import os
import blktap2
import glob
import SR
from stat import * # S_ISBLK(), ...
SECTOR_SHIFT = 9
class CachingTap(object):
def __init__(self, tapdisk, stats):
self.tapdisk = tapdisk
self.stats = stats
@classmethod
def from_tapdisk(cls, tapdisk, stats):
# pick the last image... |
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from skimage.color import lab2rgb
import sys
OUTPUT_TEMPLATE = (
'Bayesian classifier: {bayes_rgb:.3g} {bayes_lab:.3g}\n'
'kNN classifier: {knn_rgb:.3g} {knn_lab:.3g}\n'
'SVM classifier: {svm_rgb:.3g} {svm_lab:.3g}\n'
)
# r... |
from polyaxon.exceptions import PolyaxonSchemaError
from polyaxon.managers.project import ProjectConfigManager
from polyaxon.utils.formatting import Printer
CACHE_ERROR = (
"Found an invalid project config or project config cache, "
"if you are using Polyaxon CLI please run: "
"`polyaxon config purge --cac... |
from django.conf.urls import patterns, url
from corehq import SMSAdminInterfaceDispatcher
from corehq.apps.sms.views import (
DomainSmsGatewayListView,
SubscribeSMSView,
AddDomainGatewayView,
EditDomainGatewayView,
SMSSettingsView,
)
urlpatterns = patterns('corehq.apps.sms.views',
url(r'^$', 'd... |
"""This file explains how we tell if a transaction is valid or not, it explains
how we update the system when new transactions are added to the blockchain."""
import blockchain
import custom
import copy
import tools
import verify
def addr(tx):
return tools.make_address(tx['pubkeys'], len(tx['signatures']))
def ... |
"""
Logging
"""
__RCSID__ = "$Id$"
import logging
import os
from DIRAC.FrameworkSystem.private.standardLogging.LogLevels import LogLevels
from DIRAC.Core.Utilities.LockRing import LockRing
from DIRAC.Resources.LogBackends.AbstractBackend import AbstractBackend
class Logging(object):
"""
Logging is a wrapper of... |
import csv
import logging
import numpy as np
from itertools import imap
from emoticons import Sad_RE
from emoticons import Happy_RE
from sklearn.externals import joblib
from sklearn.decomposition import KernelPCA
from scipy.sparse import lil_matrix as sparse_matrix
from sklearn.feature_extraction.text import TfidfTr... |
"""
Integration tests which cover state convergence (aka smart recreate) performed
by `docker-compose up`.
"""
from __future__ import absolute_import
from __future__ import unicode_literals
import py
from .testcases import DockerClientTestCase
from .testcases import get_links
from compose.config import config
from co... |
# -*- coding:utf-8 -*-
# coding=<utf8>
__version__ = '0.2.3d'
import datetime
from itertools import chain
import json
from django.http import HttpResponse, Http404, HttpResponseRedirect
from todoes.models import Person, Task, ProblemByWorker,\
ProblemByUser, Categories, RegularTask, Activity, Note, Resource,\
Fil... |
# -*- coding: utf-8 -*-
"""
This module contains the care line highlighter mode
"""
from pyqode.qt import QtGui
from pyqode.core.api.decoration import TextDecoration
from pyqode.core.api.mode import Mode
class LineHighlighterMode(Mode):
""" Highlights a line in the editor."""
@property
def background(se... |
import pytest
from indy import IndyError
from indy.error import ErrorCode
from tests.non_secrets.common import *
@pytest.mark.asyncio
async def test_delete_wallet_record_tags_works(wallet_handle):
await non_secrets.add_wallet_record(wallet_handle, type_, id1, value1, tags1)
await check_record_field(wallet_ha... |
"""Ops related to candidate sampling."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import ops
from tensorflow.python.ops import array_ops
from tensorflow.python.ops import... |
from en.parser.nltk_lite import tokenize
from en.parser.nltk_lite import parse
from en.parser.nltk_lite.parse import cfg
from re import *
class ParadigmQuery(object):
"""
Class to read and parse a paradigm visualisation query
"""
def __init__(self, p_string=None):
"""
Construct a query... |
from dtk.ui.frame import HorizontalFrame, VerticalFrame
from dtk.ui.panel import Panel
from dtk.ui.utils import propagate_expose
from locales import _
from tooltip import tooltip_text
from skin import app_theme
from togglehoverbutton import ToggleHoverButton, ToolbarRadioButton
import gtk
import cairo
class ToolBa... |
"""Test v1 api"""
import unittest
from yabgp.api.app import app
class FlaskrTestCase(unittest.TestCase):
def setUp(self):
# prepare some peers
self.app = app.test_client()
def tearDown(self):
""""""
pass
def test_v1_root(self):
result = self.app.get('/v1')
... |
""" API v1 models. """
from itertools import groupby
import logging
from django.db import transaction
from opaque_keys import InvalidKeyError
from opaque_keys.edx.keys import CourseKey
from openedx.core.djangoapps.content.course_overviews.models import CourseOverview
from course_modes.models import CourseMode
from lms... |
"""add indexes
Revision ID: 4328f2c08f05
Revises: eb61567ea005
Create Date: 2019-02-05 19:23:02.744161
"""
from alembic import op
import sqlalchemy as sa
from docassemble.webapp.database import dbtableprefix
# revision identifiers, used by Alembic.
revision = '4328f2c08f05'
down_revision = 'eb61567ea005'
branch_lab... |
from Model import *
import numpy as np
import numpy.random as rng
def logsumexp(values):
"""
Logarithmic addition
"""
biggest = np.max(values)
x = values - biggest
result = np.log(np.sum(np.exp(x))) + biggest
return result
class TestModel(Model):
"""
An example model
"""
u = 0.01
v = 0.1
logu = np.log(u... |
"""Updates the FeaturePolicyFeature enum in enums.xml file with
values read from permissions_policy_feature.mojom.
If the file was pretty-printed, the updated version is pretty-printed too.
"""
from __future__ import print_function
import os
import sys
from update_histogram_enum import UpdateHistogramEnum
if __nam... |
'''
CSS case-mangling transform.
'''
from __future__ import with_statement
__license__ = 'GPL v3'
__copyright__ = '2008, Marshall T. Vandegrift <<EMAIL>>'
from lxml import etree
from calibre.ebooks.oeb.base import XHTML, XHTML_NS
from calibre.ebooks.oeb.base import CSS_MIME
from calibre.ebooks.oeb.base import names... |
"""
25 Mar 2013
"""
from random import random
from copy import deepcopy
from numpy import array, log2
from scipy.interpolate import interp1d
from cPickle import load
from pytadbit.tad_clustering.tad_cmo import optimal_cmo
from matplotlib import pyplot as plt
# from scipy.stats import zscore
import multiprocessing as ... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
from units.compat.mock import patch
from ansible.modules.network.edgeos import edgeos_config
from units.modules.utils import set_module_args
from .edgeos_module import TestEdgeosModule, load_fixture
class TestEdgeosConfigModule(T... |
"""
Basic Test Case class.
"""
try:
import subprocess32
except ImportError:
import subprocess as subprocess32
import re
from aft.logger import Logger as logger
from aft.testcase import TestCase
import aft.errors as errors
class BasicTestCase(TestCase):
"""
Simple Test Case executor.
"""
def _... |
"""Configure a filter pipeline from command-line arguments.
The main entry point is setup_filters()
The GET parameters have numbers appended, e.g. "rename-oldtag7". This
module uses the numbers to group the parameters, then to construct the
hxl.filter objects from them and build a pipeline.
"""
import hxl, io
from h... |
import unittest
from ReText import tablemode
class TestTableMode(unittest.TestCase):
def performEdit(self, text, offset, editSize, paddingchar=None, fragment=None):
if editSize < 0:
text = text[:offset + editSize] + text[offset:]
else:
fragment = paddingchar * editSize if not fragment else fragment
tex... |
import graphene
from django.core.exceptions import ObjectDoesNotExist, ValidationError
from ...account.models import User
from ...core.permissions import GiftcardPermissions
from ...core.utils.promo_code import (
PromoCodeAlreadyExists,
generate_promo_code,
is_available_promo_code,
)
from ...giftcard impor... |
import os
import unittest
from nose_parameterized.parameterized import parameterized
from conans.test.utils.tools import TestServer, TestClient
from conans.model.ref import ConanFileReference
from conans.util.files import save, load, md5
from conans.model.ref import PackageReference
from conans.paths import CONANFILE,... |
"""Test the listtransactions API."""
from decimal import Decimal
from io import BytesIO
from test_framework.messages import COIN, CTransaction
from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import (
assert_array_result,
assert_equal,
hex_str_to_bytes,
)
def tx_from... |
# -*- coding: utf-8 -*-
"""Parser for custom destinations jump list (.customDestinations-ms) files."""
import os
from dfvfs.lib import definitions
from dfvfs.lib import errors as dfvfs_errors
from dfvfs.path import factory as path_spec_factory
from dfvfs.resolver import resolver
from plaso.lib import errors
from pla... |
# -*- encoding: UTF-8 -*-
from naoqi import ALProxy
IP = "127.0.0.1" # set your Ip address here
PORT = 9559
# ====================
# Create proxy to ALMemory
memoryProxy = ALProxy("ALMemory", IP, PORT)
# Get The Left Foot Force Sensor Values
LFsrFL = memoryProxy.getData("Device/SubDeviceList/LFoot/FSR/FrontLeft/Sens... |
#! /usr/bin/env python
'''
Copyright (C) 2012 Diego Torres Milano
Created on Sep 5, 2012
@author: diego
'''
import re
import sys
import os
try:
sys.path.append(os.path.join(os.environ['ANDROID_VIEW_CLIENT_HOME'], 'src'))
except:
pass
from com.dtmilano.android.viewclient import ViewClient, View
device, se... |
ANSIBLE_METADATA = {'status': ['preview'],
'supported_by': 'core',
'version': '1.0'}
DOCUMENTATION = r'''
---
module: win_owner
version_added: "2.1"
short_description: Set owner
description:
- Set owner of files or directories
options:
path:
description:
- Path t... |
# -*- coding: utf-8 -*-
"""
Production Configurations
- Use djangosecure
- Use Amazon's S3 for storing static files and uploaded media
- Use mailgun to send emails
- Use Redis on Heroku
"""
from __future__ import absolute_import, unicode_literals
from boto.s3.connection import OrdinaryCallingFormat
from django.util... |
from datetime import datetime
from OpenGL.GL import *
from metno.diana import *
from PyQt4.QtCore import QEvent, QPointF, QRectF, Qt
from PyQt4.QtGui import QColor, QFont, QFontMetricsF, QPolygonF
class TestManager(Manager):
def __init__(self):
Manager.__init__(self)
TestManager.instance = self
... |
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
job = {
'id': '121',
'job_id': '11',
'time': 1424915926,
'desc':
{
'global_desc': {
# these three itemes are useless for action, but only for desc
'department': 'ad',
'server_type': 'web_se... |
"""
Django settings for reactlibapp project.
Generated by 'django-admin startproject' using Django 1.8.2.
For more information on this file, see
https://docs.djangoproject.com/en/1.8/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.8/ref/settings/
"""
# Build ... |
from openstack_dashboard.usage.base import BaseUsage
from openstack_dashboard.usage.base import GlobalUsage
from openstack_dashboard.usage.base import ProjectUsage
from openstack_dashboard.usage.tables import BaseUsageTable
from openstack_dashboard.usage.tables import GlobalUsageTable
from openstack_dashboard.usage.tab... |
# -*- coding: utf-8 -*-
import cStringIO
import datetime
import functools
import operator
import itertools
import time
import psycopg2
import pytz
from openerp.osv import orm
from openerp.tools.translate import _
from openerp.tools.misc import DEFAULT_SERVER_DATE_FORMAT,\
DEFAULT_SERVER... |
"""
Actions-handling for manage list pages.
"""
from functools import wraps
from django.http import HttpResponseForbidden
from django.shortcuts import redirect
def actions(model, allowed_actions, permission=None, fall_through=False):
"""
View decorator for handling single-model actions on manage list pages... |
# -*- coding:utf-8 -*-
import time
import re
import requests
import log, config, util, proxypool
import urllib
from os import path
import sys
import downloader
from obj import Song, Handler
from bs4 import BeautifulSoup
LOG = log.get_logger("zxLogger")
if config.LANG.upper() == 'CN':
import i18n.msg_cn as msg
els... |
from spack import *
class Fake(Package):
homepage = "http://www.fake-spack-example.org"
url = "http://www.fake-spack-example.org/downloads/fake-1.0.tar.gz"
version('1.0', 'foobarbaz')
def install(self, spec, prefix):
pass |
import threading # za vzporedno izvajanje
from minimax import *
######################################################################
## Igralec računalnik
class Racunalnik():
def __init__(self, gui, algoritem):
self.gui = gui
self.algoritem = algoritem # Algoritem, ki izračuna potezo
s... |
# -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
depends_on = (
('core', '0009_drop_timtecuser'),
)
def forwards(self, orm):
# Adding model 'Answer'
db.rename_table('c... |
"""Models for the util app. """
import cStringIO
import gzip
import logging
from config_models.models import ConfigurationModel
from django.db import models
from django.utils.text import compress_string
from opaque_keys.edx.django.models import CreatorMixin
logger = logging.getLogger(__name__) # pylint: disable=inv... |
import numpy as np
from mpi4py import MPI
from docopt import docopt
from helpers import gen_matrix, gen_vector, usage, schema
from schema import SchemaError
# Define process 0 as MASTER
MASTER = 0
def master(dim, dtype, mtype, n_proc, comm):
"""The master process, generates matrices and divides up the work."""
... |
import bpy
from bpy.props import BoolProperty, EnumProperty, IntProperty
from sverchok.node_tree import SverchCustomTreeNode
from sverchok.data_structure import updateNode, match_long_repeat, calc_mask
class SvCalcMaskNode(bpy.types.Node, SverchCustomTreeNode):
"""
Triggers: Calculate Mask
Tooltip: Calcula... |
# coding=utf-8
"""comment.py - Comments dialog."""
from __future__ import absolute_import
import os
import gtk
from src import encoding
_dialog = None
# Compatibility
try:
range = xrange # Python2
except NameError:
pass
class _CommentsDialog(gtk.Dialog):
def __init__(self, window):
gtk.Dial... |
"""Tests for distutils.command.bdist_rpm."""
import unittest
import sys
import os
import tempfile
import shutil
from test.test_support import run_unittest
from distutils.core import Distribution
from distutils.command.bdist_rpm import bdist_rpm
from distutils.tests import support
from distutils.spawn import find_exe... |
from flask import jsonify, Markup, render_template
from app import app
import os
import re
initialised = False
musicFiles = None
mpeg_regex = re.compile(r"^.*\.mp3$")
jpeg_regex = re.compile(r"^.*\.jpe?g$")
png_regex = re.compile(r"^.*\.png$")
def getMusicFiles(path): # credit to https://stackoverflow.com/a/2... |
from django.db.models.manager import Manager
from django.db.models.signals import post_save, post_delete
from haystack.utils import get_identifier
from apn_search.options import search_update_options
from apn_search.update import update_object, queue_update
def search_index_signal_handler(instance, signal, **kwargs... |
from ..dbtypes import GUID, JSONEncodedDict
from .enum import VPPUserStatus, VPPPricingParam, VPPProductType
from ..models import db
from sqlalchemy.ext.hybrid import hybrid_property, hybrid_method
import base64
import json
import dateutil.parser
class VPPAccount(db.Model):
__tablename__ = 'vpp_accounts'
id... |
import ogr,sys,urllib2,csv
print "#!/bin/bash"
iso_list = urllib2.urlopen('https://raw.githubusercontent.com/datasets/country-list/master/data.csv')
reader = csv.reader(iso_list)
data = list(reader)
#add Kosovo eventhough it is not in ISO3166
data.append(list(['Kosovo','XK']))
del data[0]
iso_list = []
for i in d... |
from django.shortcuts import render
from django.http import HttpResponse, HttpResponseRedirect
from .models import Ingredient_Spec, Ignore_Words
from objetos.models import Ingredient
# Create your views here.
def index(request):
lista = Ingredient_Spec.objects.order_by('-Count')[:20]
return render(request,'index.ht... |
#!/usr/bin/env python
from nose.tools import *
import networkx as nx
from networkx.testing.utils import *
class TestCore:
def setUp(self):
# G is the example graph in Figure 1 from Batagelj and
# Zaversnik's paper titled An O(m) Algorithm for Cores
# Decomposition of Networks, 2003,
... |
"""
Test module for misc.Transitions transform.
"""
from __init__ import DocutilsTestSupport # must be imported before docutils
from docutils.transforms.misc import Transitions
from docutils.parsers.rst import Parser
def suite():
parser = Parser()
s = DocutilsTestSupport.TransformTestSuite(parser)
s.gener... |
'''Find all classes of MasterModule and write them to modules.rst for
the autosummary.
'''
# Python modules
import glob
import os
import re
# File that will be appended with scripts
script_file = 'rst/scripts.rst'
# Find scripts
scripts = glob.glob('../../python/scripts/*.py')
scripts = [os.path.basename(x) for x in... |
from lib.alerttask import AlertTask
import pyes
class AlertSSHManyConns(AlertTask):
def main(self):
# look for events in last 15 mins
date_timedelta = dict(minutes=15)
# Configure filters using pyes
must = [
pyes.TermFilter('_type', 'bro'),
pyes.TermFilter('e... |
from easypy.meta import EasyMeta, GetAllSubclasses
def test_easy_meta_before_cls_init():
class FooMaker(metaclass=EasyMeta):
@EasyMeta.Hook
def before_subclass_init(name, bases, dct):
dct[name] = "foo"
class BarMaker(metaclass=EasyMeta):
@EasyMeta.Hook
def before_... |
"""Tests for `tf.data.experimental.prefetch_to_device()`."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from absl.testing import parameterized
from tensorflow.core.protobuf import config_pb2
from tensorflow.python.data.experimental.ops import prefetchi... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.