content stringlengths 4 20k |
|---|
#! /usr/bin/env python
import sys, os
import ddlib # DeepDive python utility
ARR_DELIM = '~^~'
# Load keyword dictionaries using ddlib, for domain-specific features
# Words in "married" dictionary are indicative of marriage
# Words in "non_married" dictionary are indicative of non_marriage
APP_HOME = os.environ[... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# advent1_easterbunny.py
#
import sys, operator
ORIENTATIONS = "NESW"
DISTANCE_FACTORS = {
'N': (0, 1),
'E': (1, 0),
'S': (0, -1),
'W': (-1, 0)
}
DIRECTION_OFFSETS = {'L': -1, 'R': 1}
def taxicab_magnitude(position):
return sum([abs(m) for m in positio... |
"""Analyzes User handles registered with the Win32k Subsystem.
Windows allows user applications to register handles with the GUI subsystem. The
GUI subsystem can then call back into the user code for various purposes. The
Win32k allocates tag* structures for each user object that is registered. These
allocations exist... |
"""Test for Email Settings service."""
__author__ = '<EMAIL>'
import getpass
import gdata.apps.emailsettings.service
import unittest
domain = ''
admin_email = ''
admin_password = ''
username = ''
class EmailSettingsTest(unittest.TestCase):
"""Test for the EmailSettingsService."""
def setUp(self):
self.... |
from __future__ import unicode_literals
import frappe
from frappe import _
from frappe.model.document import Document
class CourseSchedule(Document):
def validate(self):
self.instructor_name = frappe.db.get_value("Instructor", self.instructor, "instructor_name")
self.set_title()
self.validate_course()
self.va... |
# This file helps to compute a version number in source trees obtained from
# git-archive tarball (such as those provided by githubs download-from-tag
# feature). Distribution tarballs (built by setup.py sdist) and build
# directories (produced by setup.py build) will contain a much shorter file
# that just contains th... |
# -*- coding: utf-8 -*-
from flask import _request_ctx_stack as stack
from .services import Services
from .auth import Authorization
from .db import db
class Container(object):
def init_app(self, app):
app.teardown_request(self.teardown)
def teardown(self, exception):
pass
def set_acc... |
from django.db.backends import BaseDatabaseOperations
class DatabaseOperations(BaseDatabaseOperations):
def __init__(self, connection):
super(DatabaseOperations, self).__init__(connection)
def date_extract_sql(self, lookup_type, field_name):
# http://www.postgresql.org/docs/8.0/static/functio... |
from urllib import urlencode
from social.backends.oauth import BaseOAuth2
class SalesforceOAuth2(BaseOAuth2):
"""Salesforce OAuth2 authentication backend"""
name = 'salesforce-oauth2'
AUTHORIZATION_URL = \
'https://login.salesforce.com/services/oauth2/authorize'
ACCESS_TOKEN_URL = 'https://log... |
from msrest.serialization import Model
class HealthInformation(Model):
"""Represents common health report information. It is included in all health
reports sent to health store and in all health events returned by health
queries.
.
:param source_id: The source name which identifies the
clien... |
from a10sdk.common.A10BaseClass import A10BaseClass
class Http(A10BaseClass):
"""Class Description::
HTTP service.
Class http supports CRUD Operations and inherits from `common/A10BaseClass`.
This class is the `"PARENT"` class for this module.`
:param management: {"default": 0, "optional": ... |
"""AWS plugin for integration tests."""
from __future__ import absolute_import, print_function
import os
from lib.util import (
ApplicationError,
display,
is_shippable,
)
from lib.cloud import (
CloudProvider,
CloudEnvironment,
)
from lib.core_ci import (
AnsibleCoreCI,
)
class AwsCloudPro... |
# -*- coding: utf-8 -*-
"""Module containing the search classes to retrieve DOV interpretations."""
from pydov.search.abstract import AbstractSearch
from pydov.types.interpretaties import (FormeleStratigrafie,
GecodeerdeLithologie,
Geotech... |
"""Model class, used in Structure objects."""
from Bio.PDB.Entity import Entity
class Model(Entity):
"""
The object representing a model in a structure. In a structure
derived from an X-ray crystallography experiment, only a single
model will be present (with some exceptions). NMR structures
no... |
"""Alignment with SNAP: http://snap.cs.berkeley.edu/
"""
import os
from bcbio import bam, utils
from bcbio.distributed.transaction import file_transaction
from bcbio.pipeline import config_utils
from bcbio.ngsalign import novoalign, postalign
from bcbio.provenance import do
def align(fastq_file, pair_file, index_dir,... |
import os, sys
from ctypes import *
up=2
def setlibpath(up):
import sys
path=os.path.normpath(os.path.split(os.path.realpath(__file__))[0]+'\..'*up)
if path not in sys.path:
sys.path.append(path)
setlibpath(up)
from haru import *
from haru.c_func import *
from haru.hpdf_errorcode im... |
import os
import threading
from uuid import uuid4
from opennode.cli.actions import templates
from opennode.cli.actions import storage
from opennode.cli.actions import vm
from opennode.cli.tests import BaseTestCase, signal_when_called
class TestOpenVZ(BaseTestCase):
def _setUp(self):
self.testsp = 'loca... |
"""
Option class representing a boolean (yes/no, true/false).
"""
#-------------------------------------------------------------------------
#
# gramps modules
#
#-------------------------------------------------------------------------
from . import Option
#-----------------------------------------------------------... |
import unittest2 as unittest
from webkitpy.common.system.systemhost_mock import MockSystemHost
from webkitpy.port import Port, Driver, DriverOutput
from webkitpy.port.server_process_mock import MockServerProcess
# FIXME: remove the dependency on TestWebKitPort
from webkitpy.port.port_testcase import TestWebKitPort
... |
"""
.. moduleauthor:: easygui developers and Stephen Raymond Ferg
.. default-domain:: py
.. highlight:: python
Version |release|
"""
import os
import sys
import traceback
# A set of variables and functions to centralize differences between
# python 2 and 3
runningPython27 = False
runningPython34 = False
if 0x02070... |
# Coordinated I/O for parallel systems
#
# Written by Konrad Hinsen <<EMAIL>>
# last revision: 2000-7-31
#
class LogFile:
"""File for logging events from all processes
Constructor: LogFile(|filename|, |communicator|=None)
Arguments:
|filename| -- the name of the file
|communicator| -- the comm... |
# -*- coding: utf-8 -*-
#
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_DialogModulationParameters(object):
def setupUi(self, DialogModulationParameters):
DialogModulationParameters.setObjectName("DialogModulationParameters")
Dialog... |
import pytest
import os
import fnmatch
import tarfile
import numpy as np
import dask
from contextlib import contextmanager
import py
import tempfile
import hashlib
try:
import urllib.request as req
except ImportError:
# urllib in python2 has different structure
import urllib as req
from xmitgcm.file_utils ... |
"""Views fo the node settings page."""
# -*- coding: utf-8 -*-
import os
import httplib as http
from flask import request
from box.client import BoxClientException
from urllib3.exceptions import MaxRetryError
from framework.exceptions import HTTPError
from website.util import web_url_for
from website.util import per... |
"""Generic class for Set/Get properties of GData Provisioning clients."""
__author__ = 'Gunjan Sharma <<EMAIL>>'
import gdata.apps
import gdata.apps_property
import gdata.data
class AppsPropertyEntry(gdata.data.GDEntry):
"""Represents a generic entry in object form."""
property = [gdata.apps_property.AppsPr... |
from builtins import str
__author__ = 'janomar'
import logging
import jaydebeapi
from airflow.hooks.dbapi_hook import DbApiHook
class JdbcHook(DbApiHook):
"""
General hook for jdbc db access.
If a connection id is specified, host, port, schema, username and password will be taken from the predefined con... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
from six import string_types
from ansible.errors import AnsibleError, AnsibleParserError
from ansible.playbook.attribute import Attribute, FieldAttribute
from ansible.playbook.base import Base
from ansible.playbook.become import ... |
import yaml, yaml.composer, yaml.constructor, yaml.resolver
class CanonicalError(yaml.YAMLError):
pass
class CanonicalScanner:
def __init__(self, data):
if isinstance(data, bytes):
try:
data = data.decode('utf-8')
except UnicodeDecodeError:
rais... |
"""
Tests for mamba.core.packages
"""
import sys
import tempfile
import functools
from twisted.trial import unittest
from twisted.python import filepath
from mamba.core import packages, GNU_LINUX
from mamba.application.model import ModelManager
from mamba.application.controller import ControllerManager
class Packa... |
# -*- 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):
# Adding field 'CourseEnrollmentAllowed.auto_enroll'
db.add_column('student_courseenrollmentallowed', 'auto_... |
"""utilities for checking submodule status"""
#-----------------------------------------------------------------------------
# Copyright (C) 2013 The IPython Development Team
#
# Distributed under the terms of the BSD License. The full license is in
# the file COPYING, distributed as part of this software.
#-----... |
import json
from subprocess import call
def strip_obj_c(string):
return string.rstrip("\"\n").lstrip("@\"")
def add_obj_c(string):
return '@\"'+string+'\"'
def convert_to_json(file):
enDict = {}
desciptionDict = {}
keys = []
for line in file:
if '#define EN_' in line:
lineSplitArray = line.split(' ',2)
... |
from typing import Any
from argparse import ArgumentParser
import sys
from django.contrib.auth import authenticate, login, get_backends
from django.core.management.base import BaseCommand
from django.conf import settings
from django_auth_ldap.backend import LDAPBackend, _LDAPUser
# Quick tool to test whether you'r... |
"""Module level filter."""
__RCSID__ = '$Id$'
from DIRAC.FrameworkSystem.private.standardLogging.LogLevels import LogLevels
DOT = '.'
LEVEL = '__level__'
class ModuleFilter(object):
"""Filter module to set loglevel per module.
::
Resources
{
LogBackends
{
<backend>
{
... |
import sys
import py
BuiltinAssertionError = py.builtin.builtins.AssertionError
_reprcompare = None # if set, will be called by assert reinterp for comparison ops
def _format_explanation(explanation):
"""This formats an explanation
Normally all embedded newlines are escaped, however there are
three exce... |
#!/usr/bin/env python
import rospy
from jsk_network_tools.msg import Heartbeat, HeartbeatResponse
from std_msgs.msg import Float32
class Master():
def __init__(self):
rospy.init_node('heartbeat_master')
self.rate = rospy.get_param("~rate", 1.0)
self.pub_request = rospy.Publisher("heartbeat/... |
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
# vim: set et sw=4 ts=4 sts=4 ff=unix fenc=utf8:
# http://binux.me
# Created on 2014-10-13 22:18:36
import json
import time
from pymongo import MongoClient
from pyspider.database.base.resultdb import ResultDB as BaseResultDB
from .mongodbbase import SplitTableMix... |
import discord
from discord.ext import commands
from random import randint
import aiohttp
import random
class Image:
"""Commandes de recherche d'Images."""
def __init__(self, bot):
self.bot = bot
#Reserved for further ... stuff
"""Commands section"""
@commands.command(... |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
import json
import logging
from ansible.module_utils.basic import AnsibleModule
from ansibl... |
"""
Micro Python driver for SD cards using SPI bus.
Requires an SPI bus and a CS pin. Provides readblocks and writeblocks
methods so the device can be mounted as a filesystem.
Example usage:
import pyb, sdcard, os
sd = sdcard.SDCard(pyb.SPI(1), pyb.Pin.board.X5)
pyb.mount(sd, '/sd2')
os.listdir('/')... |
from django.contrib.staticfiles.testing import StaticLiveServerTestCase
from django.test import modify_settings
from django.test.selenium import SeleniumTestCase
from django.utils.deprecation import MiddlewareMixin
from django.utils.translation import gettext as _
class CSPMiddleware(MiddlewareMixin):
"""The admi... |
#!/usr/bin/python2
# coding: utf-8
import requests
import json
# Demands Stanford Core NLP server running on a defined port
# Start server with something like:
# java -mx4g -cp "*" edu.stanford.nlp.pipeline.StanfordCoreNLPServer --port 9999
port = 9999
conversion = {"CC": "CONJ",
"CD": "ADJ",
... |
import mock
from oslo_serialization import jsonutils
import webob
from nova.api.openstack.compute import (extended_volumes
as extended_volumes_v21)
from nova.api.openstack import wsgi as os_wsgi
from nova import compute
from nova import objects
from nova.objects impor... |
r"""
*****************************************
espressopp.interaction.CoulombKSpaceEwald
*****************************************
Coulomb potential and interaction Objects (`K` space part)
.. math::
\frac{1}{2\pi V}
\sum_{m\in \mathbb{Z}^3 \atop 0<|m|<k_{max}}
\frac{exp(-\frac{\pi^2}{\alpha^... |
# -*- coding: utf-8 -*-
"""
***************************************************************************
TestData.py
---------------------
Date : March 2013
Copyright : (C) 2013 by Victor Olaya
Email : volayaf at gmail dot com
*******************************... |
"""Tests for jslex."""
# originally from https://bitbucket.org/ned/jslex
from django.test import SimpleTestCase
from django.utils.jslex import JsLexer, prepare_js_for_gettext
class JsTokensTest(SimpleTestCase):
LEX_CASES = [
# ids
("a ABC $ _ a123", ["id a", "id ABC", "id $", "id _", "id a123"]),... |
# coding=utf-8
from builtins import object
import datetime
import django_filters
import pytz
import six
from django_filters.fields import Lookup
from realtime.models.earthquake import Earthquake
__author__ = 'Rizky Maulana Nugraha "lucernae" <<EMAIL>>'
__date__ = '23/06/15'
class DateTimeDurationFilter(django_filt... |
ANSIBLE_METADATA = {'status': ['preview'],
'supported_by': 'community',
'version': '1.0'}
import sys
import getpass
import keyring
from ansible.config.manager import ConfigManager, get_ini_config_value
def main():
config = ConfigManager()
username = get_ini_config_val... |
import glob
from optparse import OptionParser
import subprocess
import os
import os.path
import re
import shutil
import sys
version = 'build-all.py, version 0.01'
build_dir = '../all-kernels'
make_command = ["vmlinux", "modules", "dtbs"]
make_env = os.environ
make_env.update({
'ARCH': 'arm',
'KCONFIG_... |
'''outputs features for HOG machine learning'''
from matplotlib import pyplot as plt
from matplotlib import image as mpimg
from scipy import sqrt, pi, arctan2, cos, sin, ndimage, fftpack, stats
from skimage import exposure, measure, feature
import pandas as pd
from PIL import Image
import cStringIO
import urllib2
impor... |
from ctypes import c_char_p, c_int, c_size_t, c_ubyte, POINTER
from django.contrib.gis.geos.libgeos import CS_PTR, GEOM_PTR
from django.contrib.gis.geos.prototypes.errcheck import (
check_geom, check_minus_one, check_sized_string, check_string, check_zero)
from django.contrib.gis.geos.prototypes.threadsafe import G... |
"""Unit tests for the :mod:`iris.fileformats` package."""
from __future__ import (absolute_import, division, print_function)
from six.moves import (filter, input, map, range, zip) # noqa
import iris.tests as tests
class TestField(tests.IrisTest):
def _test_for_coord(self, field, convert, coord_predicate, expec... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.conf.urls import url
from django.contrib.auth import views as auth_views
from django.contrib.auth.decorators import login_required
from django.views.decorators.cache import cache_page
from django.views.generic import TemplateView
from . impor... |
import copy
class ObjectProperty(object):
OBJECT_ID = "id"
OBJECT_SUPER_TYPE = "super_type"
OBJECT_TYPE = "type"
OBJECT_STATE = "state"
DESCRIPTION = "description"
CM_ID = "cm_id"
CONNECTION_TYPES = "connection_types"
COMPONENT_TYPES = "component_types"
class State:
INITIA... |
from datetime import datetime
from dateutil.relativedelta import relativedelta
from openerp.osv import fields
from openerp.osv import osv
from openerp.tools.translate import _
from openerp import netsvc
class procurement_order(osv.osv):
_inherit = 'procurement.order'
_columns = {
'bom_id': fields.many2... |
import collections
import warnings
from math import ceil
from django.utils import six
from django.utils.functional import cached_property
class UnorderedObjectListWarning(RuntimeWarning):
pass
class InvalidPage(Exception):
pass
class PageNotAnInteger(InvalidPage):
pass
class EmptyPage(InvalidPage):... |
import requests
from .common import DEFAULT_REGION, API_RATE_LIMITS
from .exceptions import validate_response, RGApiWarning
class RGApiClient(object):
def __init__(self, key, default_region=DEFAULT_REGION, limits=API_RATE_LIMITS.DEVELOP):
self.key = key
self.default_region = default_region
... |
DATE_FORMAT = 'd F Y'
TIME_FORMAT = 'H:i:s'
DATETIME_FORMAT = 'd F Y H:i:s'
YEAR_MONTH_FORMAT = 'F Y'
MONTH_DAY_FORMAT = 'd F'
SHORT_DATE_FORMAT = 'd M Y'
SHORT_DATETIME_FORMAT = 'd M Y H:i:s'
FIRST_DAY_OF_WEEK = 1 # Pazartesi
# The *_INPUT_FORMATS strings use the Python strftime format syntax,
# see http://docs.pytho... |
from __future__ import unicode_literals
from django.contrib.sites.models import Site
from django.db import models
from django.urls import get_script_prefix
from django.utils.encoding import iri_to_uri, python_2_unicode_compatible
from django.utils.translation import ugettext_lazy as _
@python_2_unicode_compatible
cl... |
import TaskPanel
def load():
""" Loads the tool """
TaskPanel.createTask() |
from bson.objectid import ObjectId
__obj_type_to_key_descriptor__ = {
'Comment': 'object_id',
'Event': 'id',
'UserName': 'id',
'Target': 'id',
'Hash': 'id',
'Dataset': 'id',
'EmailAddress': 'id',
}
def class_from_id(type_, _id):
"""
Return an instantiated class object.
:param... |
import functools
from django.http import HttpRequest
def sensitive_variables(*variables):
"""
Indicates which variables used in the decorated function are sensitive, so
that those variables can later be treated in a special way, for example
by hiding them when logging unhandled exceptions.
Two f... |
from pycp2k.inputsection import InputSection
class _shell2(InputSection):
def __init__(self):
InputSection.__init__(self)
self.Section_parameters = None
self.Core_charge = None
self.Shell_charge = None
self.Mass_fraction = None
self.K2_spring = None
self.K4_... |
import urllib,urllib2,re,cookielib,string, urlparse,sys,os
import xbmc, xbmcgui, xbmcaddon, xbmcplugin,urlresolver
from resources.libs import main
#Mash Up - by Mash2k3 2012.
from t0mm0.common.addon import Addon
addon_id = 'plugin.video.movie25'
selfAddon = xbmcaddon.Addon(id=addon_id)
addon = Addon('plugin.video.mo... |
""" Misc utilities for the library
Authors: Bertrand Thirion, Matthew Brett, 2015
"""
import sys
import scipy.linalg as spl
import numpy as np
from scipy.stats import norm
from warnings import warn
py3 = sys.version_info[0] >= 3
def z_score(pvalue):
""" Return the z-score corresponding to a given p-value.
"... |
from calendar import timegm
import datetime
from functools import wraps
from django.contrib.sites.shortcuts import get_current_site
from django.core import urlresolvers
from django.core.paginator import EmptyPage, PageNotAnInteger
from django.http import Http404
from django.template.response import TemplateResponse
fr... |
from sqlalchemy import MetaData, Table
def upgrade(migrate_engine):
meta = MetaData()
meta.bind = migrate_engine
alarm = Table('alarm', meta, autoload=True)
alarm.c.counter_name.alter(name='meter_name')
def downgrade(migrate_engine):
meta = MetaData()
meta.bind = migrate_engine
alarm = T... |
from __future__ import unicode_literals
import re
import json
from .common import InfoExtractor
from ..compat import (
compat_str,
compat_urllib_parse,
compat_urllib_request,
)
from ..utils import (
ExtractorError,
clean_html,
int_or_none,
)
class LyndaBaseIE(InfoExtractor):
_LOGIN_URL =... |
CORE = "CORE"
DUMMY = "DUMMY"
LOADBALANCER = "LOADBALANCER"
LOADBALANCERV2 = "LOADBALANCERV2"
FIREWALL = "FIREWALL"
VPN = "VPN"
METERING = "METERING"
L3_ROUTER_NAT = "L3_ROUTER_NAT"
# Maps extension alias to service type
EXT_TO_SERVICE_MAPPING = {
'dummy': DUMMY,
'lbaas': LOADBALANCER,
'lbaasv2': LOADBALA... |
#!/usr/bin/env python
import numpy as np
import random
import copy
from collections import defaultdict
import matplotlib.pyplot as plt
from scipy.optimize import minimize
from scipy.optimize import minimize_scalar
import os
import sys
from util import load_psm
from scipy.ndimage.filters import convolve
from scipy.ndim... |
"""Return or yield the prime factors of an integer.
The ``factors(n)`` generator yields distinct prime factors and the
number of times they are repeated:
>>> list(factors(37*37*109))
[(37, 2), (109, 1)]
The ``factorise(n)`` function returns a list of prime factors:
>>> factorise(37*37*109)
[37, 37, 109]
To get a ... |
"""A typed list in Python."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensorflow.python.framework import ops
from tensorflow.python.ops import list_ops
from tensorflow.python.ops import tensor_array_ops
def dynamic_list_append(target, element... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import print_function
import importlib
import os
try:
from cached_property import cached_property as cached
except ImportError:
from .utils import cached
from .module_walk import ModuleWalk
class NoValidationError:
pass
cl... |
# coding: utf-8
import os, sys; sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", ".."))
# By default, parse() uses part-of-speech tags from the Penn Treebank tagset:
# http://www.clips.ua.ac.be/pages/penn-treebank-tagset
# It is a good idea to study the tagset and its abbreviations for a few minutes.
... |
# -*- coding: utf-8 -*-
"""
***************************************************************************
QtSql.py
---------------------
Date : March 2016
Copyright : (C) 2016 by Juergen E. Fischer
Email : jef at norbit dot de
********************************... |
"""
GravMag: Use the polynomial equivalent layer to upward continue gravity data
"""
from fatiando.gravmag import prism, sphere
from fatiando.gravmag.eqlayer import PELGravity, PELSmoothness
from fatiando import gridder, utils, mesher
from fatiando.vis import mpl
# Make synthetic data
props = {'density': 1000}
model =... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import json
from sys import version as python_version
from ansible.errors import AnsibleError
from ansible.module_utils.urls import open_url
from ansible.plugins.inventory import BaseInventoryPlugin
from ansible.module_utils._te... |
"""
This module contains all general use signals.
"""
from django.dispatch import Signal
# Signal that fires when a user is graded
COURSE_GRADE_CHANGED = Signal(providing_args=["user", "course_grade", "course_key", "deadline"])
# Signal that fires when a user is awarded a certificate in a course (in the certificate... |
from __future__ import division, absolute_import, print_function
import os
from numpy.distutils.fcompiler import FCompiler
compilers = ['LaheyFCompiler']
class LaheyFCompiler(FCompiler):
compiler_type = 'lahey'
description = 'Lahey/Fujitsu Fortran 95 Compiler'
version_pattern = r'Lahey/Fujitsu Fortran... |
import contextlib
import imp
import importlib
import sys
import unittest
@contextlib.contextmanager
def uncache(*names):
"""Uncache a module from sys.modules.
A basic sanity check is performed to prevent uncaching modules that either
cannot/shouldn't be uncached.
"""
for name in names:
i... |
"""Tests for crypto and hashing."""
__author__ = 'Mike Gainer (<EMAIL>)'
import re
import actions
from common import crypto
URLSAFE_B64_ALPHABET = re.compile('^[a-zA-Z0-9-_=]+$')
class EncryptionManagerTests(actions.TestBase):
def test_hmac_is_consistent(self):
message = 'Mary had a little lamb. He... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from bashlint import bast, errors
def gatherheredocuments(tokenizer):
# if we're at the end of the input and we're not strict, allow skipping
# reading the heredoc
while tokenizer.redirstack:
... |
"""Module with Classes to handle statistics."""
import time
from abc import ABCMeta, abstractmethod
from pathlib import Path
import rrdtool
from kytos.core import KytosEvent, log
from napps.legacy.of_core.flow import Flow
from pyof.v0x01.common.phy_port import Port
from pyof.v0x01.controller2switch.common import (Aggr... |
# 各組分別在各自的 .py 程式中建立應用程式 (第1步/總共3步)
from flask import Blueprint, render_template, make_response
# 利用 Blueprint建立 ag1, 並且 url 前綴為 /ag1, 並設定 template 存放目錄
ag8_40323123 = Blueprint('ag8_40323123', __name__, url_prefix='/ag8_40323123', template_folder='templates')
# scrum1_task1 為完整可以單獨執行的繪圖程式
@ag8_40323123.route('/task1... |
from nova.virt.baremetal import baremetal_states
class NodeDriver(object):
def __init__(self, virtapi):
self.virtapi = virtapi
def cache_images(self, context, node, instance, **kwargs):
raise NotImplementedError()
def destroy_images(self, context, node, instance):
raise NotImple... |
"""SCons.Tool.suncc
Tool-specific initialization for Sun Solaris (Forte) CC and cc.
There normally shouldn't be any need to import this module directly.
It will usually be imported through the generic SCons.Tool.Tool()
selection method.
"""
#
# Copyright (c) 2001 - 2015 The SCons Foundation
#
# Permission is hereby ... |
"""
Abstract GNU Radio publisher/subscriber interface
This is a proof of concept implementation, will likely change significantly.
"""
class pubsub(dict):
def __init__(self):
self._publishers = { }
self._subscribers = { }
self._proxies = { }
def __missing__(self, key, value=None):
dict.__setitem__(self, ... |
from openerp.osv import fields, osv
class product_template(osv.osv):
_inherit = "product.template"
def _bom_orders_count(self, cr, uid, ids, field_name, arg, context=None):
Bom = self.pool('mrp.bom')
res = {}
for product_tmpl_id in ids:
nb = Bom.search_count(cr, uid, [('pro... |
from __future__ import unicode_literals
import frappe
def get_notification_config():
return {
"for_doctype": {
"Scheduler Log": {"seen": 0},
"Communication": {"status": "Open"}
},
"for_module_doctypes": {
"ToDo": "To Do",
"Event": "Calendar",
"Comment": "Messages"
},
"for_module": {
"To Do... |
from __future__ import absolute_import
import os
import sys
import six
import getpass
from impala.util import get_logger_and_init_null
log = get_logger_and_init_null(__name__)
if six.PY2:
# pylint: disable=import-error,unused-import
# import Apache Thrift code
from thrift.transport.TSocket import TSoc... |
import glob
import os.path
import struct
# from PIL import Image
import PIL.Image
import ImageTk
import ImageEnhance
import ImageFilter
import sys
from wif import towif
im = None ### avoid "NameError: global name 'im' is not defined" error
from Tkinter import *
import tkFileDialog
file_opt={}
FILENAM... |
from pygaze.py3compat import *
from pygaze import settings
from pygaze._misc.misc import copy_docstr
from pygaze._joystick.basejoystick import BaseJoystick
class Joystick(BaseJoystick):
# see BaseJoystick
def __init__(self, disptype=settings.DISPTYPE, **args):
# see BaseJoystick
... |
"""
Certificate tool in the student support app.
"""
from django.views.generic import View
from django.utils.decorators import method_decorator
from edxmako.shortcuts import render_to_response
from support.decorators import require_support_permission
class CertificatesSupportView(View):
"""
View for viewing ... |
#!/usr/bin/env python
from nose.tools import *
import networkx as nx
class TestDFS:
def setUp(self):
# simple graph
G=nx.Graph()
G.add_edges_from([(0,1),(1,2),(1,3),(2,4),(3,4)])
self.G=G
# simple graph, disconnected
D=nx.Graph()
D.add_edges_from([(0,1),(2,3... |
"""
Script to generate the MNIST+ dataset. The purpose of this dataset is to make a
more challenging MNIST-like dataset, with multiple factors of variation. These
factors can serve to evaluate a model's performance at learning invariant
features, or its ability to disentangle factors of variation in a multi-task
classi... |
"""User friendly container for Google Cloud Bigtable Column Family."""
from google.cloud import _helpers
from google.cloud.bigtable_admin_v2.types import table as table_v2_pb2
from google.cloud.bigtable_admin_v2.types import (
bigtable_table_admin as table_admin_v2_pb2,
)
class GarbageCollectionRule(object):
... |
RGB_PATTERN = r"^\s*rgb\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*\)\s*$"
RGB_PCT_PATTERN = r"^\s*rgb\(\s*(\d{1,3}|\d{1,2}\.\d+)%\s*,\s*(\d{1,3}|\d{1,2}\.\d+)%\s*,\s*(\d{1,3}|\d{1,2}\.\d+)%\s*\)\s*$"
RGBA_PATTERN = r"^\s*rgba\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(0|1|0\.\d+)\s*\)\s*$"
RGBA_PCT_PATT... |
import rwx
import unittest
class RwxTest(unittest.TestCase):
def test_file_type(self):
self.assertEquals("dir", rwx.filetype(040330))
self.assertEquals("file", rwx.filetype(0100770))
self.assertEquals("link", rwx.filetype(0120000))
self.assertEquals("unknown", rwx.filetype(0))
def test_expand_mo... |
"""Adds the functionally of alerted of prodlots expiration"""
import stock_production_lot
import stock_move |
from django.conf.urls import patterns, url
from . import views
urlpatterns = [
# default -> public stream
url(r'^$', views.public_stream, name='public_stream'),
url(r'^myStream/$', views.my_stream, name='my_stream'),
url(r'^post/(?P<post_pk>[^/]+)/$', views.post_detail, name="post_detail"),
url(r'^... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.