content string |
|---|
#################################################################
# Program: Toolib
"""
Grid model.
Extension of PyGridTableBase, defines listener support and helper methods to generate evenrs.
You can add Grids as listeners to notify them about table changes.
def addGridTableListener(self, l): \ registers wx.gr... |
from __future__ import absolute_import
from collections import MutableMapping
# http://code.activestate.com/recipes/576972-attrdict/
class AttrDict(MutableMapping):
"""Dict-like object that can be accessed by attributes
>>> obj = AttrDict()
>>> obj['test'] = 'hi'
>>> print obj.test
hi
>>> d... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
from datetime import datetime, date, timedelta
from dateutil import relativedelta as rdelta
import json
import random
ages = {}
timeline = {}
d = date(2014, 7, 22)
while d < date(2014, 9, 9):
timeline[d] = {
'day': d.day,
'month': d.month,
'sum':... |
import json
import demistomock as demisto
from SearchIndicators import search_indicators
json_raw_data = '''[
{
"Contents": [
{
"CustomFields": {
"actor": "random",
"description": "Malware available for download from file-sharing sites",... |
# coding: utf-8
# ### Amazon Sentiment Data
# In[ ]:
import lxmls.readers.sentiment_reader as srs
from lxmls.deep_learning.utils import AmazonData
corpus = srs.SentimentCorpus("books")
data = AmazonData(corpus=corpus)
# ### Implement Pytorch Forward pass
# As the final exercise today implement the log `forward()... |
from collections import defaultdict
from ldap.cidict import cidict
from .ldapobject import LDAPObject
from .recording import SeedRequired # noqa
URI_DEFAULT = '__default__'
class MockLdap(object):
"""
Top-level class managing directories and patches.
:param directory: Default directory contents.
... |
"""The nexia integration base entity."""
from homeassistant.const import ATTR_ATTRIBUTION
from homeassistant.helpers.dispatcher import async_dispatcher_connect
from homeassistant.helpers.update_coordinator import CoordinatorEntity
from .const import (
ATTRIBUTION,
DOMAIN,
MANUFACTURER,
SIGNAL_THERMOST... |
__author__ = 'yfauser'
import httplib
import urllib
import argparse
import logging
import sys
import time
class Notifier:
def __init__(self, user=None, token=None, debug=False):
"""
Notifier Object
:param user: The user key as generated when registering to Pushover service
:param t... |
#
# Write filename to Celery queue for batching and parallel processing
#
from tasks import index_file
class export_queue_files(object):
def __init__(self, config=None):
if config is None:
config = {'verbose': False}
self.config = config
def process(self, parameters=None, data=N... |
import tempfile
import h5py
import numpy as np
from pyscf import lib
#einsum = np.einsum
einsum = lib.einsum
# Ref: Gauss and Stanton, J. Chem. Phys. 103, 3561 (1995) Table III
# Section (a)
def make_tau(t2, t1a, t1b, fac=1, out=None):
tmp = einsum('ia,jb->ijab',t1a,t1b)
t1t1 = tmp - tmp.transpose(1,0,2,3) ... |
from __future__ import unicode_literals
from decimal import Decimal
import re
from weboob.browser.pages import LoggedPage, JsonPage, HTMLPage, RawPage
from weboob.browser.elements import ItemElement, DictElement, method
from weboob.browser.filters.standard import (
Date, Eval, Env, CleanText, Field, CleanDecimal,... |
import web
import ldap
import settings
from libs.ldaplib import attrs
session = web.config.get('_session')
class LDAPWrap:
def __init__(self, app=web.app, session=session,):
# Get LDAP settings.
self.basedn = settings.ldap_basedn
self.domainadmin_dn = settings.ldap_domainadmin_dn
... |
##Background eliminator
import cv2
import numpy as np
def nothing(x):
pass
def unit_vector(vector):
return np.array(vector / np.linalg.norm(vector),np.float32)
def angle_between(v1, v2 ,origin):
v1_u = unit_vector(v1-origin)
v2_u = unit_vector(v2-origin)
dot = np.dot(v1_u, v2_u)
angl... |
from rinde.property.animation import Animation
"""
Represents collection of properties with user-friendly interface.
"""
class Properties:
"""
Creates new collection of properties.
"""
def __init__(self):
self.__properties = {}
"""
Inserts new Property object to the collection.
"""
def create(self, name... |
#!/bin env python
import cyglfw3 as glfw
"""
Tow cyglfw3 application for use with "hello world" examples demonstrating pyopenvr
"""
class CyGLFW3App(object):
"""
Uses the glfw library via the cyglfw3 bindings to create an opengl context, listen to keyboard
and VR HMD/controller events, and clean up
"... |
# -*- coding: utf-8 -*-
# Scrapy settings for scraper project
#
# For simplicity, this file contains only settings considered important or
# commonly used. You can find more settings consulting the documentation:
#
# http://doc.scrapy.org/en/latest/topics/settings.html
# http://scrapy.readthedocs.org/en/latest... |
"""Extended Kalman filtering / smoothing module.
TODO
----
* Make docstrings for all constructors.
Improvement ideas
-----------------
"""
import abc
import collections
import re
import attrdict
import numpy as np
import numpy.ma as ma
import numpy.linalg
from .. import utils
from . import base
class DTPredict... |
import mock
from odoo.addons.connector_carepoint.models import phone_physician
from ...unit.backend_adapter import CarepointCRUDAdapter
from ..common import SetUpCarepointBase
_file = 'odoo.addons.connector_carepoint.models.phone_physician'
class EndTestException(Exception):
pass
class PhonePhysicianTestBa... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import wagtail.wagtailsearch.index
def set_page_path_collation(apps, schema_editor):
"""
Treebeard's path comparison logic can fail on certain locales such as sk_SK, whic... |
import xapian
import operator
from copy import deepcopy
from django.db.models import get_model
from django.utils.encoding import force_unicode
from djapian import utils, decider
class ResultSet(object):
def __init__(self, indexer, query_str, offset=0, limit=utils.DEFAULT_MAX_RESULTS,
order_by=No... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Created on Wed Feb 24 18:39:45 2016
@author: Andrea Giovannucci
For explanation consult at https://github.com/agiovann/Constrained_NMF/releases/download/v0.4-alpha/Patch_demo.zip
and https://github.com/agiovann/Constrained_NMF
"""
from __future__ import division
fr... |
from msrest.serialization import Model
class SentimentBatchResult(Model):
"""SentimentBatchResult.
Variables are only populated by the server, and will be ignored when
sending a request.
:ivar documents: Response by document
:vartype documents:
list[~azure.cognitiveservices.language.textana... |
from typing import Any, Callable, Dict, Generic, Optional, TypeVar
import warnings
from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import AsyncHttpRe... |
try:
import PyInstaller
except ImportError:
# if importing PyInstaller fails, try to load from parent
# directory to support running without installation
import imp, os
if not hasattr(os, "getuid") or os.getuid() != 0:
imp.load_module('PyInstaller', *imp.find_module('PyInstaller',
... |
""" Callbacks that handle comment functionality.
"""
from dash.dependencies import ALL, MATCH, Input, Output, State
from .. import id_constants, state
from ..dash_app import app
@app.callback(
# We can't use ALL in the output, so we use MATCH.
# However, since there's only one component with this key, the ... |
"""
Default Mode Network extraction of AHDH dataset
===============================================
Full step-by-step example of fitting a GLM to a seed extract on the
Posterior Cingulate Cortex data and saving the results.
More specifically:
1. A sequence of fMRI volumes are loaded
2. A design matrix with the Poste... |
import dis
_const_codes = map(dis.opmap.__getitem__, [
'POP_TOP',
'ROT_TWO',
'ROT_THREE',
'ROT_FOUR',
'DUP_TOP',
'BUILD_LIST',
'BUILD_MAP',
'BUILD_TUPLE',
'LOAD_CONST',
'RETURN_VALUE',
'STORE_SUBSCR',
])
_expr_codes = _const_codes + map(dis.opmap.__getitem__, [
'UNA... |
#!/usr/bin/env python
from pathlib import Path
from argparse import ArgumentParser
import typing as T
import shutil
import python_performance as pb
try:
from matplotlib.pyplot import figure, show
except ImportError:
figure = show = None
bdir = Path(__file__).parent / "matmul"
cdir = Path(__file__).parent / "... |
#!/usr/bin/env python
# coding=UTF-8
import rospy
import rosbag
import argparse
import tf2_msgs.msg
import geometry_msgs.msg
def add_tf(inbag_filename, outbag_filename, source_frame, target_frame, position, rotation, time_increment):
print ' Processing input bagfile: %s' % (inbag_filename)
print ' ... |
'''
vidzi urlresolver plugin
Copyright (C) 2014 Eldorado
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 distr... |
import numpy as np
import scipy.sparse as sp
import pySDC.helpers.transfer_helper as th
from pySDC.core.Errors import TransferError
from pySDC.core.SpaceTransfer import space_transfer
from pySDC.implementations.datatype_classes.mesh import mesh, imex_mesh, comp2_mesh
class mesh_to_mesh(space_transfer):
"""
C... |
# -*- coding: utf-8 -*-
from __future__ import print_function, absolute_import
import logging
from gi.repository import Gtk, Notify, GLib
from gi.repository import AppIndicator3 as appindicator
from avashell.utils import resource_path
from ava.user import status
from ..base import *
from . import msgbox
_logger = l... |
from utilities import CandidateSelection,DataClean
from utilities import load_data,cross_validate
from sklearn.pipeline import Pipeline
from keyword_metrics import keyword_prf,keyword_prf_onegram
from nltk.stem import PorterStemmer
from itertools import takewhile, tee, izip
import networkx, nltk
class TextRank_Keyword... |
import re
import math
import operator
import collections
import itertools
from django.core import urlresolvers
from django.core.exceptions import PermissionDenied
import pymongo
from billy.utils import parse_param_dt, fix_bill_id
from billy.core import mdb as db, settings
from .base import (Document, RelatedDocument,... |
from django.shortcuts import render
from django.db.models import Count
from django.core import serializers
from django.http import HttpResponse
from photo.models import Photo
def index(request):
categories = Photo.objects.raw('select id, category from swan_photo group by category')
subcategories = Photo.object... |
from incload import downloader
from incload.parsers import baseparser
import urllib
class FullAlphabeticalParser(baseparser.BaseParser):
Source="http://freepd.com"
def __init__(self):
baseparser.BaseParser.__init__(self)
self.__DetectionLevel=0
self.__Genres={}
self.__Results={}
self... |
"""
alogger-ng utils
"""
import re
def print_error(line_no, message):
"""
Method called when error occurs
"""
print 'Line: %s --- %s' % (line_no, message)
def get_in_seconds(time):
"""
Takes a string in format HH:MM:SS
Note hours can be more than 2 digits
if greater than 3 years... |
class Solution:
# dfs
# time: O(m * n)
# space: O(m * n)
def numIslands(self, grid):
"""
:type grid: List[List[str]]
:rtype: int
"""
def dfs(i, j, m, n):
visited.add((i, j))
directions = [(1, 0), (-1, 0), (0, 1), (0, -1)]
for d ... |
__author__ = 'buec'
class Grammar:
def __init__(self, name="", language="en-US", encoding=""):
self.name = name
self.language = language
self.encoding = encoding
self.rules = []
self.root_rule = None
def add_rule(self, rule):
if self.contains_rule_with_name(rul... |
from __future__ import print_function
import argparse
import copy
import six
import sys
from glanceclient.common import progressbar
from glanceclient.common import utils
from glanceclient import exc
from glanceclient.openstack.common import strutils
import glanceclient.v1.images
CONTAINER_FORMATS = 'Acceptable forma... |
from ehb_datasources.drivers.Base import Driver, RequestHandler
from ehb_datasources.drivers.exceptions import RecordCreationError, \
IgnoreEhbExceptions
class PhenotypeDriver(Driver, RequestHandler):
def __init__(self, url, user, password, secure):
def getHost(url):
return url.split('/')... |
# encoding: utf-8
# module gtk._gtk
# from /usr/lib/python2.7/dist-packages/gtk-2.0/gtk/_gtk.so
# by generator 1.135
# no doc
# imports
import atk as __atk
import gio as __gio
import gobject as __gobject
import gobject._gobject as __gobject__gobject
class EntryBuffer(__gobject__gobject.GObject):
"""
Object G... |
import array
import logging
import os
import subprocess
import numpy as np
import scipy.sparse as sp
from tqdm import tqdm
from mtest.utils.data import load_csr, save_csr
logger = logging.getLogger(__name__)
def libsvm_to_csr(path):
with open(path) as f_in:
num_documents, num_features, num_labels = [... |
import datetime
import random
#import matplotlib.pyplot as plt
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import matplotlib.ticker
import sys
import time
import os
args = sys.argv[1:]
if len(args) > 0:
with open(args[0],"r") as f:
# make up some data
... |
import pytest
import math
import time
import numpy as np
import numpy.linalg as la
from pyctrl.block.clock import Clock, TimerClock
from pyctrl.block import Map, Constant, Logger
from pyctrl.block.system import TimeVaryingSystem
test_ode = True
try:
from pyctrl.system.ode import ODE, ODEINT
except:
test_ode ... |
import test.helpers as helpers
import nose.tools as nt
import mallet.input.tgf_parser as tgf
import mallet.sequence as seq
import mallet.viterbi as viterbi
class TestViterbi(object):
def subject(self, hmm_filename, sequence):
return viterbi.viterbi(tgf.parse("test/files/tgf/{}".format(hmm_filename)), se... |
#!/bin/python2.7
"""
A tool to insert institutions from CSV files.
Requirements:
- requests
- gusregon
- unicodecsv
- jmespath
Example usage:
To run help text use:
$ python insert_institution_csv.py -h
"""
import argparse
import sys
import itertools
from Queue import Queue
import jmespath
import requests
impo... |
from django.test import TestCase, RequestFactory
from bambu_analytics import track_event, events
class AnalyticsTrackingTestCase(TestCase):
def setUp(self):
self.factory = RequestFactory()
def test_track_page(self):
request = self.factory.get('/')
track_event(request, events.PAGE)
... |
import functools, ptypes
from ptypes import *
# little-endian
intofdata = lambda data: functools.reduce(lambda t, c: t * 256 | c, map(ord, reversed(data)), 0)
_dataofint = lambda integer: ((integer == 0) and b'\0') or (_dataofint(integer // 256).lstrip(b'\0') + chr(integer % 256))
dataofint = lambda integer, le=_datao... |
from novaclient import exceptions as nova_exceptions
from oslo_log import log as logging
from trove.backup.models import Backup
import trove.common.apischema as apischema
from trove.common.auth import admin_context
from trove.common import exception
from trove.common.i18n import _
from trove.common import wsgi
from tr... |
""" Stacks all maxpixles in the given folder to one image. """
from __future__ import print_function, division, absolute_import
import os
import argparse
import numpy as np
import matplotlib.pyplot as plt
from RMS.Formats.FFfile import read as readFF
from RMS.Formats.FFfile import validFFName
from RMS.Routines.Imag... |
import exceptions
import clientPackets
import glob
import Rohwabot
import consoleHelper
import bcolors
import serverPackets
def handle(userToken, packetData):
"""
Event called when someone sends a public message
userToken -- request user token
packetData -- request data bytes
"""
try:
# Get uesrToken data
... |
__version__='3.3.0'
__doc__='''Classes for ParagraphStyle and similar things.
A style is a collection of attributes, but with some extra features
to allow 'inheritance' from a parent, and to ensure nobody makes
changes after construction.
ParagraphStyle shows all the attributes available for formatting
paragr... |
"""This script wraps gyp and sets up build environments.
Build instructions:
1. Setup gyp: ./gyp_packager.py or use gclient runhooks
clang is enabled by default, which can be disabled by overriding
GYP_DEFINE environment variable, i.e.
"GYP_DEFINES='clang=0' gclient runhooks".
Ninja is the default build system. Use... |
from __future__ import with_statement
import rospy
import traceback
import threading
from threading import Timer
import sys, os, time
from time import sleep
import subprocess
import socket
from diagnostic_msgs.msg import DiagnosticArray, DiagnosticStatus, KeyValue
hdd_level_warn = 0.95
hdd_level_error = 0.99
hdd_t... |
from networking_cisco.plugins.ml2.drivers.cisco.n1kv import (
exceptions as n1kv_exc)
from networking_cisco.plugins.ml2.drivers.cisco.n1kv import (
n1kv_db)
from networking_cisco.plugins.ml2.drivers.cisco.n1kv import (
policy_profile_service)
import neutron.db.api as db
from test_cisco_n1kv_mech import Te... |
# -*- coding: utf-8 -*-
import requests
import json
class Graph:
graph_api_url = 'https://graph.facebook.com/v2.2'
def __init__(self, token):
self._token = token
def _url(self, path):
return self.graph_api_url + path
def post(self, path, data):
url = self._url(path)
... |
import struct
import pytest
import subprocess
from diffoscope.comparators.cbfs import CbfsFile
from diffoscope.comparators.binary import FilesystemFile
from diffoscope.comparators.utils.specialize import specialize
from ..utils.data import data, get_data
from ..utils.tools import skip_unless_tools_exist
from ..utils.... |
"""Handles mouse tracking/drawing"""
from . import libtcodpy as libtcod
from .game import Game
class Mouse(object):
def __init__(self, mouse):
self.mouse = mouse
self.draw_x = None
self.draw_y = None
self.abs_x = None
self.abs_y = None
def update_coords(self):
... |
import os
from PyQt4 import QtCore, QtGui
class ZoomWidget(QtGui.QLabel):
def __init__(self, useData, editor, parent=None):
QtGui.QLabel.__init__(self, parent=None)
self.useData = useData
self.editor = editor
self.prevValue = 0
self.setMinimumHeight(130)
self.set... |
"""
Exception definitions.
"""
import inspect
import sys
from muranoclient.i18n import _
class ClientException(Exception):
"""The base exception class for all exceptions this library raises."""
pass
class MissingArgs(ClientException):
"""Supplied arguments are not sufficient for calling a function."""... |
from oslo_config import cfg
from oslo_utils import importutils
_compute_opts = [
cfg.StrOpt('network_api_class',
default='conveyor.network.neutron.API',
help='The full class name of the '
'network API class to use'),
]
cfg.CONF.register_opts(_compute_opts)
def A... |
"""Heat API exception subclasses - maps API response errors to AWS Errors"""
import webob.exc
from heat.common import wsgi
from heat.openstack.common.gettextutils import _
from heat.openstack.common.rpc import common as rpc_common
class HeatAPIException(webob.exc.HTTPError):
'''
Subclass webob HTTPError so ... |
# -*- coding: utf-8 -*-
from south.utils import datetime_utils as 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 'AuditEntry.is_authorized'
db.add_column('auditlog_auditen... |
"""
util tests
"""
import os
import stat
import sys
import shutil
import tempfile
import pytest
from mock import Mock, patch
from pip.exceptions import BadCommand
from pip.util import (egg_link_path, Inf, get_installed_distributions,
find_command, untar_file, unzip_file)
from pip.commands.freez... |
from binascii import unhexlify
from cryptography.exceptions import InvalidSignature
from torba.testcase import AsyncioTestCase
from torba.client.constants import CENT, NULL_HASH32
from lbry.wallet.ledger import MainNetLedger
from lbry.wallet.transaction import Transaction, Input, Output
from lbry.schema.claim impor... |
import re
from typing import Any, Dict, List, Mapping, Optional
import markdown
from markdown.extensions import Extension
from markdown.preprocessors import Preprocessor
from zerver.openapi.openapi import get_openapi_return_values
REGEXP = re.compile(r'\{generate_return_values_table\|\s*(.+?)\s*\|\s*(.+)\s*\}')
cl... |
"""
Django settings for BRB project.
Generated by 'django-admin startproject' using Django 1.10.
For more information on this file, see
https://docs.djangoproject.com/en/1.10/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.10/ref/settings/
"""
import os
# Bu... |
"""Train the network."""
import caffe
from timer import Timer
import numpy as np
import os
from caffe.proto import caffe_pb2
import google.protobuf as pb2
import sys
import config
import _init_paths
class SolverWrapper(object):
"""A simple wrapper around Caffe's solver.
"""
def __init__(self, solver_prot... |
from Heap.BinomialHeapNode import BinomialHeapNode
class BinomialHeap:
def __init__(self, elem, key):
self.root = BinomialHeapNode(elem, key)
def merge(self, heap_to_merge):
this_root = self.root
to_merge_root = heap_to_merge.root
if this_root.key <= to_merge_root.key:
... |
'''
Created on May 20, 2011
@author: Mark V Systems Limited
(c) Copyright 2011 Mark V Systems Limited, All rights reserved.
based on http://www.hmrc.gov.uk/ebu/ct_techpack/joint-filing-validation-checks.pdf
Deprecated Nov 15, 2015. Use plugin/validate/HMRC/__init__.py
'''
import xml.dom, xml.parsers
import os, re,... |
"""This module is deprecated. Please use :mod:`airflow.providers.amazon.aws.sensors.sqs`."""
import warnings
# pylint: disable=unused-import
from airflow.providers.amazon.aws.sensors.sqs import SQSSensor # noqa
warnings.warn(
"This module is deprecated. Please use `airflow.providers.amazon.aws.sensors.sqs`.",
... |
from typing import TYPE_CHECKING
import warnings
from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import HttpRequest, HttpResponse
from azure.mgmt.cor... |
from __future__ import unicode_literals
from ..filters import CLIFilter, to_cli_filter, Never
from ..utils import Callback
from collections import defaultdict
__all__ = (
'Registry',
)
class _Binding(object):
"""
(Immutable binding class.)
"""
def __init__(self, keys, handler, filter=None, eager... |
#!/usr/bin/env
import numpy as np
import cv2, csv, os, re, sys, time, argparse, datetime
'''
started 25 August 2015
31 August 2015:
modifying script so that it queries frames from a video taken with ffmpeg
typical useage:
-- run this script at the beginning of a 10 minute acclimation period (this time can be change... |
"""Tests for utilities in offline_eval_map_corloc binary."""
import tensorflow.compat.v1 as tf
from object_detection.metrics import offline_eval_map_corloc as offline_eval
class OfflineEvalMapCorlocTest(tf.test.TestCase):
def test_generateShardedFilenames(self):
test_filename = '/path/to/file'
result = o... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Message Bus Python SDK
"""
"""
Copyright 2014 Message Bus
Licensed 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
http://www.apache.org/lice... |
from subprocess import *
from time import sleep
from timeit import default_timer as clock
from tempfile import TemporaryFile
#from Queue import Queue
from collections import deque
from Tester import Tester
from signal import SIGTERM
import platform
import os, sys
## This class provides an interface to run commands i... |
from pypers.core.step import CmdLineStep
class FilterSamplesFromOTUTable(CmdLineStep):
spec = {
"version": "2015.05.13",
"descr": [
"Filters samples from an OTU table",
"Currently we implement only filter on --min_count, ie minimum total observations"
],
"url... |
from rbuild import errors
from rbuild_plugins.build import groups
def createRmakeJobForPackages(handle, packageList, recurse=True):
return _createRmakeJobForPackages(handle, packageList, recurse)
def createRmakeJobForAllPackages(handle):
"""
Builds a job that could possibly build all packages that are def... |
import cabbagerc
import discord
from discord.ext import commands
from phrasebook.Phrasebook import Phrasebook
from datetime import datetime
cabbageNumber = 2
cabbageStealer = 0
cabbageTheftTime = 0
description = '''Bot That Performs Cabbage-Related Functions'''
bot = commands.Bot(command_prefix=cabbagerc.PREF, descri... |
"""Defines style error handler classes.
A style error handler is a function to call when a style error is
found. Style error handlers can also have state. A class that represents
a style error handler should implement the following methods.
Methods:
__call__(self, line_number, category, confidence, message):
... |
"""NOEtools: For predicting NOE coordinates from assignment data.
The input and output are modelled on nmrview peaklists.
This modules is suitable for directly generating an nmrview
peaklist with predicted crosspeaks directly from the
input assignment peaklist.
"""
from . import xpktools
def predictNOE(peaklist, or... |
import unittest
from rx import Observable
from rx.testing import TestScheduler, ReactiveTest, is_prime, MockDisposable
from rx.disposables import Disposable, SerialDisposable
on_next = ReactiveTest.on_next
on_completed = ReactiveTest.on_completed
on_error = ReactiveTest.on_error
subscribe = ReactiveTest.subscribe
sub... |
"""Tests for pad.plugins.uri_detail plugin"""
import collections
import unittest
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
try:
from unittest.mock import patch, MagicMock, Mock, call
except ImportError:
from mock import patch, MagicMock, Mock, call
import oa.context... |
#!/usr/bin/env python
import pickle
import sys
import event
from event import *
import pygraphviz as pgv
import copy
G = pgv.AGraph()
def default_object_handler(obj):
global G
class PyQemuDumpAnalyzer:
def __init__(self, filename):
self.dumpfile = open(filename,"rb")
def run(self):
while 1:
try:
obj =... |
import logging
import ezt
from google.appengine.ext import webapp
from google.appengine.ext.webapp import util
from mapreduce.api import map_job
from mapreduce import input_readers
import ezt_util
import models
import mapreduces
class MapReduceTriggerHandler(webapp.RequestHandler):
MR_SPECS = dict(
RANDOMIZE =... |
'''
Author: Eric P. Nichols
Date: Feb 8, 2008.
Board class.
Board data:
1=white, -1=black, 0=empty
first dim is column , 2nd is row:
pieces[1][7] is the square in column 2,
at the opposite end of the board in row 8.
Squares are stored and manipulated as (x,y) tuples.
x is the column, y ... |
from setuptools import find_packages, setup
with open("./README.rst") as f:
readme = f.read()
setup(
name="axe-selenium-python",
use_scm_version=True,
setup_requires=["setuptools_scm"],
description="Python library to integrate axe and selenium for web \
accessibility testing.",
... |
__author__ = 'erik'
import requests
import re
def add_zeros(number, digits):
number_str = str(number)
if number < 10:
for members in range(digits-1):
number_str = "0" + number_str
elif number < 100:
for members in range(digits-2):
number_str = "0" + number_str
... |
# -*- coding: utf-8 -*-
import sys, os, inspect
current_dir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
parent_dir = os.path.dirname(current_dir)
sys.path.append(parent_dir)
import MySQLdb
from django.utils.datastructures import MultiValueDictKeyError
from django.template import Reques... |
import sigrokdecode as srd
from .lists import *
class SamplerateError(Exception):
pass
class Decoder(srd.Decoder):
api_version = 3
id = 'ir_nec'
name = 'IR NEC'
longname = 'IR NEC'
desc = 'NEC infrared remote control protocol.'
license = 'gplv2+'
inputs = ['logic']
outputs = ['ir_n... |
from docutils.utils import new_document
from docutils.writers import html4css1
from docutils.core import publish_parts
import re
DEBUG = False
#DEBUG = True
IGNORE_ATTR = (
"start", "class", "frame", "rules",
)
IGNORE_TAGS = (
"div",
)
class CleanHTMLWriter(html4css1.Writer):
"""
This docutils writ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#librairies annexes
import httplib, urllib
import StringIO
import wave
import time
import pymedia.audio.sound as sound
import sys
#librairies liées au robot poppy
import pypot.primitive
import pypot.robot
class maryclient:
def __init__(self):
self.host = ... |
__all__ = ['maxpool', 'maxpool_back']
import os
import math
import numpy
import pycuda.gpuarray as gpuarray
import pycuda.autoinit
import pycuda.driver as cuda
from pycuda.compiler import SourceModule
from .utils import gpu_func
from .enums import MAX_BLOCK_SIZE, CUR_DIR, CACHE_DIR
mod = SourceModule(open(os.path.jo... |
import tennis
PLAYER1 = 0
PLAYER2 = 1
def test(actual, exp):
assert actual == exp, 'Expected: {}, Actual: {}'.format(exp, actual)
if __name__ == '__main__':
game = tennis.TennisGame(['Alice', 'Bob'])
test(game.score, 'love all')
game.point(PLAYER1)
test(game.scores[PLAYER1], 15)
test(game.s... |
from pyshell.register.loader.variable import VariableLoader
from pyshell.register.utils.addon import getOrCreateProfile
def _localGetAndInitCallerModule(profile=None):
profile_loader = getOrCreateProfile(VariableLoader, profile)
return profile_loader
def setVariableLoadPriority(value, profile=None):
loa... |
import os
import sys
from contextlib import contextmanager
from typing import Any, Dict, Iterator, List
from pylama.lint import Linter as BaseLinter # type: ignore
from isort.exceptions import FileSkipped
from . import api
@contextmanager
def supress_stdout() -> Iterator[None]:
stdout = sys.stdout
with op... |
from nutils import *
from . import register, unittest
@register( 'sin', function.sin, numpy.sin, [(3,)] )
@register( 'cos', function.cos, numpy.cos, [(3,)] )
@register( 'tan', function.tan, numpy.tan, [(3,)] )
@register( 'sqrt', function.sqrt, numpy.sqrt, [(3,)] )
@register( 'log', function.ln, numpy.log, [(3,)] )
@r... |
'''
Discretize the continuous hybridization function into a discretized model(DiscModel).
checking method is also provided.
'''
from numpy import *
from matplotlib.pyplot import *
from matplotlib import cm
from scipy.interpolate import InterpolatedUnivariateSpline,interp1d
from scipy.integrate import quadrature,cumtra... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.