content stringlengths 4 20k |
|---|
from flask import Flask
from flask import Response
from generatefeed import Podcast
mediaFileDirectoryPath = "."
app = Flask(__name__, static_folder=mediaFileDirectoryPath)
# define feed functions here.
@app.route('/podcast/feed.xml')
def feed():
podcast = Podcast()
podcast.title = "MacBob2 Podcast"
podcast.desc... |
"""
otfPDF v1.3 Nov 30 2010
provides support for the ProofPDF script, for working with OpenType/TTF
fonts. Provides an implementation of the fontPDF font object. Cannot be
run alone.
"""
__copyright__ = """Copyright 2014 Adobe Systems Incorporated (http://www.adobe.com/). All Rights Reserved.
"""
from fontTools.pens.... |
"""
Listens for actions to be done to OSFstorage file nodes specifically.
"""
from django.apps import apps
from django.db import transaction
from website.project.signals import contributor_removed, node_deleted
from framework.celery_tasks import app
from framework.postcommit_tasks.handlers import enqueue_postcommit_ta... |
"""Provides the base class for Link objects used by other objects.
This class was created by realthunder during the `LinkMerge`
to demonstrate how to use the `App::Link` objects to create
Link aware arrays.
It is used by `draftobject.array` (ortho, polar, circular)
and `draftobject.patharray` to create respective Link... |
from mock import MagicMock, patch
import requests
import requests_mock
import unittest
from airflow.exceptions import AirflowException
from airflow.hooks.druid_hook import DruidDbApiHook, DruidHook
class TestDruidHook(unittest.TestCase):
def setUp(self):
super(TestDruidHook, self).setUp()
sessio... |
import gettext
import locale
import sys
_debug = False
def setup_locale_and_gettext():
"""Set up localization with gettext"""
package_name = "kupfer"
localedir = "./locale"
try:
from kupfer import version_subst
except ImportError:
pass
else:
package_name = version_subst.PACKAGE_NAME
localedir = version_... |
import datetime
from calendar import timegm
from functools import wraps
from django.contrib.sites.shortcuts import get_current_site
from django.core.paginator import EmptyPage, PageNotAnInteger
from django.http import Http404
from django.template.response import TemplateResponse
from django.urls import reverse
from dj... |
"""Downloads the UCI HIGGS Dataset and prepares train data.
The details on the dataset are in https://archive.ics.uci.edu/ml/datasets/HIGGS
It takes a while as it needs to download 2.8 GB over the network, process, then
store it into the specified location as a compressed numpy file.
Usage:
$ python data_download.py... |
'''
Created on Apr 25, 2017
@author: abhijit.tomar
'''
from sklearn.cross_validation import train_test_split
from pull import PullFunctions
from constants import DataConstants
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.ensemble import RandomForestClassifier
from sklearn.pipeline import Pi... |
#!/usr/bin/env python
from canari.maltego.utils import debug, progress
from canari.framework import configure #, superuser
from canari.maltego.entities import Phrase, IPv4Address
from common.launchers import get_qradio_data
__author__ = 'Zappus'
__copyright__ = 'Copyright 2016, TramaTego Project'
__credits__ = []
_... |
import os
import platform
import sys
from webkitpy.common.system import environment, executive, filesystem, platforminfo, user, workspace
class SystemHost(object):
def __init__(self):
self.executable = sys.executable
self.executive = executive.Executive()
self.filesystem = filesystem.File... |
import dis
import sys
from io import StringIO
import unittest
def disassemble(func):
f = StringIO()
tmp = sys.stdout
sys.stdout = f
dis.dis(func)
sys.stdout = tmp
result = f.getvalue()
f.close()
return result
def dis_single(line):
return disassemble(compile(line, '', 'single'))
cl... |
import io
import os
from nova.virt.libvirt import utils as libvirt_utils
files = {'console.log': b''}
disk_sizes = {}
disk_backing_files = {}
disk_type = "qcow2"
RESIZE_SNAPSHOT_NAME = libvirt_utils.RESIZE_SNAPSHOT_NAME
def create_image(disk_format, path, size):
pass
def create_cow_image(backing_file, path,... |
import chainerx
from chainerx import _docs
def _set_docs_device():
Device = chainerx.Device
_docs.set_doc(
Device,
"""Represents a physical computing unit.
""")
_docs.set_doc(
Device.synchronize,
"""Synchronizes the device.
""")
_docs.set_doc(
Device.name,
... |
from Tkinter import *
import pylab as PL
class GUI:
## GUI variables
titleText = 'PyCX Simulator' # window title
timeInterval = 0 # refresh time in milliseconds
running = False
modelFigure = None
def __init__(self,title='PyCX Simulator',interval=0):
self.... |
from google.appengine._internal.django.template import TemplateSyntaxError, TemplateDoesNotExist, Variable
from google.appengine._internal.django.template import Library, Node, TextNode
from google.appengine._internal.django.template.loader import get_template
from google.appengine._internal.django.conf import settings... |
"""
perf is a tool included in the linux kernel tree that
supports functionality similar to oprofile and more.
@see: http://lwn.net/Articles/310260/
"""
import os
import stat
import subprocess
import signal
import logging
from autotest.client import profiler, os_dep, utils
class perf(profiler.profiler):
version... |
'''Run list encoding utilities.
:since: pyglet 1.1
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id: $'
class _Run(object):
def __init__(self, value, count):
self.value = value
self.count = count
def __repr__(self):
return 'Run(%r, %d)' % (self.value, self.count)
class RunL... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
Use parsec.py to parse JSON text.
'''
__author__ = 'He Tao, <EMAIL>'
from parsec import *
whitespace = regex(r'\s*', re.MULTILINE)
lexeme = lambda p: p << whitespace
lbrace = lexeme(string('{'))
rbrace = lexeme(string('}'))
lbrack = lexeme(string('['))
rbrack = le... |
# -*- coding: utf-8 -*-
from openerp import http
import hashlib
from lxml import etree
from openerp.http import request
from openerp.modules.registry import RegistryManager
from openerp import SUPERUSER_ID
import time
import base64
import datetime,json
import cStringIO
import StringIO
import Image
import logging
impor... |
__author__ = "Peter Ogden"
__copyright__ = "Copyright 2019, Xilinx"
__email__ = "<EMAIL>"
import numpy as np
import warnings
class PynqBuffer(np.ndarray):
"""A subclass of numpy.ndarray which is allocated using
physically contiguous memory for use with DMA engines and
hardware accelerators. As physically ... |
"""
Internal tasks for redhat downstream builds
"""
import contextlib
import logging
import requests
import yaml
import os
from tempfile import NamedTemporaryFile
from teuthology.config import config as teuthconfig
from teuthology.parallel import parallel
from teuthology.orchestra import run
from teuthology.task.insta... |
from unittest.mock import patch
import pytest
import requests
from pyoffers.api import HasOffersAPI
from pyoffers.exceptions import HasOffersException, MaxRetriesExceeded
from pyoffers.models import Advertiser, Country
def test_invalid_network_id(api):
old_token = api.network_token
try:
api.network_... |
"""
Tests for the edx_proctoring integration into Studio
"""
from __future__ import absolute_import
from datetime import datetime, timedelta
import ddt
import six
from django.conf import settings
from edx_proctoring.api import get_all_exams_for_course, get_review_policy_by_exam_id
from mock import patch
from pytz im... |
#!/usr/bin/env python
import os
import logging
import time
import sys
l = logging.getLogger("angr.tests.test_ddg")
import nose
import angr
# Load the tests
test_location = str(os.path.dirname(os.path.realpath(__file__)))
def perform_one(binary_path):
proj = angr.Project(binary_path,
use... |
from dispel4py.workflow_graph import WorkflowGraph
from dispel4py.provenance import *
from dispel4py.seismo.seismo import *
from dispel4py.seismo.obspy_stream import createProcessingComposite, INPUT_NAME, OUTPUT_NAME
from dispel4py.base import SimpleFunctionPE, IterativePE, create_iterative_chain
import json
# from dis... |
# ICE Revision: $Id$
"""
Application class that implements pyFoamRunner
"""
from .PyFoamApplication import PyFoamApplication
from PyFoam.Execution.AnalyzedRunner import AnalyzedRunner
from PyFoam.LogAnalysis.BoundingLogAnalyzer import BoundingLogAnalyzer
from PyFoam.RunDictionary.SolutionDirectory import SolutionDir... |
"""Distance util functions."""
from numbers import Number
from homeassistant.const import (
LENGTH,
LENGTH_FEET,
LENGTH_KILOMETERS,
LENGTH_METERS,
LENGTH_MILES,
UNIT_NOT_RECOGNIZED_TEMPLATE,
)
VALID_UNITS = [LENGTH_KILOMETERS, LENGTH_MILES, LENGTH_FEET, LENGTH_METERS]
def convert(value: floa... |
import argparse
import logging
import os
import socket
import time
from libfb.py import log
from scubadata import ScubaData
def computecachesize(cachepath, logger):
"""measure size of cache directory"""
skipped = 0
cachesize = 0
manifestsize = 0
for root, dirs, files in os.walk(cachepath):
... |
"""
Module for Image annotations using annotator.
"""
from lxml import etree
from pkg_resources import resource_string
from xmodule.x_module import XModule
from xmodule.raw_module import RawDescriptor
from xblock.core import Scope, String
from xmodule.annotator_mixin import get_instructions, html_to_text
from xmodule.... |
import unittest
import mock
from evproc import exc
from evproc import processor
class TopoSortTest(unittest.TestCase):
def test_sorted(self):
nodes_map = {
'node0': mock.Mock(test_reqs=set()),
'node1': mock.Mock(test_reqs=set(['node0'])),
'node2': mock.Mock(test_reqs=... |
import win32gui, win32con, os
filter='Python Scripts\0*.py;*.pyw;*.pys\0Text files\0*.txt\0'
customfilter='Other file types\0*.*\0'
fname, customfilter, flags=win32gui.GetSaveFileNameW(
InitialDir=os.environ['temp'],
Flags=win32con.OFN_ALLOWMULTISELECT|win32con.OFN_EXPLORER,
File='somefilename', DefExt='p... |
from django.forms import widgets
from django.utils.translation import ugettext as _
from taiga.base.api import serializers
####################################################################
## Serializer fields
####################################################################
class JsonField(serializers.Writab... |
#!/usr/bin/env python
"""Executable Python script for checking log (entries) sizes.
CI/CD tool to assert that logs and databases are in certain bounds.
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for add... |
"""
A demonstration intended to illustrate possible problems with the Gaussian
fitting approach to measuring the cross-correlation peak.
If the cross-correlation peak is well-represented by a single Gaussian
component, the errors acquired from the normal least-squares fit should be
representative of the true error in ... |
"""accumulator.py: transcription of GeographicLib::Accumulator class."""
# accumulator.py
#
# This is a rather literal translation of the GeographicLib::Accumulator class
# from to python. See the documentation for the C++ class for more information
# at
#
# https://geographiclib.sourceforge.io/html/annotated.html
... |
"""Test the Kodi config flow."""
from homeassistant.components.kodi.const import DEFAULT_SSL
TEST_HOST = {
"host": "1.1.1.1",
"port": 8080,
"ssl": DEFAULT_SSL,
}
TEST_CREDENTIALS = {"username": "username", "password": "password"}
TEST_WS_PORT = {"ws_port": 9090}
UUID = "11111111-1111-1111-1111-1111111... |
from aodhclient import client
from aodhclient.v2 import alarm
from aodhclient.v2 import alarm_history
from aodhclient.v2 import capabilities
from aodhclient.v2 import quota
class Client(object):
"""Client for the Aodh v2 API.
:param string session: session
:type session: :py:class:`keystoneauth.adapter.A... |
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
from ansible.module_utils.basic import AnsibleModule, get_exception
try:
from pandevice import base
from pandevice import firewall
from pandevice import panorama
f... |
"""Cookies Tests Definitions."""
import logging
from categories import test_set_base
from base import util
_CATEGORY = 'cookies'
class CookiesTest(test_set_base.TestBase):
TESTS_URL_PATH = '/%s/tests' % _CATEGORY
def __init__(self, key, name, url_name, doc,
value_range=None, is_hidden_stat=Fal... |
'''
A very incomplete implementation of the XInput extension.
'''
import sys, array
from Xlib.protocol import rq
extname = 'XInputExtension'
PropertyDeleted = 0
PropertyCreated = 1
PropertyModified = 2
NotifyNormal = 0
NotifyGrab = 1
NotifyUngrab = 2
NotifyWhileGrabbed = 3
NotifyPassiveGrab = 4
NotifyPassiveUngrab... |
# DotBoxing PyQt GUI Code
# Matt Mahan and Matt Rundle
# Programming Paradigms PyGameTwisted Project
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from mainwindow import Ui_MainWindow
from username import Ui_username
from challenge import Ui_challenge
class guiQT(QMainWindow, Ui_MainWindow):
def __init__(sel... |
import logging
from autotest.client.shared import error
from virttest import env_process
from virttest import utils_misc
from virttest import utils_test
@error.context_aware
def run(test, params, env):
"""
boot cpu model test:
steps:
1). boot guest with cpu model
2). check flags if enable_check ... |
"""Automatically setup docs for a project
Call from command line:
bench setup-docs app path
"""
from __future__ import unicode_literals, print_function
import os, json, frappe, shutil
from frappe.utils import markdown
class setup_docs(object):
def __init__(self, app, target_app):
"""Generate source templates f... |
from nose.tools import *
from django.test import TestCase
from qualitio import store
import models
class TestRunTestCase(TestCase):
def setUp(self):
self.test_case_directory = store.TestCaseDirectory.objects.create(parent=None,
name... |
# coding: utf-8
import json
from copy import deepcopy
from django.test import TestCase
from formpack.utils.expand_content import SCHEMA_VERSION
from kpi.exceptions import BadAssetTypeException
from kpi.utils.hash import get_hash
from ..models import Asset
from ..models import AssetVersion
class AssetVersionTestCase... |
from django.test import TestCase
from common.utils import BaseAuthenticatedClient
from dialer_gateway.models import Gateway
from dialer_gateway.utils import prepare_phonenumber
class GatewayView(BaseAuthenticatedClient):
"""Test Function to check Gateway Admin pages"""
def test_admin_gateway_view_list(self):... |
# -*- coding: utf-8 -*-
import mock
from website import mailchimp_utils
from tests.base import OsfTestCase
from nose.tools import * # noqa; PEP8 asserts
from osf_tests.factories import UserFactory
import mailchimp
from framework.celery_tasks import handlers
class TestMailChimpHelpers(OsfTestCase):
def setUp(sel... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
elife_v3, the switch to versionless urls
essentially the same as elife_v2 BUT the version suffix is now optional.
"""
# we can reuse these functions
import elife_v1
# these seemingly unused imports are actually used
from elife_ga_metrics.elife_v1 import event_counts, ev... |
# coding=utf-8
"""
InaSAFE Disaster risk assessment tool by AusAid -**InaSAFE Wizard**
This module provides: Keyword Wizard Step: Field
Contact : <EMAIL>
.. note:: 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 F... |
"""
If a child cell hasn't sent capacity or capability updates in a while,
downgrade its likelihood of being chosen for scheduling requests.
"""
from oslo_config import cfg
from oslo_log import log as logging
from oslo_utils import timeutils
from nova.cells import weights
from nova.i18n import _LW
LOG = logging.getL... |
# Converted from ElasticBeanstalk_Python_Sample.template located at:
# http://aws.amazon.com/cloudformation/aws-cloudformation-templates/
from troposphere import GetAtt, Join, Output
from troposphere import Parameter, Ref, Template
from troposphere.elasticbeanstalk import Application, Environment
from troposphere.elas... |
import logging
import socket
import threading
import errno
from pulseaudio_streamer import network
port_inc = 0
class Server:
PORT_RANGE_START = 8804
PORT_RANGE_END = 8854
def __init__(self, stop_event, encoder):
self.encoder = encoder
self.ip = network.getFistLanIp()
self.stop_... |
# -*- coding: utf-8 -*-
"""QGIS Unit tests for QgsExpression.
.. note:: This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
"""
__a... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys # for system io
import datetime
import sqlite3 # for DB Activities
import urllib2 # for url parssing et al
import textwrap # To limit o/p characters per line
import subprocess # To invoke espeak
import time
import os
from nltk.corpus import wo... |
#-------------------------------------------------------------------------------
# elftools: elf/sections.py
#
# ELF sections
#
# Eli Bendersky (<EMAIL>)
# This code is in the public domain
#-------------------------------------------------------------------------------
from ..common.utils import struct_parse, elf_asse... |
"""Config flow utilities."""
from collections import OrderedDict
from pyvesync import VeSync
import voluptuous as vol
from homeassistant import config_entries
from homeassistant.const import CONF_PASSWORD, CONF_USERNAME
from homeassistant.core import callback
from .const import DOMAIN
class VeSyncFlowHandler(confi... |
"A library for proxy configuration and autodetection."
import ctypes
import ctypes.util
import platform
import sys
def _load(name, *versions):
for ver in versions:
try: return ctypes.cdll.LoadLibrary('lib%s.so.%s' % (name, ver))
except: pass
name_ver = ctypes.util.find_library(name)
if na... |
import os
def test_RosdepInternalError():
from rosdep2.core import RosdepInternalError
try:
raise Exception('foo')
except Exception as e:
ex = RosdepInternalError(e)
assert e == ex.error
def test_rd_debug():
# just tripwire/coverage
from rosdep2.core import rd_debug
... |
import unittest
from parameterized import parameterized
from airflow import DAG
from airflow.api_connexion.exceptions import EXCEPTIONS_LINK_MAP
from airflow.models import Log, TaskInstance
from airflow.operators.dummy import DummyOperator
from airflow.security import permissions
from airflow.utils import timezone
fr... |
# Portalocker taken from ActiveState.com.
## {{{ http://code.activestate.com/recipes/65203/ (r7)
# portalocker.py - Cross-platform (posix/nt) API for flock-style file locking.
# Requires python 1.5.2 or better.
"""Cross-platform (posix/nt) API for flock-style file locking.
Synopsis:
import portalo... |
import typing
from pathlib import Path
import pandas as pd
import matchzoo
def load_data(
stage: str = 'train',
task: str = 'ranking',
return_classes: bool = False
) -> typing.Union[matchzoo.DataPack, typing.Tuple[matchzoo.DataPack, list]]:
"""
Load WikiQA data.
:param stage: One of `train`... |
from setuptools import setup, Extension
import sys
def check_system(systems, message):
import sys
if sys.platform in systems:
return
print(message)
sys.exit(1)
OTHER_OS_MESSAGE = """
*****************************************************
* pyxpcconnection only works on Mac ... |
'''
Copyright (c) <2012> Tarek Galal <<EMAIL>>
Permission is hereby granted, free of charge, to any person obtaining a copy of this
software and associated documentation files (the "Software"), to deal in the Software
without restriction, including without limitation the rights to use, copy, modify,
merge, publish,... |
from AlgorithmImports import *
### <summary>
### In this algorithm we demonstrate how to use the UniverseSettings
### to define the data normalization mode (raw)
### </summary>
### <meta name="tag" content="using data" />
### <meta name="tag" content="universes" />
### <meta name="tag" content="coarse universes" />
##... |
import sys, errno, os, time
from twisted.trial import unittest
from twisted.python.util import sibpath
from twisted import plugin, plugins
# Indicates whether or not the unit tests are being run. This is
# inspected by notestplugin.py
running = False
begintest = '''
from zope.interface import classProvides
from tw... |
# -*- coding: utf-8 -*-
"""
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License,
or (at your option) any later version.
This program is distributed in... |
import json
import logging
import random
import subprocess
from functools import partial
import pkg_resources
import requests
import time
import sys
from hamcrest import assert_that, is_
from tests import available_models
def create_session(client, id):
result = client.post("/switches-sessions/{}".format(id),... |
from datetime import datetime, time
from dateutil.relativedelta import relativedelta
from odoo import fields
from odoo.tests import common
from odoo.addons.hr_timesheet.tests.test_timesheet import TestCommonTimesheet
class TestTimesheetHolidaysCreate(common.TransactionCase):
def test_status_create(self):
... |
from unittest import TestCase
import numpy as np
import pandas as pd
import trtools.tools.tile as tile
class TestTile(TestCase):
def __init__(self, *args, **kwargs):
TestCase.__init__(self, *args, **kwargs)
def runTest(self):
pass
def setUp(self):
pass
def test_base_tile(s... |
import logging
from flask import Flask, jsonify, request, g, make_response
from api import app
from werkzeug.exceptions import HTTPException
logger = logging.getLogger(__name__)
def standard_responce(data, code):
if isinstance(data, basestring):
data = {'error': data}
elif isinstance(data, HTTPExcepti... |
import logging
import sys
import os
from optparse import make_option
from datetime import timedelta
from django.core.management.base import BaseCommand
from django.utils import timezone
from django.conf import settings
from ...export import generate_donations_csv_file, generate_organizations_csv_file, generate_users_cs... |
"""Generic logging, the way I remember it from scripts gone by.
TODO:
- network logging support.
- log rotation config
"""
from datetime import datetime
import logging
import os
import sys
import traceback
# Define our own FATAL_LEVEL
FATAL_LEVEL = logging.CRITICAL + 10
logging.addLevelName(FATAL_LEVEL, 'FATAL')
# ... |
import logging
from openerp import models
_logger = logging.getLogger(__name__)
class AutoVacuum(models.TransientModel):
""" Expose the vacuum method to the cron jobs mechanism. """
_name = 'ir.autovacuum'
def _gc_transient_models(self, cr, uid, *args, **kwargs):
for model in self.pool.itervalu... |
'''
A distributed viewer setup: This Python scripts starts an
avango.osg.simpleviewer and connects to the distribution group "testgroup". If
there is another instance loading some geometry under this node this model
should also appear in the client. (see also simpleviewer-srv.py)
'''
import avango
import avango.scrip... |
from itertools import product, combinations
from random import shuffle
from typing import Optional, List, Iterable
class Card(tuple):
pass
class Deck(object):
def __init__(self, num_features: int, num_options_per_feature: int):
self.num_features = num_features
self.num_options_per_feature =... |
import os
import GafferSceneTest
import GafferRenderMan
class RenderManTestCase( GafferSceneTest.SceneTestCase ) :
def setUp( self ) :
self.__compiledShaders = set()
def compileShader( self, sourceFileName, shaderName=None ) :
# perhaps one day we'll need to implement this for other renderman
# renderers,... |
# -*- coding: utf-8 -*-
"""
Based on django mongotools (https://github.com/wpjunior/django-mongotools) by
Wilson Júnior (<EMAIL>).
"""
import copy
from django import forms
from django.core.validators import (EMPTY_VALUES, MinLengthValidator,
MaxLengthValidator)
try:
from djang... |
#!/usr/bin/env python
##
## You can download latest version of this file:
## $ wget https://gist.github.com/vaab/e0eae9607ae806b662d4/raw -O setup.py
## $ chmod +x setup.py
##
## This setup.py is meant to be run along with ``./autogen.sh`` that
## you can also find here: https://gist.github.com/vaab/9118087/raw
##
... |
import glob
from optparse import OptionParser
import os
import shutil
import sys
import tempfile
import pmenv
import util
__author__ = "Aurelien FORET"
__version__ = "0.4"
def resolve_binary_path(option, opt_str, value, parser):
setattr(parser.values, option.dest, os.path.abspath(value))
def glob_tests(option, ... |
# -*- coding: utf-8 -*-
import os
import sys
import multiprocessing
#do not generate pyc file
#sys.dont_write_bytecode = True
import krait_rc
from PySide2.QtCore import Qt, QCoreApplication
from PySide2.QtGui import QPixmap, QFont, QFontDatabase
from PySide2.QtWidgets import QApplication, QSplashScreen
#from PySide2.Q... |
"""minimal package setup"""
import os
from setuptools import setup, find_packages
# Utility function to read the README file.
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(
name="magpysv",
version="1.1",
author="Grace Cox",
author_email="<EMAIL>",
li... |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {
'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'
}
DOCUMENTATION = r'''
---
module: meraki_admin
short_description: Manage administrators in the Meraki cloud
version_adde... |
#!/usr/bin/python
"""The :class:`FunctionalTester` object provides a higher-level interface to
working with a Trac environment to make test cases more succinct.
"""
from trac.tests.functional import internal_error
from trac.tests.functional.better_twill import tc, b
from trac.tests.contentgen import random_page, rando... |
import logging.config
import uuid
import structlog
import structlog.stdlib
RENDERER = structlog.processors.JSONRenderer()
class StructlogFormatter(logging.Formatter):
def format(self, record):
# TODO: Figure out a better way of handling this besides just looking
# at the logger name, ide... |
import unittest
import functools
import numpy
from operator import mul
import six
import chainer
from chainer.backends import cuda
from chainer import functions
from chainer import testing
from chainer.testing import attr
from chainer.utils import conv
from chainer_tests.functions_tests.pooling_tests import pooling_n... |
import datetime
import json
import random
from six import string_types
from mcstatus.protocol.connection import Connection
class ServerPinger:
def __init__(self, connection, host="", port=0, version=47, ping_token=None):
if ping_token is None:
ping_token = random.randint(0, (1 << 63) - 1)
... |
"""A nice way to loop until some iteration experiences no transient errors.
@see: L{test_retries}
"""
import time
import random
class ImmediateRetry(object):
"""A nice way to loop until some iteration experiences no transient errors.
Example usage:
>>> for retry in retries.ImmediateRetry():
... ... |
# -*- coding: utf-8 -*-
from django.db.models import F
from django.db.models.aggregates import Max
from django.db.models.query_utils import Q
from 臺灣言語資料庫.資料模型 import 外語表
from 臺灣言語資料庫.資料模型 import 文本表
class 外語請教條(外語表):
class Meta:
proxy = True
@classmethod
def 有建議講法的外語表(cls):
return (
... |
from djanalytics.tests.base_chart_test import BaseChartTest
from djanalytics import models
from django.core.urlresolvers import reverse
class TestReferrerChart(BaseChartTest):
def test_referrer(self):
for i in range(3):
models.RequestEvent.objects.create(
client=self.dja_clien... |
"""
OpenStreetMap (Map)
@website https://openstreetmap.org/
@provide-api yes (http://wiki.openstreetmap.org/wiki/Nominatim)
@using-api yes
@results JSON
@stable yes
@parse url, title
"""
from json import loads
# engine dependent config
categories = ['map']
paging = False
# search-url
ba... |
import webapp2
import urllib2
import logging
import urlparse
class MainPage(webapp2.RequestHandler):
def get(self):
is_bot = 0
if 'User-Agent' in self.request.headers:
is_bot = self.request.headers['User-Agent'].find('facebookexternalhit')
#is_bot = self.request.headers['User-Agent'].find('Chrome')... |
"""
pretty.py
Contains the main function pretty( ) which takes in the name of a raw text file, and outputs an HTML file. Optionally, also outputs the MD file used, and also optionally a file which is useful for debugging. Takes the parameter MAGIC_CODE_RATIO which can be tweaked to change how aggressively we detect... |
"""
:Author: Simon Gibbons (<EMAIL>)
"""
from .core import DefaultSplitter
from .fixedwidth import (FixedWidth,
FixedWidthData,
FixedWidthHeader,
FixedWidthTwoLineDataSplitter)
class SimpleRSTHeader(FixedWidthHeader):
position_line = 0
... |
# pylint: skip-file
# flake8: noqa
# noqa: E302,E301
# pylint: disable=too-many-instance-attributes
class RouteConfig(object):
''' Handle route options '''
# pylint: disable=too-many-arguments
def __init__(self,
sname,
namespace,
kubeconfig,
... |
"""Star98 Educational Testing dataset."""
__docformat__ = 'restructuredtext'
COPYRIGHT = """Used with express permission from the original author,
who retains all rights."""
TITLE = "Star98 Educational Dataset"
SOURCE = """
Jeff Gill's `Generalized Linear Models: A Unified Approach`
http://jgill.wustl.e... |
"""
Template file used by ExpGenerator to generate the actual
permutations.py file by replacing $XXXXXXXX tokens with desired values.
This permutations.py file was generated by:
'/Users/ronmarianetti/nupic/eng/lib/python2.6/site-packages/nupic/frameworks/opf/expGenerator/ExpGenerator.py'
"""
import os
from nupic.swa... |
# /usr/bin/env python
'''
Written by Kong Xiaolu and CBIG under MIT license:
https://github.com/ThomasYeoLab/CBIG/blob/master/LICENSE.md
'''
import os
import numpy as np
import torch
import CBIG_pMFM_basic_functions as fc
import warnings
def CBIG_mfm_test_desikan_main(gpu_index=0):
torch.cuda.set_device(gpu_inde... |
# -*- coding: utf-8 -*-
"""
/***************************************************************************
GranicznikiDialog
A QGIS plugin
Graniczniki
-------------------
begin : 2014-05-17
copyright : (C) 2014 by Pa... |
try:
import start as start
cubit = start.start_cubit()
except:
try:
import cubit
except:
print 'error importing cubit, check if cubit is installed'
pass
def get_cubit_version():
v=cubit.get_version()
try:
v=float(v[0:4])
except:
v=f... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.