content string |
|---|
"""
Template tags as workaround for a Django 1.11 bug in the multiwidget template.
"""
from django.template import Library, Node, TemplateSyntaxError
register = Library()
class WithDictNode(Node):
"""
Node to push a complete dict
"""
def __init__(self, nodelist, context_expr):
self.nodelist ... |
import operator
from enum import Enum, unique
import maya
# pylint: disable=invalid-name
@unique
class WeekDay(Enum):
Monday = 0
Tuesday = 1
Wednesday = 2
Thursday = 3
Friday = 4
Saturday = 5
Sunday = 6
_DAY_NAMES = {day.name.lower(): day for day in WeekDay}
_DAY_NAMES.update((day.name.... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import serial
import time
port = "/dev/ttyUSB0"
baud = 2400
parity = serial.PARITY_EVEN
bitlenght = serial.SEVENBITS
stopbits = serial.STOPBITS_TWO
ser = serial.Serial(port,
baudrate = baud,
bytesize = bitlenght,
... |
import os
import sys
from flask import request
from flask_security import current_user
from flask_restful_swagger import swagger
from manager_rest.deployment_update.constants import PHASES
from manager_rest import config
from manager_rest import manager_exceptions
from manager_rest import utils
from manager_rest.stor... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# This is very different to AboutModules in Ruby Koans
# Our AboutMultipleInheritance class is a little more comparable
#
from runner.koan import *
#
# Package hierarchy of Python Koans project:
#
# contemplate_koans.py
# koans/
# __init__.py
# about_asserts.py... |
from django.test import TestCase
from django.urls import reverse
from wagtail.core.models import Page
from wagtail.tests.utils import WagtailTestUtils
from tests.app.models import Author, Book
class TestAdminForm(WagtailTestUtils, TestCase):
def setUp(self):
super(TestAdminForm, self).setUp()
se... |
import numpy as np
import commands
import random
from parameter import *
HDT_CMD_INFO = 'hdtInfo'
HDT_CMD_HDT2RDF = 'hdt2rdf'
HDT_CMD_HDTSEARCH = 'hdtSearch'
HDT_CMD_SEARCH_HEADER = 'searchHeader'
HDT_CMD_RDF2HDT = 'rdf2hdt'
HDT_CMD_MODIFY_HEADER = 'modifyHeader'
HDT_CMD_REPLACE_HEADER = 'replaceHeader'
dirname='~/Ph... |
from __future__ import print_function
from beets.plugins import BeetsPlugin
from beets.ui import Subcommand
from beets import ui
from beets import config
import musicbrainzngs
import re
import logging
SUBMISSION_CHUNK_SIZE = 200
UUID_REGEX = r'^[a-f0-9]{8}(-[a-f0-9]{4}){3}-[a-f0-9]{12}$'
log = logging.getLogger('be... |
#!/usr/bin/env python
# # MoodCube: plot Moods
# ### take some data and display a 2D Surface plot
# Library Imports and Python parameter settings
from __future__ import division
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
# Update the matplotlib configuration parame... |
#!usr/bin/env python
import sys
import os
import yt
yt.mylog.setLevel("INFO")
import synchrotron.yt_synchrotron_emissivity as sync
from itertools import chain
yt.enable_parallelism(suppress_logging=True)
dir = './data/'
ptype = 'lobe'
proj_axis = 'x'
#proj_axis = [1,0,2]
extend_cells = 8
try:
ind = int(sys.argv[... |
"""Utilities used by insteon component."""
import logging
from insteonplm.devices import ALDBStatus
from homeassistant.const import CONF_ADDRESS, CONF_ENTITY_ID, ENTITY_MATCH_ALL
from homeassistant.core import callback
from homeassistant.helpers import discovery
from homeassistant.helpers.dispatcher import dispatche... |
# -*- coding: utf-8 -*-
import httplib
import requests
import logging
from requests import Session
from contextlib import closing
from soya.utils import SingletonMixin
from soya.utils.exc import (
UpperServiceException,
)
from soya.settings import (
API_KEY,
API_URI,
API_VERSION,
OUTPUT_JSON_FO... |
from typing import NamedTuple
from typing import Optional
from .rates import get_tariff_rates
class Charge(NamedTuple):
""" Represents a charge """
units: Optional[float]
unit_rate: Optional[float]
cost_excl_gst: float
gst: float
cost_incl_gst: float
def __repr__(self) -> s... |
from __future__ import print_function
import math
import numpy as np
import unittest
from op_test import OpTest
import paddle
import paddle.fluid as fluid
from paddle.fluid import core
class TestUnfoldOp(OpTest):
"""
This is for test on unfold Op
"""
def init_data(self):
self.batch_size = 3
... |
__author__ = 'Bohdan Mushkevych'
import gc
from synergy.conf import context
from synergy.db.model import unit_of_work
from synergy.db.manager import ds_manager
from synergy.workers.abstract_uow_aware_worker import AbstractUowAwareWorker
class AbstractMongoWorker(AbstractUowAwareWorker):
""" Abstract class is in... |
from CIM15.IEC61970.Core.IdentifiedObject import IdentifiedObject
class ModelingAuthority(IdentifiedObject):
"""A Modeling Authority is an entity responsible for supplying and maintaining the data defining a specific set of objects in a network model.A Modeling Authority is an entity responsible for supplying and ... |
"""
Misc commands tester
"""
import agent_test
import agentlib
import commands
import plugins.jsonparser
import logging
if __name__ == "__main__":
logging.basicConfig(level=logging.CRITICAL)
class TestJsonParser(agent_test.TestCase):
def setUp(self):
super(TestJsonParser, self).setUp()
sel... |
from django.template import RequestContext
from django.http import HttpResponse, HttpResponseRedirect
from django.contrib.auth.decorators import login_required
from django.shortcuts import render_to_response
from datetime import datetime, date, timedelta
from chambres.models import Chambre, Souci, Client, Reservation,... |
import os
import IMP
import IMP.em
import IMP.test
import IMP.core
class Tests(IMP.test.TestCase):
"""Class to test EM correlation restraint"""
def test_origin_spacing_data_is_kept_in_mrc_format1(self):
scene = IMP.em.read_map(self.get_input_file_name("in.mrc"), self.mrw)
scene.set_origin(-1... |
import Proc
import time
class SMR (Proc.Proc):
NONE = 0
LCONN = 1
MASTER = 2
SLAVE = 3
def __init__(self, pgs):
super(SMR, self).__init__(3)
self.pgs = pgs
def start(self, args, sin=None, sout=None, serr=None):
super(SMR, self).start(args, sin, sout, serr)
self... |
"""Collects and reports container and host metrics.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import errno
import io
import logging
import os
import time
import six
from treadmill import cgroups
from tread... |
'''
Module consists of code used to dynamically execute methods.
'''
#--REGULAR IMPORTS-------------------------------------------------------------
from time import sleep
from inspect import isfunction
from copy import copy
from sys import stdout
import types, code
from traceback import print_exc, print_tb
#... |
from GangaCore.GPIDev.Lib.Dataset import Dataset
from GangaCore.GPIDev.Schema import *
# Test Dataset
class TestDataset(Dataset):
_schema = Schema(Version(1,0), {'files':FileItem(defvalue="",sequence=1)})
_category = 'datasets'
_name = "TestDataset"
def __init__(self):
super(TestDataset, self... |
import time
from fabric.api import run, execute, env
environment = "production"
env.use_ssh_config = True
env.hosts = ["konklone.com"]
branch = "master"
repo = "<EMAIL>:konklone/konklone.com.git"
keep = 3
socket = "konklone"
home = "/home/eric/konklone.com"
shared_path = "%s/shared" % home
versions_path = "%s/vers... |
"""
Certificate end-points used by the student support UI.
See lms/djangoapps/support for more details.
"""
import logging
import urllib
from functools import wraps
from django.http import (
HttpResponse,
HttpResponseBadRequest,
HttpResponseForbidden,
HttpResponseServerError
)
from django.views.decor... |
#!/usr/bin/env python
# -*- coding: utf-8 -*- #
from __future__ import unicode_literals
AUTHOR = 'Jason Kennemer'
SITENAME = 'NewOps'
SITEURL = ''
PATH = 'content'
THEME = 'themes/pelican-alchemy/alchemy'
TIMEZONE = 'US/Central'
DEFAULT_LANG = 'en'
# Extract a post's date from the filename:
#FILENAME_METADATA = '(?... |
'''
Calculates the product of distinct prime factors of a number
18 Oct 2012
James Cowgill
'''
from __future__ import print_function
import math
def _prime_olympiad_test_list(number, primes):
'''Tests just using the primes in the primes'''
# Calculate cutoff
cutoff = int(math.sqrt(number))
# Find ... |
from .backup_resource_vault_configs_operations import BackupResourceVaultConfigsOperations
from .backup_engines_operations import BackupEnginesOperations
from .protection_container_refresh_operation_results_operations import ProtectionContainerRefreshOperationResultsOperations
from .protection_containers_operations imp... |
# -*- coding: utf-8 -*-
"""
Control screen layout.
This modules allows you to handle your screens outputs directly from your bar!
- Detect and propose every possible screen combinations
- Switch between combinations using click events and mouse scroll
- Activate the screen or screen combination on a single... |
from ..deployment.local_deployment import *
from ..facades.fb import *
from ..facades.identity import *
from ..facades.api import *
from ..facades.db import *
# TODO use some testing framework
class UsersAccounts:
def __init__(self, deployment_info):
self.deployment_info = deployment_info
self.db_facade = DbFac... |
def extract_timeseries (model, fieldname, units, lat, lon, location):
from ..common import number_of_levels, number_of_timesteps, convert
field = model.find_best(fieldname, maximize=(number_of_levels, number_of_timesteps))
field = field(lat=lat,lon=lon)
field = model.cache.write(field, prefix=model.name+'_'+fie... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
import os
import tempfile
import logging
from contextlib import contextmanager
log = logging.getLogger(__name__)
class SingleInstanceException(BaseException):
pass
@contextmanager
def singleton(flavor_id=""):
"""
Inspired by tendo.singleton: htt... |
# -*- 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):
# Changing field 'MindMapComponent.title'
db.alter_column('mindmap_mindmapcomponent', 'title', self.gf('dja... |
#!/usr/bin/env python
########################################################################################################
###
### @author Alberto Ciolini
###
########################################################################################################
import pyshark
from event import *
def bro... |
from threading import Event
import pandas as pd
from yandextank.common.util import FileMultiReader
from yandextank.plugins.Phantom.reader import PhantomReader, PhantomStatsReader, string_to_df_microsec
class TestPhantomReader(object):
def setup_class(self):
stop = Event()
self.multireader = File... |
"""
This script does all the platform dependent stuff. Its main task is
to figure out where the python modules are.
"""
import sys
import os
import re
import logging
logger = logging.getLogger('mypaint')
class ColorFormatter (logging.Formatter):
"""Minimal ANSI formatter, for use with non-Windows console logging.... |
from cStringIO import StringIO
import os
import shutil
import tempfile
from zipfile import ZipFile
from django.conf import settings
from django.contrib.auth.models import User
from django.core.urlresolvers import reverse
from django.test import TestCase
from django.test.utils import override_settings
from symposion.c... |
#!/usr/bin/env python
# -- Content-Encoding: UTF-8 --
"""
The Node Composer
:author: Thomas Calmant
:license: Apache Software License 2.0
:version: 3.0.0
..
Copyright 2014 isandlaTech
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the ... |
config = {
"branch": "date",
"nightly_build": True,
"update_channel": "beta-dev",
# l10n
"hg_l10n_base": "https://hg.mozilla.org/releases/l10n/mozilla-beta",
# mar
"latest_mar_dir": "fake_kill_me",
# repositories
# staging beta dev releases use date repo for now
"mozilla_dir":... |
from . import test_auth_key, Plan, TestCase
class TestPlansRecord(TestCase):
def setUp(self):
super(TestPlansRecord, self).setUp()
self.assertNotEqual(test_auth_key, None)
self.plan = Plan(authorization_key=test_auth_key)
def test_plans_records(self):
"""
Integration t... |
"""Class for representing a single entity in the Cloud Datastore."""
class Entity(dict):
"""Entities are akin to rows in a relational database
An entity storing the actual instance of data.
Each entity is officially represented with a
:class:`gcloud.datastore.key.Key` class, however it is possible t... |
import bpy
from object_smoke2cycles import interface
from object_smoke2cycles import create_mat
from traceback import print_exc
bl_info = {
"name": "Smoke2Cycles",
"description": "Convert BI smoke/fire simulations into a cycles 2.69.x compatible setup",
"author": "HiPhiSch",
"version": (0, 3),
"bl... |
import unittest
import sys
sys.path.insert(0,'..')
import sympy
import numpy as np
from parampy import Parameters
from qubricks import Operator
class TestOperator(unittest.TestCase):
def setUp(self):
self.p = Parameters()
self.array = np.array([[1,2],[3,4]])
z,x = sympy.var('z,x')
self.matrix = sympy.Matri... |
#!/opt/local/bin/python
# -*- coding: utf-8 -*-
"""
Main program file.
Example of Franco-Conde Model.
StoneX V1.0 compatible
"""
################################################################################
# MODULES
################################################################################
## P... |
import math
import numbers
class CartesianCoordinateSystem:
def __init__(self, x, y):
if not isinstance(x, numbers.Real): raise ValueError("There is an Error, please check the value of (CartesianCoordinateSystem) x")
if not isinstance(y, numbers.Real): raise ValueError("There is an Error, please ... |
#!/usr/bin/python
# -- Content-Encoding: UTF-8 --
"""
The history module.
:authors: Josh Marshall, Thomas Calmant
:copyright: Copyright 2015, isandlaTech
:license: Apache License 2.0
:version: 0.2.6
..
Copyright 2015 isandlaTech
Licensed under the Apache License, Version 2.0 (the "License");
you may not... |
from django.db import migrations, models
from djangocms_blog.settings import get_setting
BLOG_PLUGIN_TEMPLATE_FOLDERS = get_setting("PLUGIN_TEMPLATE_FOLDERS")
class Migration(migrations.Migration):
dependencies = [
("djangocms_blog", "0023_auto_20160626_1539"),
]
operations = [
migrati... |
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import horizon.manager
import uuid
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
... |
"""
Takes in a dataflish BIN file and splits it into multiple files.
Intent is to split it each time it is armed
Requirements:
pip install pymavlink
"""
from pymavlink.DFReader import DFReader_binary
def split_logs(filename, seconds2split, prefix=None, verbose=False):
"""
This splits an ArduPilot binary da... |
import os
from pyramid.authentication import AuthTktAuthenticationPolicy
from pyramid.authorization import ACLAuthorizationPolicy
from pyramid.security import Allow, Authenticated
from pyramid.session import SignedCookieSessionFactory
from passlib.apps import custom_app_context as pwd_context
class NewRoot(object):... |
##
# \namespace reviewTool.api.contexts.asset
#
# \remarks [desc::commented]
#
# \author Dr. D Studios
# \date 08/02/11
from ..context import Context
from ..entity import Entity
from ...database import db
class AssetContext(Context):
ShotgunAssetTypeMap = {
'Characte... |
"""Tests for BigQuery Ops."""
import concurrent.futures
from io import BytesIO
import json
import fastavro
import numpy as np
import grpc # pylint: disable=wrong-import-order
import tensorflow as tf # pylint: disable=wrong-import-order
from tensorflow.python.framework import dtypes # pylint: disable=wrong-import-... |
import re
import threading
import warnings
from opengraph.opengraph import OpenGraph
RE_ENDS_IN_INT = re.compile(r"[\d]+$")
class IntegrationThread(threading.Thread):
"""
Used as a base class for everything else.
"""
def __init__(self, rpc, bug_system, execution, bug_id):
"""
:param... |
import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk, Pango
class SearchDialog(Gtk.Dialog):
def __init__(self, parent):
Gtk.Dialog.__init__(self, "Search", parent,
Gtk.DialogFlags.MODAL, buttons=(
Gtk.STOCK_FIND, Gtk.ResponseType.OK,
Gtk.STOCK_CANCEL... |
from datetime import datetime, timedelta
from olympia.constants.scanners import MAD
from olympia.users.models import (
EmailUserRestriction,
IPNetworkUserRestriction,
RESTRICTION_TYPES,
)
def _no_action(version):
"""Do nothing."""
pass
def _flag_for_human_review(version):
"""Flag the versio... |
"""
Future objects that represent one-shot caller-callee contract. A caller
will hold a Future object and its callee will hold a Promise object.
Direct caller-callee relationship where a caller has direct reference to
its callee should be modelled by normal function call or task spawning.
Future objects should be for... |
import time
from rstem import led2
led = led2
def width():
return 8
def height():
return 8
led.init_matrices([(0,0,90)])
led.width = width
led.height = height
x = 0.0
y = 0.0
xdist = 0.1
ydist = 0.5
period = 0.01
while True:
# Draw the ball (which is just a point)
led.fill(0)
if (0 <= int(x) < 8 and 0 ... |
from __future__ import unicode_literals
from sqlalchemy.orm import Load
from pfamserver.models import Uniprot, UniprotRegFull, Pdb, PdbPfamAReg
from pfamserver.extensions import db
def get_pdbs_from_uniprot_pfam_a_reg(uniprot_id, seq_start, seq_end):
query = db.session.query(PdbPfamAReg)
query = query.join(Pd... |
from . import client
def basic(client, id):
""" Gets basic data about an studio
:param client: an instance of a :class:`Client <Client>`
:param id: the id to get
:return: the json answer of the API
:rtype: str
"""
return client.get('studio/%d' % id)
def page(client, id):
""" Get... |
from flask import flash
from mongoengine import Document
from mongoengine.fields import StringField, EmailField, BooleanField, IntField
from wevesi import crypt
class User(Document):
name = StringField(required=True)
email = EmailField(required=True, unique=True)
password = StringField(required=True)
... |
import unittest
import os
from datetime import datetime
from tempfile import mkstemp
from invenio.testutils import make_test_suite, run_test_suite
from invenio import bibupload
from invenio import bibtask
from invenio.dbquery import run_sql
from invenio.search_engine_utils import get_fieldvalues
from invenio import oa... |
import io
import os
import shutil
import tempfile
from docker import errors
from docker.utils.proxy import ProxyConfig
import pytest
import six
from .base import BaseAPIIntegrationTest, BUSYBOX
from ..helpers import random_name, requires_api_version, requires_experimental
class BuildTest(BaseAPIIntegrationTest):
... |
import sys
# check python version
if sys.version_info < (3, 4, 0):
print("CloudBot requires Python 3.4 or newer.")
sys.exit(1)
import json
import logging.config
import logging
import os
__version__ = "1.0.9"
__all__ = ["clients", "util", "bot", "client", "config", "event", "hook", "permissions", "plugin", "... |
from PyInstaller.utils.hooks import collect_data_files
from PyInstaller.compat import is_win, is_darwin
import os
import sys
# The osgeo libraries require auxiliary data and may have hidden dependencies.
# There are several possible configurations on how these libraries can be
# deployed.
# This hook evaluates the ca... |
import collections
class MessagesOnHold(object):
"""Tracks messages on hold by ordering key. Not thread-safe.
"""
def __init__(self):
self._size = 0
# A FIFO queue for the messages that have been received from the server,
# but not yet sent to the user callback.
# Both or... |
import warnings
import pytest
import torch
from pyro import util
pytestmark = pytest.mark.stage('unit')
def test_warn_if_nan():
# scalar case
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter("always")
x = float('inf')
msg = "example message"
y = util.warn... |
import unittest
import numpy as np
import flavio
constraints = flavio.default_parameters
wc_obj = flavio.WilsonCoefficients()
par = constraints.get_central_all()
class TestKpilnu(unittest.TestCase):
def test_kpilnu(self):
# test for errors
q2=0.05
flavio.physics.kdecays.kpilnu.get_ff(q2, p... |
"""Bignum routines"""
from __future__ import absolute_import, division, print_function, unicode_literals
import struct
# generic big endian MPI format
def bn_bytes(v, have_ext=False):
ext = 0
if have_ext:
ext = 1
return ((v.bit_length()+7)//8) + ext
def bn2bin(v):
s = bytearray()
i = b... |
from PIL import Image, ImageDraw
from geometry import Point
def mid(a,b, frac):
return a*(1-frac) + b*frac
def mid_color(a, b, frac):
return tuple(int(mid(x,y, frac)) for x,y in zip(a,b))
black = (0,0,0)
white = (255,255,255)
def create_image(color):
#the grid cell size is 25*25, but we want a little bl... |
from tkinter import *
from threading import Thread
from time import sleep
import math
class Menu(Frame):
def __init__(self, master, child):
super(Menu, self).__init__(master)
self.grid()
self.createWidgets(master, child)
def update(self, child):
"""
Threading function to update stats periodically
"""
... |
# import os
# import numpy as np
#
# import torch
# import torch.nn as nn
# from torch.autograd import Variable
#
# from gensim.models.word2vec import Word2Vec
#
# from pymongo import MongoClient
#
# from tempfile import gettempdir
#
# from obonet import read_obo
#
# from src.python.preprocess import *
#
# import argpa... |
#!/usr/bin/env python
##################################################
# Gnuradio Python Flow Graph
# Title: MIMO TOP FLOW
# Description: LTE decoding up to 2 tx antennas
# Generated: Wed Nov 12 13:26:55 2014
##################################################
execfile("/home/johannes/.grc_gnuradio/decode_bch_hier_gr... |
#!/usr/bin/env python
# encoding: utf-8
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
class Client(object):
def __init__(self, usr, psw, from_address):
self.username = usr
self.password = psw
self.from_address = from_address
s... |
import os
import config
import yaml
from .jargon import Jargon
from .resources import DEFAULT_DATA, DEFAULT_HEADER
JARGON_PATH = os.path.join(config.savePath, 'jargon.yaml') if config.savePath is not None else None
class JargonLoader:
def __init__(self, jargon_path: str):
self.jargon_path = jargon_path
... |
# Capstone Python bindings, by Nguyen Anh Quynnh <<EMAIL>>
import ctypes
from . import copy_ctypes_list
from .sparc_const import *
# define the API
class SparcOpMem(ctypes.Structure):
_fields_ = (
('base', ctypes.c_uint8),
('index', ctypes.c_uint8),
('disp', ctypes.c_int32),
)
class S... |
# NSIS Support for SCons
# Written by Mike Elkins, January 2004
# Provided 'as-is', it works for me!
"""
This tool provides SCons support for the Nullsoft Scriptable Install System
a windows installer builder available at http://nsis.sourceforge.net/home
To use it you must copy this file into the scons/SC... |
"""Module that allows Checkers tests to be used with PyUnit test runner.
This also provides a main function that calls a PyUnit-based main function once
the Checkers tests have been "discovered" by PyUnit.
Note that the way this works, Checkers will go ahead and run all of the tests in
the Checkers test runs. It then... |
"""Helpers for Home Assistant dispatcher & internal component/platform."""
import logging
from homeassistant.core import callback
from homeassistant.loader import bind_hass
from homeassistant.util.async import run_callback_threadsafe
_LOGGER = logging.getLogger(__name__)
DATA_DISPATCHER = 'dispatcher'
@bind_hass
d... |
__doc__="""HPFan
HPFan is an abstraction of a fan or probe.
$Id: HPFan.py,v 1.1 2010/06/29 10:36:44 egor Exp $"""
__version__ = "$Revision: 1.1 $"[11:-2]
from Products.ZenModel.DeviceComponent import DeviceComponent
from Products.ZenModel.Fan import *
from HPComponent import *
class HPFan(Fan, HPComponent):
""... |
""" This is an integration test using both the TSCatalog and the FileCatalog plugins
It supposes that the TransformationDB and the FileCatalogDB to be present
It supposes the TransformationManager and that DataManagement/FileCatalog services running
The TSCatalog and FileCatalog plugins must be configured... |
from collections import namedtuple
from pybliometrics.scopus.superclasses import Retrieval
from pybliometrics.scopus.utils import check_parameter_value
class PlumXMetrics(Retrieval):
@property
def category_totals(self):
"""A list of namedtuples representing total metrics as categorized
by Plu... |
"""Tests for samba.param."""
from samba import param
import samba.tests
class LoadParmTestCase(samba.tests.TestCase):
def test_init(self):
file = param.LoadParm()
self.assertTrue(file is not None)
def test_length(self):
file = param.LoadParm()
self.assertEquals(0, len(file))
... |
#!/usr/bin/env python2
# vim:fileencoding=utf-8
from __future__ import (unicode_literals, division, absolute_import,
print_function)
__license__ = 'GPL v3'
__copyright__ = '2014, Kovid Goyal <kovid at kovidgoyal.net>'
from lxml import etree
from calibre import prepare_string_for_xml as xml
fr... |
#!/usr/bin/env python3
from generator.textutil import indent, dedent
from generator.Enum import Enum
from generator.Message import Message
import re
class File:
def __init__(self, f, base_file):
# Store relevant information from our class in our object
self.package = f.package
self.name... |
import sys
import test_framework
def main(arg):
op = arg[1] if len(arg) > 1 and "clean" == arg[1] else ""
test_framework.runTest("xml_",
"xsd-positive/",
"../templates/c-xml-expat",
op)
if __name__ == "__main__":
main(sys.... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
http://www.myengineeringworld.net/2013/10/Excel-thermochemical-NASA-polynomials-Burcat.html
"""
#
# http://www.wsp.ru/en/..%5Cdownload%5Cdocs%5Carticles%5Cen%5CTENG221.pdf
# http://www.wsp.ru/en/test/wspgGCGS.asp?gas_specification=air
#import sys
#sys.path.append("/ho... |
import logging
import cobra
from kepavi.kegg_utils import Kegg
import requests
import os
from collections import defaultdict
import random
from kepavi.user.models import KeggReaction
# Sigma js has my preference since it can handle
# larger graph
GRAPH_LIBRARY_BACKEND = {'cytoscape', 'sigma'}
# this meta... |
# pylint: disable=no-self-use,invalid-name,protected-access
import torch
import numpy
from allennlp.common.testing import AllenNlpTestCase
from allennlp.data import Vocabulary
from allennlp.training.metrics import SpanBasedF1Measure, Metric
from allennlp.common.params import Params
class SpanBasedF1Test(AllenNlpTest... |
"""Handles all reconnaissance operations."""
from __future__ import absolute_import, division, print_function
from logging import getLogger
from threading import Thread
from time import sleep, strftime
from typing import List, Set
import scapy
import scapy.layers.dot11 as dot11
import wifiphisher.common.globals as u... |
from __future__ import absolute_import, division, print_function, unicode_literals
from logging import getLogger
from os.path import basename, dirname
import re
import sys
from .._vendor.auxlib.ish import dals
from ..base.constants import ROOT_ENV_NAME
from ..base.context import context
from ..common.constants import... |
class SessionHandler:
def __init__(self, app):
self.app = app
def logout(self):
wd = self.app.wd
wd.find_element_by_link_text("Logout").click()
def login(self, username, password):
wd = self.app.wd
self.app.open_hp()
wd.find_element_by_name("user").click()
... |
#!/usr/bin/python
import sys, os, ntpath, shutil, time, datetime
def help():
print "Usage: python copy.py [all][file][dir] [type]-t [date begin]-b [date from]-e [size low]-s [size high]-l [name]-strict [name]-leninent force"
print "command all will copy all the files from the Main Drive of the computer, you can spec... |
from django.conf import settings
from django.conf.urls.defaults import *
from django.views.generic import list_detail
from jumpsuit.core.models import Host
urlpatterns = patterns('',
url(r'^add/?$', 'web.views.add_host',
name='jumpsuit_host_add'),
url(r'^(?P<host>[a-z0-9]+[a-z0-9\-]*)/delete/?$', 'web... |
import numpy
import numpy as np
import h5py
from srxraylib.plot.gol import plot_image,plot_surface,plot
# see https://stackoverflow.com/questions/17044052/mathplotlib-imshow-complex-2d-array
from colorsys import hls_to_rgb
from matplotlib.colors import hsv_to_rgb
import pylab as plt
from matplotlib.colors import Nor... |
"""
Instance app - Util functions
"""
# Imports #####################################################################
import json
import requests
import socket
from mock import Mock
# Functions ###################################################################
def is_port_open(ip, port):
"""
Check if the... |
#!/usr/bin/env python
import cgi
import urllib
import requests
import json
import mustachify
import pyimgur
import random
import sys
downloadImagePath = "gs_image.jpg"
mustachifyImagePath = "mustachfied_image.jpg"
def getSearchQuery():
query = ""
form = cgi.FieldStorage()
if form.has_key('q'):
qu... |
# -*- coding: utf-8 -*-
from datetime import datetime
from operator import contains
from functools import partial
import unittest
import pytz
from minerva.storage import datatype
from minerva.storage.trend.granularity import create_granularity
from minerva.storage.trend.datapackage import DataPackage
from minerva.sto... |
"""
Check xmlschema package import memory usage.
Refs:
https://pypi.org/project/memory_profiler/
https://github.com/brunato/xmlschema/issues/32
"""
import argparse
from memory_profiler import profile
def test_choice_type(value):
if value not in (str(v) for v in range(1, 9)):
msg = "%r must be an ... |
from templeplus.pymod import PythonModifier
from toee import *
import tpdp
import char_class_utils
import math
###################################################
def GetConditionName():
return "Scout"
classEnum = stat_level_scout
classSpecModule = __import__("class046_scout")
######################################... |
import numpy as np
from srilm import LM
from decoder_config import LM_ARPA_FILE, SPACE, LM_ORDER
'''
Sample text from character language model
'''
def sample_continuation(s, lm, order, alpha=1.0):
# Higher alpha -> more and more like most likely sequence
n = lm.vocab.max_interned()
probs = np.empty(n, dt... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.