code stringlengths 1 199k |
|---|
import os
import random
import unittest
import warnings
from math import exp, pi
import gpytorch
import torch
from gpytorch.distributions import MultivariateNormal
from gpytorch.kernels import InducingPointKernel, RBFKernel, ScaleKernel
from gpytorch.likelihoods import GaussianLikelihood
from gpytorch.means import Cons... |
"""
Django settings for apps project.
Generated by 'django-admin startproject' using Django 1.9.7.
For more information on this file, see
https://docs.djangoproject.com/en/1.9/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.9/ref/settings/
"""
import os
from loca... |
"""Command for spanner databases create."""
from googlecloudsdk.api_lib.spanner import database_operations
from googlecloudsdk.api_lib.spanner import databases
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.spanner import flags
class Create(base.CreateCommand):
"""Cloud Spanner databases cre... |
import sys, os
sys.path.insert(0, os.path.abspath(os.path.join('..')))
extensions = ['sphinx.ext.autodoc', 'sphinx.ext.viewcode']
templates_path = ['_templates']
source_suffix = '.rst'
master_doc = 'index'
project = u'M2Crypto'
copyright = u'2017, Matej Cepl <mcepl@cepl.eu>'
version = ''
release = ''
exclude_patterns =... |
from zeroconf import Zeroconf, ServiceInfo
import socket
import configparser
from . import hazc_cmd
class hazc_device:
#Forward constants
NO_PARAM = hazc_cmd.NO_PARAM
BOOL = hazc_cmd.BOOL
FLOAT = hazc_cmd.FLOAT
STRING = hazc_cmd.STRING
INT = hazc_cmd.INT
global running
running = False
... |
from victor.exceptions import (
FieldValidationException,
FieldTypeConversionError,
FieldRequiredError,
VectorInputTypeError
)
class Field(object):
required = True
"""Field is required and an exception will be raised if missing"""
missing_value = None
"""Value to use when field is missin... |
""" PyAbleton
A library for creating and editing Ableton Live instrument/effect presets in Python.
"""
__author__ = 'ham@hamiltonkib.be'
__version__ = '1.0'
import presets |
"""
Django settings for figexample project.
For more information on this file, see
https://docs.djangoproject.com/en/1.7/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.7/ref/settings/
"""
import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
SECRET_KEY... |
import abc
import platform
from UserList import UserList
class Monitor(object):
@abc.abstractmethod
def current(self):
pass
@abc.abstractmethod
def percent(self, range):
pass
@abc.abstractmethod
def reset(self):
pass
@abc.abstractmethod
def max(self):
pass... |
"""
Forms for day forms
"""
from django.conf import settings
from django import forms
from django.utils.translation import ugettext as _
from arrow import Arrow
from datebook.models import DayEntry
from datebook.forms import CrispyFormMixin
from datebook.utils.imports import safe_import_module
DATETIME_FORMATS = {
... |
from __future__ import absolute_import, division, print_function
import numpy as np
from ...magic.core.frame import Frame
from ..basics.remote import Remote, connected_remotes
from . import time
from . import filesystem as fs
from .logging import log
def remote_convolution(image, kernel, host_id):
"""
This func... |
"""
| This file is part of the web2py Web Framework
| Copyrighted by Massimo Di Pierro <mdipierro@cs.depaul.edu>
| License: LGPLv3 (http://www.gnu.org/licenses/lgpl.html)
Provides:
- List; like list but returns None instead of IndexOutOfBounds
- Storage; like dictionary allowing also for `obj.foo` for `obj['foo']`
"""
... |
from ..debugging import bacpypes_debugging, ModuleLogger
from ..capability import Capability
from ..basetypes import ErrorType, PropertyIdentifier
from ..primitivedata import Atomic, Null, Unsigned
from ..constructeddata import Any, Array, ArrayOf, List
from ..apdu import \
SimpleAckPDU, ReadPropertyACK, ReadProper... |
"""
Contains data about certain markup, like HTML tags and external links.
When updating this file, please also update the the C tokenizer version:
- mwparserfromhell/parser/ctokenizer/definitions.c
- mwparserfromhell/parser/ctokenizer/definitions.h
"""
__all__ = [
"get_html_tag",
"is_parsable",
"is_visible... |
from __future__ import print_function
from __future__ import division
from builtins import range
from past.utils import old_div
from coetools import *
sum = add.reduce # Just to make sure
inbpz = capfile(sys.argv[1], 'bpz')
inroot = inbpz[:-4]
infile = loadfile(inbpz)
for line in infile:
if line[:7] == '##INPUT':
... |
import math
import sys
import os
import random
CommonPath = os.path.abspath(os.path.join('..', 'Common'))
sys.path.append(CommonPath)
import tsp
def GenerateInitialPath(tour_length):
tour=list(range(tour_length))
random.shuffle(tour)
return tour
MAX_ITERATION = 50000
def reversed_sections(tour):
'''generat... |
"""django_todo URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.11/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class... |
"""
Example
-------
class SystemSetting(KVModel):
pass
setting = SystemSetting.create(key='foo', value=100)
loaded_setting = SystemSetting.get_by_key('foo')
"""
from django.db import models
from .fields import SerializableField
class KVModel(models.Model):
"""
An Abstract model that has key and value fields... |
import re
from datetime import datetime
from flask import current_app as app
from flask_jwt import current_identity
from flask_restplus import Namespace, Resource, fields, reqparse
from sqlalchemy.exc import IntegrityError
from packr.models import Message
api = Namespace('contact',
description='Operatio... |
from typing import TYPE_CHECKING, Any, Dict, Union
from ansiblelint.rules import AnsibleLintRule
if TYPE_CHECKING:
from typing import Optional
from ansiblelint.file_utils import Lintable
class MercurialHasRevisionRule(AnsibleLintRule):
id = 'hg-latest'
shortdesc = 'Mercurial checkouts must contain expli... |
from setuptools import setup
setup(
name='libipa',
version='0.0.6',
author='Andrew Udvare',
author_email='audvare@gmail.com',
packages=['ipa'],
scripts=['bin/ipa-unzip-bin', 'bin/ipa-dump-info'],
url='https://github.com/Tatsh/libipa',
license='LICENSE.txt',
description='Library to re... |
"""
Support to interface with Sonos players (via SoCo).
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/media_player.sonos/
"""
import datetime
import logging
from os import path
import socket
import urllib
import voluptuous as vol
from homeassistant.compo... |
"""
"""
import logging
import time
import hiro
import mock
from flask import Flask, request
from werkzeug.exceptions import BadRequest
from flask_limiter.extension import C, Limiter
from flask_limiter.util import get_remote_address
def test_reset(extension_factory):
app, limiter = extension_factory({C.DEFAULT_LIMIT... |
class argpasser(object):
"""
ComEst use the arguments that are almost repeatedly. Therefore, it will be useful to create a customized arguemnt passer like this.
"""
def __init__(self,
stamp_size_arcsec = 20.0,
mag_dict = {"lo":20.0, "hi":25.0 },
... |
import os
from setuptools import setup, find_packages
README = open(os.path.join(os.path.dirname(__file__), 'README.md')).read()
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
setup(
name='django-email-subscription',
url='https://github.com/MagicSolutions/django-email-subscriptio... |
from pymongo import MongoClient
from pandas import read_csv
from datetime import date
mongodb = MongoClient('192.168.178.82', 9999)
db = mongodb['dev']
drug_collection = db['drug']
drugs = read_csv('~/Dokumente/bfarm_lieferenpass_meldung.csv', delimiter=';', encoding='iso8859_2').to_dict()
drugs.pop('Id', None)
drugs.p... |
"""Molt Web API with Interface."""
import re
import redis
import docker
import subprocess
import os
import shlex
import requests
import sys
import argparse
from flask import Flask, Response, render_template, abort, request
from molt import Molt, MoltError
app = Flask(__name__)
parser = argparse.ArgumentParser()
parser.... |
from django.contrib import admin
try:
from django.contrib.auth import get_permission_codename
except ImportError: # pragma: no cover
# Django < 1.6
def get_permission_codename(action, opts):
return '%s_%s' % (action, opts.object_name.lower())
class ObjectPermissionsModelAdminMixin(object):
def ... |
"""
Production Configurations
- Use Redis for cache
"""
from __future__ import absolute_import, unicode_literals
from boto.s3.connection import OrdinaryCallingFormat
from django.utils import six
from .common import * # noqa
SECRET_KEY = env('DJANGO_SECRET_KEY')
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'htt... |
"""
getname
~~~~~~~
Get popular cat/dog/superhero/supervillain names.
:copyright: (c) 2015 by lord63.
:license: MIT, see LICENSE for more details.
"""
from getname.main import random_name
__title__ = "getname"
__version__ = '0.1.1'
__author__ = "lord63"
__license__ = "MIT"
__copyright__ = "Copyright... |
from cse.util import Util
from collections import OrderedDict
from cse.pipeline import Handler
class WpApiParser(Handler):
def __init__(self):
super()
def parse(self, comments, url, assetId, parentId):
data = self.__buildDataSkeleton(url, assetId)
data["comments"] = self.__iterateComment... |
"""Test framework for syscoin utils.
Runs automatically during `make check`.
Can also be run manually."""
import argparse
import binascii
import configparser
import difflib
import json
import logging
import os
import pprint
import subprocess
import sys
def main():
config = configparser.ConfigParser()
config.opt... |
from __future__ import print_function
import sys, os
def print_error(*args, **kwargs):
print(*args, file=sys.stderr, **kwargs)
if len(sys.argv) != 2:
print_error("Usage: python pre_NAMD.py $PDBID")
sys.exit(-1)
mypath = os.path.realpath(__file__)
tclpath = os.path.split(mypath)[0] + os.path.sep + 'tcl' + os.p... |
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('busshaming', '0013_auto_20170917_0502'),
]
operations = [
migrations.CreateModel(
name='StopSequence',
... |
"""
Poisson time series penalised likelihood regression
via the Berman Turner device
"""
from . import weighted_linear_model
from . import design_nonlattice as design
from math import ceil
import numpy as np
from importlib import reload
design = reload(design)
class NonLatticeOneShot:
"""
the simplest device.
... |
"""useful context managers"""
from contextlib import suppress
with suppress(ModuleNotFoundError):
from lag import *
import os
import contextlib
def clog(*args, condition=True, log_func=print, **kwargs):
if condition:
return log_func(*args, **kwargs)
@contextlib.contextmanager
def cd(newdir, verbose=True... |
import os
import warnings
from pymatgen.core.structure import Structure
from pymatgen.core.units import Ha_to_eV, bohr_to_ang
from pymatgen.io.abinit.abiobjects import *
from pymatgen.util.testing import PymatgenTest
class LatticeFromAbivarsTest(PymatgenTest):
def test_rprim_acell(self):
l1 = lattice_from_a... |
import _plotly_utils.basevalidators
class ArrowcolorValidator(_plotly_utils.basevalidators.ColorValidator):
def __init__(
self, plotly_name="arrowcolor", parent_name="layout.annotation", **kwargs
):
super(ArrowcolorValidator, self).__init__(
plotly_name=plotly_name,
paren... |
import sys
if sys.version_info.major >= 3:
from configparser import RawConfigParser
else:
from ConfigParser import RawConfigParser
from .OrderedMultiDict import OrderedMultiDict
class UsefulConfigParser(object):
"""A config parser that sucks less than those in module `ConfigParser`."""
def __init__(self... |
__Author__ = "Riyaz Ahmad Bhat"
__Email__ = "riyaz.ah.bhat@gmail.com"
import re
from collections import namedtuple
from sanity_checker import SanityChecker
class DefaultList(list):
"""Equivalent of Default dictionaries for Indexing Errors."""
def __init__(self, default=None):
self.default = default
... |
import os
from setuptools import setup, find_packages
here = os.path.abspath(os.path.dirname(__file__))
with open(os.path.join(here, 'README.md')) as f:
README = f.read()
with open(os.path.join(here, 'CHANGES.md')) as f:
CHANGES = f.read()
requires = [
'pyramid',
'pyramid_jinja2',
'pyramid_debugtool... |
"""
atomorder/parse_args.py
Parses command line arguments and overwrites setting defaults
"""
from . import settings
import argparse
import sys
description = ""
epilog = ""
parser = argparse.ArgumentParser(
description = description,
formatter_class = argparse.RawDescriptionHelpFormatter,
epilog... |
import glob
import os
import shutil
import subprocess
import sys
import yaml
def create_role(role):
ret = subprocess.check_output(
'ansible-galaxy init {}'.format(role).split())
if not ret.strip().endswith('created successfully'):
raise Exception('could not create role "{}"'.format(role))
def ge... |
"""Make use of synaptic as backend."""
__author__ = "Sebastian Heinlein <devel@glatzor.de>, " \
"Michael Vogt <mvo@canonical.com"
import tempfile
from gettext import gettext as _
from gi.repository import GObject
from defer import Deferred
import sessioninstaller.errors
class SynapticBackend(object):
"... |
from django.test import TestCase
from medicine.models import Medicine
from medicine.views import ListAllMedicines
from user.models import HealthProfessional
class TestListAllMedicines(TestCase):
def setUp(self):
# Making a HealthProfessional
self.view = ListAllMedicines
# Making medicati
... |
import _plotly_utils.basevalidators
class BgcolorValidator(_plotly_utils.basevalidators.ColorValidator):
def __init__(
self, plotly_name="bgcolor", parent_name="sankey.node.hoverlabel", **kwargs
):
super(BgcolorValidator, self).__init__(
plotly_name=plotly_name,
parent_na... |
from pyperator.decorators import inport, outport, component, run_once
from pyperator.nodes import Component
from pyperator.DAG import Multigraph
from pyperator.utils import InputPort, OutputPort
import pyperator.components |
import itertools
import os.path
import sys
import time
from . import core
from . import file_io
from . import geometry
from . import stringconv
from . import version
def save_output(profileli, opt):
""" Save a summary of results of evaluated profiles
"""
def m(x, pixelwidth):
return geometry.to_metr... |
import os
import re
import subprocess
from six.moves.urllib.parse import urlparse, quote_plus
from subprocess import CalledProcessError, PIPE, STDOUT
from conans.client.tools.env import no_op, environment_append
from conans.client.tools.files import chdir
from conans.errors import ConanException
from conans.util.files ... |
import pycmds.project.classes as pc
import pycmds.hardware.hardware as hw
import pathlib
import appdirs
import toml
import yaqc
class Driver(hw.Driver):
def __init__(self, *args, **kwargs):
self._yaqd_port = kwargs.pop("yaqd_port")
super().__init__(*args, **kwargs)
self.grating_index = pc.Co... |
u"""
Fixer for Python 3 function parameter syntax
This fixer is rather sensitive to incorrect py3k syntax.
"""
from lib2to3 import fixer_base
from lib2to3.fixer_util import token, String, Newline, Comma, Name
from libfuturize.fixer_util import indentation, suitify, DoubleStar
_assign_template = u"%(name)s = %(kwargs)s[... |
__author__ = 'Radoslaw Matusiak'
__copyright__ = 'Copyright (c) 2016 Radoslaw Matusiak'
__license__ = 'MIT'
__version__ = '0.5'
import cmd
import functools
import os
import sys
from polar import Device
from polar.pb import device_pb2 as pb_device
__INTRO = """
_| _| ... |
import json
import sublime
import sublime_plugin
from .edit import Edit
class PawnBuildPathCommand(sublime_plugin.TextCommand):
def run(self, edit):
self.view.window().show_input_panel(
"Working directory that contains pawncc.exe",
"C:\\Pawno\\",
self.onPawnPathDone,
... |
class node:
def __init__(self):
self.outputs=[]
def set(self):
for out in self.outputs:
out.set()
def clear(self):
for out in self.outputs:
out.clear()
class switch:
def __init__(self):
self.outputs=[]
self.state=False
self.input=False
def set(self):
self.input=True
if(self.state):
for out... |
from math import sqrt
def is_prime(x):
for i in xrange(2, int(sqrt(x) + 1)):
if x % i == 0:
return False
return True
def rotate(v):
res = []
u = str(v)
while True:
u = u[1:] + u[0]
w = int(u)
if w == v:
break
res.append(w)
return re... |
"""
Copyright (c) 2016 Genome Research Ltd.
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, distri... |
import mock
from tests.compat import unittest
from tests.utils import APITestCase
import evelink.eve as evelink_eve
class EVETestCase(APITestCase):
def setUp(self):
super(EVETestCase, self).setUp()
self.eve = evelink_eve.EVE(api=self.api)
def test_character_names_from_ids(self):
self.api... |
try:
from calais import Calais
except ImportError: # pragma: no cover
Calais = None # NOQA
if Calais is not None:
def process_calais(content, key):
calais = Calais(key)
response = calais.analyze(content)
people = [entity["name"] for entity in getattr(response, "entities", []) if en... |
import datetime
day = datetime.datetime.now().weekday()
def get_sunday():
return "Today it's Sunday"
def get_monday():
return "Today it's Monday"
def get_tuesday():
return "Today it's Tuesday"
def get_wednesday():
return "Today it's Wednesday"
def get_thursday():
return "Today it's Thursday"
def get... |
from django.conf.urls import url
from timeline import views
urlpatterns = [
url(r'^$', views.timelines, name='timelines'),
] |
from contextlib import contextmanager
from functools import wraps
from werkzeug.local import LocalProxy, LocalStack
_additional_ctx_stack = LocalStack()
__all__ = ("current_additions", "Additional", "AdditionalManager")
@LocalProxy
def current_additions():
"""
Proxy to the currently added requirements
"""
... |
import unittest
"""
Given a binary tree, we need to find maximum value we can get by subtracting
value of node B from value of node A, where A and B are two nodes of the binary tree
and A is ancestor of B. Expected time complexity is O(n).
"""
class Node:
def __init__(self, data, left=None, right=None):
sel... |
import datetime
now = datetime.datetime.now()
print now.strftime("%Y-%m-%d %H:%M:%S") |
import requests
from unittest import skip
from sure import expect
from httpretty import HTTPretty
@skip
def test_http_passthrough():
url = 'http://httpbin.org/status/200'
response1 = requests.get(url)
response1 = requests.get(url, stream=True)
HTTPretty.enable()
HTTPretty.register_uri(HTTPretty.GET,... |
from SPARQLWrapper import SPARQLWrapper, JSON
import requests
import re
import os
import os.path
import time
import sys
FINTO_ENDPOINT='http://api.dev.finto.fi/sparql'
FINNA_API_SEARCH='https://api.finna.fi/v1/search'
lang = sys.argv[1]
LANGMAP = {
'fi': 'fin',
'sv': 'swe',
'en': 'eng'
}
def row_to_concept(row):
... |
from django.db import models
class Profil(models.Model):
awal = ''
PILIHAN_JENJANG = (
(awal, '----'),
('Pertama', 'Perekayasa Pertama'),
('Muda', 'Perekayasa Muda'),
('Madya', 'Perekayasa Madya'),
('Utama', 'Perekayasa Utama'),
)
nip = models.CharField(max_length... |
import sys, os, os.path, re, subprocess, datetime, multiprocessing.pool
import dns.reversename, dns.resolver
import dateutil.parser, dateutil.tz
import idna
import psutil
from dns_update import get_dns_zones, build_tlsa_record, get_custom_dns_config, get_secondary_dns, get_custom_dns_record
from web_update import get_w... |
from colab.plugins.utils.proxy_data_api import ProxyDataAPI
class JenkinsDataAPI(ProxyDataAPI):
def fetch_data(self):
pass |
"""Library for performing speech recognition with the Google Speech Recognition API."""
__author__ = 'Anthony Zhang (Uberi)'
__version__ = '1.0.4'
__license__ = 'BSD'
import io, subprocess, wave, shutil
import math, audioop, collections
import json, urllib.request
class AudioSource(object):
def __init__(self):
... |
from ftw.upgrade import UpgradeStep
from plone import api
class AddLanguageIndex(UpgradeStep):
"""Add Language index."""
def __call__(self):
self.install_upgrade_profile()
ct = api.portal.get_tool("portal_catalog")
survey_results = ct(portal_type="euphorie.survey")
for brain in s... |
"""Test API for Zenodo and GitHub integration."""
from __future__ import absolute_import, print_function
from contextlib import contextmanager
from copy import deepcopy
import pytest
from flask import current_app
from invenio_accounts.models import User
from invenio_github.models import Release, ReleaseStatus, Reposito... |
"""sdist tests"""
import os
import shutil
import sys
import tempfile
import unittest
import urllib
import unicodedata
import posixpath
from StringIO import StringIO
from setuptools.command.sdist import sdist
from setuptools.command.egg_info import manifest_maker
from setuptools.dist import Distribution
SETUP_ATTRS = {
... |
import os
from setuptools import setup
from subprocess import call
from sys import platform, argv
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
SCRIPTS = ["src/bg_daemon/background_daemon.py"]
if (all([e not in argv for e in ['egg_info', 'sdist', 'register']]) and
platform ... |
"""
Stateful module base class and interface description.
All stateful Python modules
- Get Skype4Py Skype instance on init - have full control over Skype and
thus are not limited to !command handlers
- Reside in the some modules/ folder as UNIX script modules
- Have .py extension and be valid... |
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import (
scoped_session,
sessionmaker,
)
from zope.sqlalchemy import ZopeTransactionExtension
import tornado.web
from handlers.index import IndexHandler
from handlers.sensors import SensorsHandler
import logging
logging.getLogger().... |
"""
***************************************************************************
v_univar.py
---------------------
Date : December 2012
Copyright : (C) 2012 by Victor Olaya
Email : volayaf at gmail dot com
*****************************************************... |
import sys, re, os
import logging
import GrubConf
class LiloImage(object):
def __init__(self, lines, path):
self.reset(lines, path)
def __repr__(self):
return ("title: %s\n"
" root: %s\n"
" kernel: %s\n"
" args: %s\n"
" initrd: ... |
import os
import sys
this_dir = os.path.dirname(os.path.abspath(__file__))
trunk_dir = os.path.split(this_dir)[0]
sys.path.insert(0,trunk_dir)
from ikol.dbregister import DataBase
from ikol import var
if os.path.exists(var.DB_PATH):
os.remove(var.DB_PATH)
DB = DataBase(var.DB_PATH)
DB.insertPlaylist("loLWOCl7nlk","... |
extensions = [
]
templates_path = ['_templates']
source_suffix = '.rst'
master_doc = 'index'
project = 'TrinityX'
copyright = '2020, ClusterVision Solutions BV'
author = 'ClusterVision Solutions BV'
version = '12'
release = '12.0'
language = None
exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store', 'README.rst']
pyg... |
TESTS = {
"Level_1": [
{
"input": [1, 2, 3],
"answer": 2,
"explanation": "3-1=2"
},
{
"input": [5, -5],
"answer": 10,
"explanation": "5-(-5)=10"
},
{
"input": [10.2, -2.2, 0, 1.1, 0.5],
... |
from socket import *
from ftplib import FTP
import ftplib
import socket
import thread
import time
import sys
import codecs
import os
reload(sys)
sys.setdefaultencoding( "utf-8" )
class ClientMessage():
#设置用户名密码
def setUsrANDPwd(self,usr,pwd):
self.usr=usr
self.pwd=pwd
#设置目标用户
def setToUs... |
import SocketServer
import re, binascii
import os, stat, os.path, mimetypes, urllib, time
from pygopherd import handlers, protocols, GopherExceptions
from pygopherd.protocols.base import BaseGopherProtocol
import pygopherd.version
import cgi
class HTTPProtocol(BaseGopherProtocol):
def canhandlerequest(self):
... |
"""
End-to-end tests for mypmirun
"""
import os
import logging
logging.basicConfig(level=logging.DEBUG)
from pmi_utils import PMITest
from vsc.utils.affinity import sched_getaffinity, sched_setaffinity
class TaskPrologEnd2End(PMITest):
def setUp(self):
"""Prepare to run test."""
super(TaskPrologEnd2... |
from fabric.api import local
def html():
local('hovercraft -t ./sixfeetup_hovercraft formation_flask.rst ./build/') |
import xbmcaddon
import xbmcgui
import xbmcvfs
import datetime
import os
from libs.vpnproviders import removeGeneratedFiles, cleanPassFiles, providers, usesUserKeys, usesMultipleKeys, getUserKeys
from libs.vpnproviders import getUserCerts, getVPNDisplay, getVPNLocation, removeDownloadedFiles, isAlternative, resetAltern... |
"""
uds.warnings
~~~~~~~~~~~~
:copyright: Copyright (c) 2015, National Institute of Information and Communications Technology.All rights reserved.
:license: GPL2, see LICENSE for more details.
"""
import warnings
def deprecated(func):
"""This is a decorator which can be used to mark functions
as deprecated. It ... |
__author__ = 'dako'
class SessionHelper:
def __init__(self, app):
self.app = app
def login(self, username, password):
wd = self.app.wd
self.app.open_home_page()
wd.find_element_by_name("user").click()
wd.find_element_by_name("user").clear()
wd.find_element_by_name... |
from time import gmtime, strftime
import ephem
import wx.calendar
class App(wx.App):
def OnInit(self):
self.frame = MyFrame("Lunacy", (50, 60), (640, 220))
self.frame.Show()
self.SetTopWindow(self.frame)
return True
class MyFrame(wx.Frame):
def __init__(self, title, pos, size):
wx.Frame.__init__(self, None,... |
from pluginInterfaces import PluginFit, Parameter,leastsqFit
import numpy as np
class PluginFitThreeBodyBeta(PluginFit):
def __init__(self):
pass
def fit(self,array,errarray,param,xmin=0,xmax=0, fitAxes=[]):
"""return the data that is needed for plotting the fitting result"""
"""0...a, 1...xc,... |
""" sha1Hash_test.py
Unit tests for sha1.py
"""
from crypto.hash.sha1Hash import SHA1
import unittest
import struct
assert struct.calcsize('!IIIII') == 20, '5 integers should be 20 bytes'
class SHA1_FIPS180_TestCases(unittest.TestCase):
""" SHA-1 tests from FIPS180-1 Appendix A, B and C """
def testFIPS18... |
__requires__ = 'kartograph.py==0.6.8'
import sys
from pkg_resources import load_entry_point
if __name__ == '__main__':
sys.exit(
load_entry_point('kartograph.py==0.6.8', 'console_scripts', 'kartograph')()
) |
from wxPython.wx import *
import os
import datetime
from objects.emprunt import Emprunt
from popups.members import AddMemberPanel, ShowMembersPanel
class CheckoutPopup(wxDialog):
def __init__(self, parent):
self.parent=parent
wxDialog.__init__(self, parent,-1,"Check out items")
self.mastersi... |
from datetime import *
from Tweetstream import *
from UserAnalyser import *
from TimeAnalyser import *
import math
import sys
import pickle
def load_list(filein):
d = dict()
for l in filein:
l = eval(l)
d[l[0]] = l[1]
return d
if __name__ == "__main__":
follow = load_list(open(sys.argv[5], 'r'))
keywords = ope... |
class Solution(object):
def setZeroes(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: void Do not return anything, modify matrix in-place instead.
"""
width,height = len(matrix[0]),len(matrix)
for i in xrange(height):
foundzero = False
... |
"""
core/api/serializers.py is the module for core model api data serializers
"""
from django.contrib.auth.models import User, Permission
from rest_framework import serializers
from core.models import (Product, ProductCategory, UnitOfMeasurement, UOMCategory, CompanyCategory, Company,
Curre... |
def hamming(s,t):
dist = 0
for x in range(len(s)):
if s[x]!=t[x]:
dist+=1
return dist |
import os
import sys
import time
import difflib
from os import path
from subprocess import Popen, PIPE, STDOUT
already_compiled = set()
def run_test(testname, testcode, compiled):
stdin = b''
if path.isfile(testname + '.tst'):
with open(testname + '.tst', 'rb') as stdinfile:
stdin = stdinfil... |
"""
Windows Process Control
winprocess.run launches a child process and returns the exit code.
Optionally, it can:
redirect stdin, stdout & stderr to files
run the command as another user
limit the process's running time
control the process window (location, size, window state, desktop)
Works on Windows NT, 200... |
from bs4 import BeautifulSoup
from urllib2 import urlopen
import pandas as pd
pos_idx_map = {
'qb': 2,
'rb': 3,
'wr': 4,
'te': 5,
}
def make_url(pos, wk):
ii = pos_idx_map[pos]
fstr = "http://fantasydata.com/nfl-stats/nfl-fantasy-football-stats.aspx?fs=1&stype=0&sn=1&w=%s&s=&t=0&p=%s&st=FantasyP... |
"""
Copyright 2015 SmartBear Software
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/licenses/LICENSE-2.0
Unless required by applicable law or agreed to... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.