content stringlengths 4 20k |
|---|
import imp
import sys
import sublime_plugin
from .colorsublime import commands
from .colorsublime import status
from .colorsublime import logger
NO_SELECTION = -1
# Make sure all dependencies are reloaded on upgrade
reloader_path = 'Colorsublime.colorsublime.reloader'
if reloader_path in sys.modules:
imp.reload... |
class BaseUrls(object):
"""
Wrapper around a map of URL endpoints for each K8sObject type.
"""
default_api_version = "v1"
default_apps_version = "v1alpha1"
default_autoscaling_version = "v1"
default_batch_version = "v1"
default_extensions_version = "v1beta1"
default_cron_version = ... |
from datetime import datetime, date, time, timedelta
import random
import sys
import os
import json
# Constants
creator_id = [1, 3, 4, 7, 8] # Pks of users fixture-loader, "segreteria", "rappresentanteSN", "referente" and "galileiano"
start_time = [time(14, 0), time(16, 0), time(18, 0)]
class Event:
# Status ch... |
from xml.sax.saxutils import escape
from screenplain.types import *
from screenplain.richstring import RichString
from screenplain.richstring import Bold, Italic, Underline
style_names = {
Bold: 'Bold',
Italic: 'Italic',
Underline: 'Underline',
}
def _write_text_element(out, styles, text):
style_va... |
# coding=UTF-8
import sys
import json
from six import StringIO
from doit import reporter
from doit.task import Task
from doit.exceptions import CatchedException
class TestConsoleReporter(object):
def test_initialize(self):
rep = reporter.ConsoleReporter(StringIO(), {})
rep.initialize([Task("t_n... |
#!/usr/bin/python
#############################################
# show_block_details.py #
# #
# A simple python program that retrieves #
# btier block placement metadata #
# And optionally stores the data in sqlite #
# EXAMPLE CODE ... |
# -*- coding: utf-8 -*-
"""
Created on Wed Nov 23 18:45:19 2016
@author: aarora
"""
import os
import csv
from bs4 import BeautifulSoup
from common import globals as glob
# Map colors
### GRAYSCALE
# colors = ["#ffffff", "#f0f0f0", "#d9d9d9", "#bdbdbd", "#969696", "#737373", "#525252", "#252525"]
# colors = ["#f7f7f7",... |
from __future__ import absolute_import, division, print_function, unicode_literals
import getpass
import os
import re
import socket
import time
from builtins import object, open, str
from pants import version
from pants.base.build_environment import get_buildroot, get_scm
from pants.util.collections_abc_backport impo... |
"""
Created on Tue Aug 2 09:55:43 2016
@author: Miles
"""
import numpy as np
import matplotlib.pyplot as plt
import dave.fileio.mastio as mastio
import dave.fileio.tpf as tpf
import dave.fileio.kplrfits as kplrfits
import dave.misc.noise as noise
import gapfill
import pdb
def getData(epic, campaign):
"""Obtains... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
@author: Ivan Fontarensky
@license: GNU General Public License 3.0
@contact: ivan.fontarensky_at_gmail.com
"""
__author__ = 'ifontarensky'
__docformat__ = 'restructuredtext'
__version__ = '1.0'
from PyQt4 import QtCore, QtGui
from PyQt4.QtCore import... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Simple example using convolutional neural network to classify IMDB
sentiment dataset.
References:
- Andrew L. Maas, Raymond E. Daly, Peter T. Pham, Dan Huang, Andrew Y. Ng,
and Christopher Potts. (2011). Learning Word Vectors for Sentiment
Analysis. The 49th... |
"""XPath parsing rules.
To understand how this module works, it is valuable to have a strong
understanding of the `ply <http://www.dabeaz.com/ply/>` module.
"""
from eulxml.xpath import ast
from eulxml.xpath.lexrules import tokens
precedence = (
('left', 'OR_OP'),
('left', 'AND_OP'),
('left', 'EQUAL_OP')... |
from datetime import date, time, datetime
from django.conf import settings
from django.db.models.fields import NOT_PROVIDED
from django.db.models.sql import aggregates as sqlaggregates
from django.db.models.sql.compiler import SQLCompiler
from django.db.models.sql.constants import LOOKUP_SEP, MULTI, SINGLE
from d... |
#!/usr/bin/python
# Try and create two VMs and a private network betwene the two
import sys
from XmTestLib import *
from XmTestLib.network_utils import *
# Create two domains (default XmTestDomain, with our ramdisk)
try:
domain1 = XmTestDomain()
console1 = domain1.start()
domain2 = XmTestDomain()
co... |
"""Test the Hirshfeld Method in cclib"""
from __future__ import print_function
import sys
import os
import logging
import unittest
import numpy
from cclib.method import Hirshfeld, volume
from cclib.parser import Psi4
from cclib.io import ccread
from cclib.method.calculationmethod import MissingAttributeError
from ... |
import urllib2
from lxml import etree
def load_url(url):
req = urllib2.Request(url)
return urllib2.urlopen(req)
def xss_tests():
raise Exception('disabled')
attacks_url = 'http://ha.ckers.org/xssAttacks.xml'
doc = etree.parse(load_url(attacks_url))
for attack in doc.iter("attack"):
n... |
"""REANA command line interface client."""
import logging
import os
import sys
import click
from urllib3 import disable_warnings
from reana_client.cli import workflow, files, ping, secrets, quotas
from reana_client.utils import get_api_url
DEBUG_LOG_FORMAT = (
"[%(asctime)s] p%(process)s "
"{%(pathname)s:%(l... |
from cycler import cycler
from scipy.misc import derivative
import math as math
import pylab
import numpy
def g(x):
return derivative(newtonIteration, x, dx=1e-10)
def gPrime(x):
return derivative(g, x, dx=1e-10)
def fPrime(x):
return 3*math.pow(x, 2)
def f(x):
return math.pow(x, 3) - 5
def newton... |
""" Simple exporter that convert a notebook from Legacy Python 2 to Python 3
"""
from nbconvert.exporters.notebook import NotebookExporter
#!/usr/bin/env python3
"""
To run: python3 nb2to3.py notebook-or-directory
"""
# Authors: Thomas Kluyver, Fernando Perez
# See: https://gist.github.com/takluyver/c8839593c615bb2... |
# -*- coding: utf-8 -*-
from .store import store
from MySQLdb import IntegrityError
from ORZ import OrzField, OrzBase
from ORZ.klass_init import OrzMeta
from datetime import datetime
__all__ = []
__dict__ = []
class ModelField(OrzField):
def __init__(self, *args, **kwargs):
self.auto_now = kwargs.get('au... |
from flocker.node import BackendDescription, DeployerType
from purestorage_flasharray_flocker_driver import purestorage_blockdevice
def api_factory(cluster_id, **kwargs):
return purestorage_blockdevice.pure_from_configuration(
cluster_id=cluster_id,
pure_ip=kwargs.get('pure_ip'),
pure_api_... |
import grp
import platform
class Group(object):
"""
This is a generic Group manipulation class that is subclassed
based on platform.
A subclass may wish to override the following action methods:-
- group_del()
- group_add()
- group_mod()
All subclasses MUST define platform and d... |
import unittest
import numpy
import six
import chainer
from chainer import cuda
from chainer import functions
from chainer import gradient_check
from chainer import testing
from chainer.testing import attr
from chainer.testing import condition
class TestLocalResponseNormalization(unittest.TestCase):
def setUp(... |
import functools
import logging
from operator import or_, and_
from django.db.models import Q
from django.core.exceptions import FieldError
from django.conf import settings
from django.utils.encoding import smart_unicode
from synnefo_admin.admin.utils import model_dict
from synnefo_admin import admin_settings
sign =... |
from __future__ import unicode_literals
from indico.core.db import db
from indico.modules.events.cloning import EventCloner
from indico.modules.vc import VCRoomEventAssociation, VCRoomLinkType, get_vc_plugins
from indico.util.i18n import _
class VCCloner(EventCloner):
name = 'vc'
friendly_name = _('Videoconf... |
import ddt
import mock
from six.moves import urllib
from cinder import context
from cinder import exception
from cinder.tests.unit import fake_constants as fake
from cinder.tests.unit import fake_volume
from cinder.tests.unit.volume.drivers.dell_emc import scaleio
from cinder.tests.unit.volume.drivers.dell_emc.scaleio... |
import sys
from ase.build import molecule, fcc111, add_adsorbate
from ase.optimize import QuasiNewton
from ase.constraints import FixAtoms
from ase.calculators.emt import EMT
from ase.vibrations import Vibrations
sys.path.append("../..")
from __init__ import AnharmonicModes
slab = fcc111('Al', size=(2, 2, 2), vacuu... |
from __future__ import unicode_literals
from moto.core.responses import BaseResponse
from moto.ec2.utils import filters_from_querystring, \
network_acl_ids_from_querystring
class NetworkACLs(BaseResponse):
def create_network_acl(self):
vpc_id = self.querystring.get('VpcId')[0]
network_acl = s... |
from __future__ import absolute_import
from __future__ import print_function
import os.path
import signal
from twisted.application import service
from twisted.application.internet import ClientService
from twisted.application.internet import backoffPolicy
from twisted.cred import credentials
from twisted.internet imp... |
#!/usr/bin/env python
# vim: tabstop=4 shiftwidth=4 softtabstop=4 noexpandtab
#
# read FNT font files from Dune II
from struct import *
import sys
from save_pictures import *
def extract_fnt(filename):
with open(filename, 'rb') as fnt_file:
fnt = fnt_file.read()
(size, sig, params, offsets, width_list, char_data... |
# -*- coding: utf-8 -*-
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.lines as mlines
data_for_plots=np.load("../Daten/vgg_3_eps_AE_loss.npy",encoding='latin1')
#[epoch, test value, train value, name, train epoch, ylabel]
plot_in_range_array=[[114,200],[95,113]]
colors_array=["blue","red"]
l... |
#!/usr/bin/env python
# -*- coding: utf-8
from mosql import util
# Backup things in util
backup = {k: getattr(util, k) for k in dir(util)}
# Load patches
import mosql.mysql
import mosql.sqlite
# Restore backup
for k in backup:
setattr(util, k, backup[k])
class Patcher(object):
"""This class implements the... |
"""Two new tables: analyses and worker_results.
Revision ID: 963d3d929b19
Revises: ea55c632ae8d
Create Date: 2016-05-09 08:58:34.603632
"""
# revision identifiers, used by Alembic.
revision = '963d3d929b19'
down_revision = 'ea55c632ae8d'
branch_labels = None
depends_on = None
from alembic import op
import sqlalchem... |
"""
Support for MQTT cover devices.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/cover.mqtt/
"""
import asyncio
import logging
import voluptuous as vol
from homeassistant.core import callback
import homeassistant.components.mqtt as mqtt
from homeassi... |
# -*- coding: utf-8 -*-
import re
import inspect
import datetime
from operator import itemgetter
from django.utils import importlib
from django.core.urlresolvers import reverse
from django import forms
from mptt.models import MPTTModel
from qualitio.core.utils import success, failed
from qualitio.core import BaseFor... |
"""
Tests for contentstore/views/user.py.
"""
import json
from .utils import CourseTestCase
from django.contrib.auth.models import User, Group
from auth.authz import get_course_groupname_for_role
from student.models import CourseEnrollment
from xmodule.modulestore.django import loc_mapper
class UsersTestCase(CourseTe... |
import hashlib
import sys
import os
from random import SystemRandom
import base64
import hmac
if len(sys.argv) < 2:
sys.stderr.write('Please include username as an argument.\n')
sys.exit(0)
username = sys.argv[1]
#This uses os.urandom() underneath
cryptogen = SystemRandom()
#Create 16 byte hex salt
salt_seq... |
#!/usr/bin/env python
# vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4
# -*- mode: python; indent-tabs-mode nil; tab-width 4; python-indent 4; -*-
# -#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#
# these are system modules
import sys
# these are my local ones
from env import gid... |
"""
WSGI middleware for OpenStack API controllers.
"""
from oslo_log import log as logging
from oslo_service import wsgi as base_wsgi
import routes
from cinder.api.openstack import wsgi
from cinder.i18n import _
LOG = logging.getLogger(__name__)
class APIMapper(routes.Mapper):
def routematch(self, url=None, e... |
# This example shows how to stop experiments that hit the systems performance to heavy
# - init_knobs
# - default_knobs
# - full stop or single stop of experiments
#
name = "CrowdNav-Exceptions"
execution_strategy = {
"type": "step_explorer",
"ignore_first_n_results": 100,
"sample_size": 100,
"knobs": ... |
import contextlib
import importlib
import logging
import os
import pathlib
import sys
import tempfile
import unittest
from unittest.mock import patch
import pytest
from airflow.configuration import conf
from tests.test_utils.config import conf_vars
SETTINGS_FILE_VALID = """
LOGGING_CONFIG = {
'version': 1,
'... |
from __future__ import print_function
import tensorflow as tf
import numpy as np
import os
import json
import collections
from bayou.models.core.model import Model
from bayou.models.core.utils import CHILD_EDGE, SIBLING_EDGE
from bayou.models.core.utils import read_config
MAX_GEN_UNTIL_STOP = 20
MAX_AST_DEPTH = 5
... |
import math
import random
import time
import threading
from mince import Colour
# Easing Functions
def linear(edge0, edge1, weight):
''' Linear interpolation '''
if weight < 0:
weight = 0.0
elif weight > 1:
weight = 1.0
return edge0 + ((edge1 - edge0) * float(weight))
def smooth_step(e... |
"""This file allows the bots to be easily configure and run the tests.
Running this script requires passing --config-path with a path to a config file
of the following structure:
[data_files]
passwords_path=<path to a file with passwords>
[binaries]
chrome-path=<chrome binary path>
chromedriver-path=<chrome ... |
from apikit.args import BOOL_TRUISH
from werkzeug.datastructures import MultiDict
from aleph.model import Entity
from aleph.text import string_value
class QueryState(object):
"""Hold state for common query parameters."""
def __init__(self, args, authz, limit=None):
if not isinstance(args, MultiDict)... |
import os
import os.path
import glob
import copy
import subprocess
from bouwer.plugin import *
from bouwer.builder import *
from bouwer.config import *
import bouwer.util
class Object(Plugin):
"""
Build an executable object for a program.
"""
def config_input(self):
""" Configuration input ite... |
"""
Tests for course dates fragment.
"""
from datetime import datetime, timedelta
import six
from django.urls import reverse
from student.tests.factories import UserFactory
from xmodule.modulestore import ModuleStoreEnum
from xmodule.modulestore.tests.django_utils import ModuleStoreTestCase
from xmodule.modulestore... |
# -*- coding: utf-8 -*-
from __future__ import print_function
from util import *
from pattern import de
#-------------------------------------------------------------------------
class TestInflection(unittest.TestCase):
def setUp(self):
pass
def test_gender(self):
# Assert der Hund => MA... |
# -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import DataMigration
from django.db import models
class Migration(DataMigration):
def forwards(self, orm):
"Write your forwards methods here."
# Note: Remember to use orm['appname.ModelName'] rather than "from appname.mo... |
"""mysite 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')
C... |
from hydrocarbon.settings.base import *
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = None # WILL BE OVERRIDED IN PRIVATE SETTINGS
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False
TEMPLATE_DEBUG = False
# ALLOWED HOSTS
ALLOWED_HOSTS = ['herocomics.kr'... |
import unittest
from kona.linalg.memory import KonaMemory
from kona.linalg.common import objective_value
from kona.linalg.vectors.composite import ReducedKKTVector
from kona.linalg.vectors.composite import CompositePrimalVector
from kona.algorithms.util.merit import AugmentedLagrangian
from kona.examples import Sella... |
import unittest
import psycopg2
import psycopg2.extensions
import psycopg2.extras
from testutils import ConnectingTestCase, slow
class ConnectionStub(object):
"""A `connection` wrapper allowing analysis of the `poll()` calls."""
def __init__(self, conn):
self.conn = conn
self.polls = []
... |
import json
import requests
import re
import os
import requests
from bs4 import BeautifulSoup
from datanator_query_python.util import mongo_util
# from datanator_query_python.query import query_taxon_tree
# from pymongo.collation import Collation, CollationStrength
import datanator.config.core
class KeggOrgCode(mongo... |
from .base import *
import dj_database_url
PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
DEBUG = False
ALLOWED_HOSTS = ['*']
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'tambox',
'USER': 'tambox',
'PASSWORD': '... |
"""
mtxPython - A framework to create matrix games.
Copyright (C) 2016 Tobias Stampfl <<EMAIL>>
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 in version 3 of the License.
T... |
#!/usr/bin/env python3
import os
from setuptools import setup
import RecordSheet
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(
name="RecordSheet",
version=RecordSheet.__version__,
author=RecordSheet.__author__,
author_email="<EMAIL>",
description=("... |
# -*- coding: utf-8 -*-
"""
Catch-up TV & More
Copyright (C) 2016 SylvainCecchetto
This file is part of Catch-up TV & More.
Catch-up TV & More 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 Foundat... |
class Solution:
# @param words, a list of strings
# @param L, an integer
# @return a list of strings
def spaces(self, num):
return ' '*num
def fullJustify(self, words, L):
line = []
output = []
linelength = 0
if (len(words) == 0):
ret... |
import pytest
import grrrrit
from grrrrit import IncludeOwner
@pytest.fixture()
def event():
return {
"uploader": {"name": "UserName"},
"change": {
"project": "test",
"branch": "master",
"subject": "test",
"number": "2001",
... |
import glob, os, sys
import numpy as np
from random import*
import matplotlib.pyplot as plt
import matplotlib.cm as cmx
import matplotlib.colors as colors
def get_rand_color(val):
h,s,v = random()*6, 0.5, 243.2
colors = []
for i in range(val):
h += 3.75#3.708
tmp = ((v, v-v*s*abs(1-h%2), v-... |
"""Test .dist-info style distributions.
"""
import os
import shutil
import tempfile
import unittest
import textwrap
try:
import ast
except:
pass
import pkg_resources
from setuptools.tests.py26compat import skipIf
def DALS(s):
"dedent and left-strip"
return textwrap.dedent(s).lstri... |
"""
polib setup script.
"""
__author__ = 'David Jean Louis <<EMAIL>>'
from distutils.core import setup
import codecs
import polib
author_data = __author__.split(' ')
maintainer = ' '.join(author_data[0:-1])
maintainer_email = author_data[-1]
desc = 'A library to manipulate gettext files (po and mo files).'
if poli... |
import numpy as np
import nibabel as nb
import os
import sys
import nighresjava
from ..io import load_volume, save_volume
from ..utils import _output_dir_4saving, _fname_4saving, \
_check_topology_lut_dir, _check_available_memory
def background_estimation(image, distribution='exponential', ratio=1... |
import os
import glob
import sys
import shutil
import pysam
from bcbio.pipeline import config_utils
from bcbio.distributed.transaction import file_transaction, tx_tmpdir
from bcbio.utils import (safe_makedir, file_exists)
from bcbio.provenance import do
from bcbio import utils
from bcbio.log import logger
from bcbio.p... |
# coding=UTF-8
import os
import tec_year_catagoy
import tec_teach_set
import tec_constant
import tec_readme
# 小集零时目录的标题
valid_file_names = set()
# 1. 检查小集的模版是否正确
def check_teachsets_valid(root_path):
paths = os.listdir(root_path)
is_all_valid = True
for compent in paths:
# 过滤掉隐藏文件
if c... |
#! python
# -*- coding: utf-8 -*-
"""
@author: Adam Deller, UNIVERSITY COLLEGE LONDON.
Quantum defects values for Helium (4), labeled as [S][L][J].
High Precision Theory of Atomic Helium
G. W. F. Drake
Physica Scripta, Vol. T83 83-92 (1999)
https://dx.doi.org/10.1238/Physica.Topical.083a00083
"""
qua... |
"""
Copyright (c) 2015 SONATA-NFV
ALL RIGHTS RESERVED.
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... |
"""Integration Tests for Camper+ App"""
import os
from datetime import datetime
import unittest
from unittest.mock import patch, Mock
import camperapp
from camperapp import app, db
from camperapp.models import CampEvent, CampGroup, Camper, User, Role, Parent
from config import basedir
from flask_login import login_use... |
from ....const import GRAMPS_LOCALE as glocale
_ = glocale.translation.gettext
#-------------------------------------------------------------------------
#
# Gramps modules
#
#-------------------------------------------------------------------------
from .. import Rule
#-----------------------------------------------... |
# coding=utf-8
"""
InaSAFE Disaster risk assessment tool developed by AusAid -
**Impact Function Base Class**
Contact : <EMAIL>
.. note:: This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; ei... |
import os
import numpy as np
from traits.api import Undefined
from hyperspy.misc.array_tools import sarray2dict
# Plugin characteristics
# ----------------------
format_name = 'MRC'
description = ''
full_support = False
# Recognised file extension
file_extensions = ['mrc', 'MRC', 'ALI', 'ali']
default_extension = 0... |
"""
Monitors home energy use for the ELIQ Online service.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/sensor.eliqonline/
"""
from datetime import timedelta
import logging
import voluptuous as vol
from homeassistant.components.sensor import PLATFORM_... |
from weboob.capabilities.bank import Account
from weboob.deprecated.browser import Browser, BrowserIncorrectPassword
from .pages import LoginPage, SummaryPage, UselessPage, TransactionSearchPage, TransactionsPage, TransactionsCsvPage
__all__ = ['CitelisBrowser']
class CitelisBrowser(Browser):
PROTOCOL = 'https... |
import sys
def delayed_plugin(module, fname, package='divisi2.algorithms'):
modname = package+'.'+module
def plugin_method(*args, **kw):
"""
Sorry, this meta-code won't be too informative. If you're seeing this in
IPython's ?? mode, try a single question mark instead.
"""
... |
from openslide import OpenSlide
from flask_restful import Resource
from bson.objectid import ObjectId
from flask import Response, request, session
from PIL import Image
import os, gridfs, cStringIO
from utils.deepzoom import PILBytesIO
from bson.json_util import dumps
from utils.auth import requires_auth
class Auth(Re... |
import gmsh
import math
model = gmsh.model
factory = model.occ
gmsh.initialize()
gmsh.option.setNumber("General.Terminal", 1)
model.add("spline")
for i in range(1, 11):
factory.addPoint(i, math.sin(i/9.*2.*math.pi), 0, 0.1, i)
factory.addSpline(range(1, 11), 1)
factory.addBSpline(range(1, 11), 2)
factory.addBe... |
"""
Sol performance module
Contains a boat performance evaluator for sailonline.org boats
"""
__author__ = "J.R. Versteegh"
__copyright__ = "Copyright 2011, J.R. Versteegh"
__contact__ = "<EMAIL>"
__version__ = "0.1"
__license__ = "GPLv3, No Warranty. See 'LICENSE'"
from bisect import bisect
import math
import numpy ... |
import os
import socket
import csv
import tempfile
import imp
from subprocess import *
from fabric.api import task, warn, put, puts, get, local, run, execute, \
settings, abort, hosts, env, runs_once, parallel
import config
from internalutil import _list, mkdir_p
from filefinder import get_testid_file_list
## Crea... |
"""A wrapped MinitaurGymEnv with a built-in controller."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from gym import spaces
import numpy as np
import gin
from pybullet_envs.minitaur.agents.trajectory_generator import tg_simple
from pybullet_envs.minita... |
from django.shortcuts import render, HttpResponseRedirect, Http404
from django.conf import settings
# Create your views here.
from .forms import EmailForm, JoinForm
from .models import Join
def get_ip(request):
try:
x_forward = request.META.get("HTTP_X_FORWARDED_FOR")
if x_forward:
ip = x_forward.split(",")[0... |
"""
kppvh - performs some checking on PGDP or Project Gutenberg files.
"""
import re
import collections
from itertools import count, groupby
import datetime
from collections import Counter
class MiscChecks(object):
def guess_language(self, myfile):
# Look for strings like "Note de transcription" or
... |
import pytest
import numpy as np
from ..interpolation import SteffenInterpolator
def test_extrapolation_raise_by_default():
xi = np.arange(0, 10, 0.5)
yi = 3 * xi
stfi = SteffenInterpolator(xi, yi)
with pytest.raises(ValueError):
stfi(200)
stfi1 = SteffenInterpolator(xi, yi, extrapolat... |
from torch import nn
from torch.nn import functional as F
from ..box_head.roi_box_feature_extractors import ResNet50Conv5ROIFeatureExtractor
from maskrcnn_benchmark.modeling.poolers import Pooler
from maskrcnn_benchmark.layers import Conv2d
from maskrcnn_benchmark.modeling.make_layers import make_conv3x3
class Mask... |
import cython
NULL = 5
_NULL = NULL
def test_sizeof():
"""
>>> test_sizeof()
True
True
True
True
True
"""
x = cython.declare(cython.bint)
print(cython.sizeof(x) == cython.sizeof(cython.bint))
print(cython.sizeof(cython.char) <= cython.sizeof(cython.short) <= cython.sizeof(c... |
"""module for the visualizations of generic dataquickframes"""
import os
from PyQt5 import QtGui
import pyqtgraph as pg
from . import base
from .. import dpi
from .. import cfg, colors
from .. import plotlist
from ..ui.xyscatter import Ui_XYScatter
from .. import functions as fn
class DQFItem(plotlist.DQFItem):
... |
"""
Shelve extension
================
A storage/query backend for `shelve`_ which is bundled with Python.
:status: stable
:database: any dbm-style database supported by `shelve`_
:dependencies: the Python standard library
:suitable for: "smart" interface to a key/value store, small volume
A "shelf" is a persistent, ... |
"""Test code for data acquisition."""
from pyfusion.test.tests import PfTestBase
from pyfusion.data.base import BaseData
from pyfusion.acquisition.base import BaseAcquisition
from pyfusion.conf.utils import get_config_as_dict, import_from_str
from pyfusion.utils.debug import equal_except_for
from pyfusion.acquisition.... |
"""Stubouts, mocks and fixtures for the test suite."""
import pickle
import random
from nova.openstack.common import jsonutils
from nova import test
import nova.tests.image.fake
from nova.virt.xenapi import driver as xenapi_conn
from nova.virt.xenapi import fake
from nova.virt.xenapi import vm_utils
from nova.virt.xe... |
from __future__ import absolute_import
import logging
import zlib
from .exceptions import DecodeError
from .packages.six import string_types as basestring, binary_type
log = logging.getLogger(__name__)
class DeflateDecoder(object):
def __init__(self):
self._first_try = True
self._data = binar... |
import errno
import logging
import os
import time
LOG = logging.getLogger(__name__)
WAIT_TIME = 0.01
class _InterProcessLock(object):
"""Lock implementation which allows multiple locks, working around
issues like bugs.debian.org/cgi-bin/bugreport.cgi?bug=632857 and does
not require any cleanup. Since the... |
import os
import posixpath
import re
import shutil
import subprocess
import sys
import tempfile
import textwrap
from collections import namedtuple
import psutil
import pytest
BASE_DIR = posixpath.realpath(posixpath.dirname(posixpath.dirname(__file__)))
_re_coverage_filename = re.compile(r'^\.coverage(\..+)?$')
def... |
#! /usr/bin/env python
#
# Bingo probability calculator
#
# Programming Praxis
# Problem 3
# http://programmingpraxis.com/2009/02/19/bingo/
#
from random import *
import numpy as np
import time
start_time = time.time()
class Card:
def __init__(self):
self.card = np.zeros([5, 5])
self.card[:, 0] = sample(r... |
# -*- coding: utf-8 -*-
from odoo.tests.common import TransactionCase
from odoo.exceptions import UserError
class TestInventory(TransactionCase):
def setUp(self):
super(TestInventory, self).setUp()
self.env.ref('core.goods_category_1').account_id = self.env.ref(
'finance.account_goods... |
from shinken.misc.sorter import hst_srv_sort, last_state_change_earlier
# Will be populated by the UI with it's own value
app = None
import time
import re
def get_page():
app.bottle.redirect("/all?search=isnot:UP isnot:OK isnot:PENDING isnot:ACK isnot:DOWNTIME bp:>0")
def get_all():
user = app.bottle.requ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
######################################################
# Modificado por Francisco José Rodríguez Bogado
######################################################
# Código para simular un daemon sacado de:
# http://homepage.hispeed.ch/py430/python/daemon.py
###################... |
#!/usr/bin/python -tt
# -*- coding: utf-8 -*-
'''
Copyright 2014-2015 Teppo Perä
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
Un... |
import logging
from io import BytesIO
import six
from six.moves import cPickle as pickle
try:
long_type = long # noqa
except NameError:
long_type = None
FLAG_BYTES = 0
FLAG_PICKLE = 1 << 0
FLAG_INTEGER = 1 << 1
FLAG_LONG = 1 << 2
FLAG_COMPRESSED = 1 << 3 # unused, to main compatability with python-memcache... |
# -*- coding: utf-8 -*-
# Created on 2015/10/27
import logging
import json
from datetime import datetime
import tornado
import tornado.httpserver
import tornado.ioloop
import tornado.options
import tornado.web
import tornado.gen
import tornado.httpclient
from tornado.web import RequestHandler
from tornado.options im... |
import os
from datetime import datetime, timedelta
from shutil import rmtree
from uuid import uuid4
from zipfile import ZipFile
from youtube_dl import YoutubeDL
from update import DownloadUpdate, PlaylistUpdate, ZipUpdate
class Download:
completed = False
error = False
zipped = False
zipping = Fals... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.