content stringlengths 4 20k |
|---|
'''
(c) 2011, 2012 Georgia Tech Research Corporation
This source code is released under the New BSD license. Please see
http://wiki.quantsoftware.org/index.php?title=QSTK_License
for license details.
Created on Jan, 13, 2013
@author: Grahesh
@summary: Price Dropping Event Study
'''
import pandas
from qstkutil imp... |
"""This script is used to synthesize generated parts of this library."""
import synthtool as s
import synthtool.gcp as gcp
import synthtool.languages.ruby as ruby
import logging
logging.basicConfig(level=logging.DEBUG)
gapic = gcp.GAPICMicrogenerator()
library = gapic.ruby_library(
"appengine", "v1",
proto_p... |
from openerp.osv import osv, fields
class res_partner(osv.osv):
_inherit = 'res.partner'
_columns = \
{ 'payment_block' : fields.boolean
( 'Payment Block'
, help="Do not include credit/debit of this account in payment selection"
)
, 'payment_obey_bala... |
"""Tests for the pvpc_hourly_pricing sensor component."""
from datetime import datetime, timedelta
import logging
from unittest.mock import patch
from pytz import timezone
from homeassistant.components.pvpc_hourly_pricing import ATTR_TARIFF, DOMAIN
from homeassistant.const import CONF_NAME
from homeassistant.core imp... |
import designate.tests
from designate.backend.agent_backend import impl_fake
from designate.tests.unit.agent import backends
class FakeAgentBackendTestCase(designate.tests.TestCase):
def setUp(self):
super(FakeAgentBackendTestCase, self).setUp()
self.CONF.set_override('listen', ['0.0.0.0:0'], 'se... |
from functools import wraps
def setupmethod(f):
"""Use this decorator for methods that change the internal state / parameters
of the system, such that the eigenstates have to be recalculated.
This method will reset the 'data was changed' flag"""
@wraps(f)
def decorated(self, *ops, **kwops):
... |
"""
Extends top.py from psutils/ to make a benchmark.
Author: Maik Roeder <EMAIL>
"""
"""
A clone of top / htop.
Author: Giampaolo Rodola' <<EMAIL>>
"""
import os
import sys
if os.name != 'posix':
sys.exit('platform not supported')
import time
from datetime import datetime, timedelta
import psutil
BENCHMARK = ... |
# -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding field 'UserProfile.fan_page_access_token'
db.add_column('accounts_userprofile', 'fan_page_access_to... |
__version__ = "0.10.5"
version = __version__ # backward compat. |
from nose.tools import eq_
from ycm.test_utils import MockVimModule
vim_mock = MockVimModule()
from .. import completion_request
class ConvertCompletionResponseToVimDatas_test:
""" This class tests the
completion_request._ConvertCompletionResponseToVimDatas method """
def _Check( self, completion_data, exp... |
# -*- coding: utf-8 -*-
"""
This test file will verify proper password history enforcement
"""
from datetime import timedelta
from django.test import TestCase
from django.test.utils import override_settings
from django.utils import timezone
from freezegun import freeze_time
from mock import patch
from student.models ... |
#! /usr/bin/env python
from openturns import *
from math import *
TESTPREAMBLE()
RandomGenerator().SetSeed(0)
try :
# Problem parameters
dimension = 3
a = 7.0
b = 0.1
# Reference analytical values
meanTh = a/2
covTh = (b**2 * pi**8) / 18.0 + (b * pi**4) / 5.0 + (a**2) / 8.0 + 1.0 / 2.0
... |
from __future__ import unicode_literals, absolute_import
"""GridFS implementation for Motor, an asynchronous driver for MongoDB."""
import textwrap
import gridfs
import pymongo
import pymongo.errors
from gridfs import grid_file
from motor.core import (AgnosticBaseCursor,
AgnosticCollection,
... |
"""ContainerPackage class"""
from .halo_endpoint import HaloEndpoint
class ContainerPackage(HaloEndpoint):
"""Initializing the ContainerPackage class:
Args:
session (:class:`cloudpassage.HaloSession`): This will define how you
interact with the Halo API, including proxy settings and API ... |
"""CalendarResourceClient simplifies Calendar Resources API calls.
CalendarResourceClient extends gdata.client.GDClient to ease interaction with
the Google Apps Calendar Resources API. These interactions include the ability
to create, retrieve, update, and delete calendar resources in a Google Apps
domain.
"""
__au... |
from . import config
from .config import log
from .config import *
import ldap
import time
import lib389
from lib389 import DirSrv, Entry
from lib389 import utils
from lib389.tools import DirSrvTools
from subprocess import Popen
conn = None
added_entries = None
added_backends = None
def harn_nolog():
conn.conf... |
DEFAULT_KAFKA_PORT = 9092
#: Compression flag value denoting ``gzip`` was used
GZIP = 1
#: Compression flag value denoting ``snappy`` was used
SNAPPY = 2
#: This set denotes the compression schemes currently supported by Kiel
SUPPORTED_COMPRESSION = (None, GZIP, SNAPPY)
CLIENT_ID = "kiel"
#: The "api version" value ... |
# -*- coding: utf-8 -*-
#
# Advanced Emulator Launcher main script file
#
# Copyright (c) 2016-2018 Wintermute0110 <<EMAIL>>
# Portions (c) 2018 Chrisism
# Portions (c) 2010-2015 Angelscry and others
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Publi... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import
import theano
import theano.tensor as T
from theano.tensor.signal import downsample
from .. import activations, initializations
from ..utils.theano_utils import shared_zeros
from ..layers.core import Layer
class Convolution1D(Layer):
def __init__(se... |
import os
import subprocess
import json
import logging
import math # Required for the math.log function
from commitFile import * # Represents a file
import time
"""
file: repository.py
authors: Ben Grawi <<EMAIL>>, Christoffer Rosen <<EMAIL>>
date: October 2013... |
from typing import Dict, Set
from marshmallow import fields, validate
from polyaxon.contexts import refs as contexts_refs
from polyaxon.lifecycle import V1Statuses
from polyaxon.polyflow.component.base import BaseComponent, BaseComponentSchema
from polyaxon.polyflow.events import EventTriggerSchema, V1EventKind
from ... |
#!/usr/bin/python
'''
This is part of a simplistic Diffie-Hellman key exchange implementation.
For demonstration use only.
github.com/askbow
askbow.com
This file stores prime numbers defined in RFC3526 and (for reference) RFC2409
https://datatracker.ietf.org/doc/rfc3526/?include_text=1
https://www.ietf.org/rfc/rfc240... |
"""Support for ISY994 sensors."""
from typing import Callable, Dict, Union
from pyisy.constants import ISY_VALUE_UNKNOWN
from homeassistant.components.sensor import DOMAIN as SENSOR
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import TEMP_CELSIUS, TEMP_FAHRENHEIT
from homeassistant.he... |
import os
import pytest
from supp.assistant import assist
from supp.project import Project
from .helpers import sp
def tassist(source, pos, project=None, filename=None, debug=False):
debug = debug or os.environ.get('DEBUG')
return assist(project or Project(), source, pos, filename, debug=debug)
def test_si... |
import bpy
def write(fw, mesh_source, image_width, image_height, opacity, face_iter_func):
filepath = fw.__self__.name
fw.__self__.close()
material_solids = [bpy.data.materials.new("uv_temp_solid")
for i in range(max(1, len(mesh_source.materials)))]
material_wire = bpy.data.ma... |
#!/usr/bin/env python3
import sys
import os
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
#sys.path.insert(0, os.path.dirname... |
"""
HTTP Application
================
"""
import asyncio
import logging
from troika.http import \
exceptions, handlers, server, route, transcoders, version
LOGGER = logging.getLogger(__name__)
class Application:
"""The Application is the central coordinator managing the HTTP server,
routes, settings, t... |
from tempest import config
from tempest.openstack.common import log as logging
from tempest.scenario import manager
from tempest.scenario import utils as test_utils
from tempest import test
CONF = config.CONF
LOG = logging.getLogger(__name__)
load_tests = test_utils.load_tests_input_scenario_utils
class TestServer... |
import logging
import os
import sys
import fixtures
import mox
from oslo_config import cfg
from oslotest import mockpatch
import testscenarios
import testtools
from heat.common import context
from heat.common import messaging
from heat.engine.clients.os import cinder
from heat.engine.clients.os import glance
from hea... |
## @package avatar.py
# Controls access to avatar pictures
from flask import request, jsonify, send_from_directory, abort
from flask.views import MethodView
from flask.ext.login import current_user
from werkzeug.utils import secure_filename
from backend import db, app
from backend.database.models import User
from sess... |
import contextlib
import json
import urlparse
from gevent import pywsgi
from gevent.server import StreamServer
import msgpack
from greenrpc import DEFAULT_PORT
from greenrpc.base import BaseServer
class TCPServer(StreamServer, BaseServer):
def __init__(self, services, bind=("127.0.0.1", DEFAULT_PORT), spawn=1):... |
"""
Django settings for foosball project.
Generated by 'django-admin startproject' using Django 1.8.3.
For more information on this file, see
https://docs.djangoproject.com/en/1.8/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.8/ref/settings/
"""
# Build pat... |
'''OpenGL extension SGIX.framezoom
This module customises the behaviour of the
OpenGL.raw.GL.SGIX.framezoom to provide a more
Python-friendly API
Overview (from the spec)
This extension provides a additional way to rasterize geometric
primitives and pixel rectangles. The techique is to reduce the
number of pi... |
# polling_location/urls.py
# Brought to you by We Vote. Be good.
# -*- coding: UTF-8 -*-
from django.conf.urls import url
from . import views_admin
urlpatterns = [
url(r'^$', views_admin.polling_location_list_view, name='polling_location_list',),
url(r'^import/$',
views_admin.polling_locations_import... |
#!/usr/bin/env python3
import sqlite3
import json
import rospy
from std_msgs.msg import String
from lg_common.helpers import run_with_influx_exception_handler
NODE_NAME = 'sqlite_rfid_storage'
class MockPub(object):
def publish(self, *args, **kwargs):
pass
class RfidStorage(object):
def __init__(s... |
# -*- coding: utf-8 -*-
#
# Test links:
# https://www.oboom.com/B7CYZIEB/10Mio.dat
import re
from pyload.utils import json_loads
from pyload.plugin.Hoster import Hoster
from pyload.plugin.captcha.ReCaptcha import ReCaptcha
class OboomCom(Hoster):
__name = "OboomCom"
__type = "hoster"
__version =... |
# coding=utf-8
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import numba
import numpy as np
from sympy import Function, Abs
r"""
Generalized 1-Dimensional Piecewise Analytic Function defined in the interval $ ... |
from __future__ import unicode_literals
from builtins import object
from typing import Set
class TriggerRule(object):
ALL_SUCCESS = 'all_success'
ALL_FAILED = 'all_failed'
ALL_DONE = 'all_done'
ONE_SUCCESS = 'one_success'
ONE_FAILED = 'one_failed'
DUMMY = 'dummy'
NONE_FAILED = 'none_faile... |
"""
======================================
Gradient Boosting Out-of-Bag estimates
======================================
Out-of-bag (OOB) estimates can be a useful heuristic to estimate
the "optimal" number of boosting iterations.
OOB estimates are almost identical to cross-validation estimates but
they can be compute... |
"""Pymode utils."""
import os.path
import sys
import threading
import warnings
from contextlib import contextmanager
import vim # noqa
from ._compat import StringIO
DEBUG = int(vim.eval('g:pymode_debug'))
warnings.filterwarnings('ignore')
@contextmanager
def silence_stderr():
"""Redirect stderr."""
if DE... |
"""Async Callback Examples.
There are 3 examples below.
1. AsyncCallbackHandler
Registering a function as a callback to be triggered when the job has
completed.
2. AsyncErrorCallbackHandler
Registering a function as an error callback to be triggered when an error has
been hit in the Async process.
3. AsyncAsyncCall... |
from application import db
from application.models import Badges, WHMCSclients
from flask import request, flash, url_for, redirect
from flask.ext.admin import BaseView, expose
from flask.ext.login import current_user
from wtforms import Form
from wtforms.fields import IntegerField
from wtforms.ext.sqlalchemy.fields im... |
import unittest
from parameterized import parameterized
from textwrap import dedent
from conans.test.utils.tools import TestClient
class CppStdMinimumVersionTests(unittest.TestCase):
CONANFILE = dedent("""
import os
from conans import ConanFile
from conans.tools import check_min_cppstd, ... |
# -*- coding: utf-8 -*-
#
# Documentation config
#
import sys, os
sys.path.append(os.path.abspath('exts'))
sys.path.append(os.path.abspath('utils'))
import sbt_versions
# highlight_language = 'scala'
highlight_language = 'text' # this way we don't get ugly syntax coloring
extensions = ['sphinx.ext.extlinks', 'incl... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Basic tests for Cerebrum/Account.py."""
from __future__ import unicode_literals
import pytest
import datasource # testsuite/testtools/
from Cerebrum import Account
from Cerebrum import Errors
from Cerebrum import Person
person_cls = Person.Person
account_cls = Accou... |
from oslo_config import cfg
from oslo_log import log as logging
from oslo_serialization import jsonutils
from oslo_utils import encodeutils
import six
import webob.exc
from wsme.rest import json
from glance.api import policy
from glance.api.v2 import metadef_namespaces as namespaces
from glance.api.v2.model.metadef_ob... |
import aiohttp
import concurrent
import google.api_core.exceptions
from hailtop.auth import service_auth_headers
from hailtop.config import get_deploy_config
from hailtop.google_storage import GCS
from hailtop.tls import get_context_specific_ssl_client_session
from hailtop.utils import request_retry_transient_errors
... |
import abc
import os
import shutil
import sys
import tempfile
import unittest
import backbacker.commands.file_sync as file_sync
class FileSyncTests(unittest.TestCase, metaclass=abc.ABCMeta):
@classmethod
@abc.abstractmethod
def instance(cls):
raise NotImplementedError()
def setUp(self):
... |
import sys
import logbook
import pytest
logbook.StderrHandler().push_application()
@pytest.fixture
def logger():
return logbook.Logger('testlogger')
@pytest.fixture
def active_handler(request, test_handler, activation_strategy):
s = activation_strategy(test_handler)
s.activate()
@request.addfina... |
from mitsuba.core import *
from mitsuba.render import *
import multiprocessing
import numpy as np
from numpy.random import *
import numpy.matlib
import json
from body import Body
from file_checker import file_checker
sensor_prop = {
'type' : 'perspective',
'toWorld' : Transform.lookAt(
Point(0, 0, 95... |
#!/Library/Frameworks/Python.framework/Versions/2.7/bin/python
# USAGE:
# ./hbond_plotting.py dir/data_file system_descriptor
# PREAMBLE:
import sys
import os
from plotting_functions import *
from sel_list import *
#dat = sys.argv[1]
system = sys.argv[1]
nSel = len(sel)
change_dir = os.chdir
# ----------------... |
# Description: Compares naive Bayes with and withouth feature subset selection
# Category: preprocessing
# Uses: voting.tab
# Referenced: orngFSS.htm
# Classes: orngFSS.attMeasure, orngFSS.selectBestNAtts
import orange, orngFSS
class BayesFSS(object):
def __new__(cls, examples=None, **kwds):
lear... |
from gi.repository import GObject
if __name__ == '__main__':
# install _() func before importing dbus_support
from common import i18n
from common import dbus_support
if dbus_support.supported:
import dbus
class MusicTrackInfo(object):
__slots__ = ['title', 'album', 'artist', 'duration', 'track_number'... |
import httplib
import httplib2
import logging
import os
import time
from apiclient import discovery
from apiclient.errors import HttpError
from apiclient.http import MediaFileUpload
from mutagen import oggvorbis
from oauth2client import file
from oauth2client import client
from oauth2client import tools
log = logging... |
# -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model 'Flash'
db.create_table('cmsplugin_flash', (
('cmsplugin_ptr', self.gf('django.db... |
import click
import re
import os
import functools
__doc__ = """
Convert a libre office forumla into an XML .jff file accepted by JFLAP
uses \"|\" (literal: "|") as separator. and literal: newline as newline
separator. Removes all whitespace (" "). Uses literal -> as production rule
symbol.
"""
RHS_DIVIDER = '"|"' # ... |
from weboob.tools.test import BackendTest
class PixtoilelibreTest(BackendTest):
BACKEND = 'pixtoilelibre'
# small gif file
DATA = 'R0lGODlhAQABAIAAAP///wAAACH5BAAAAAAALAAAAAABAAEAAAICRAEAOw==\n'
def test_pixtoilelibre(self):
assert self.backend.can_post(self.DATA, max_age=0)
post = ... |
"""Tests for hermite_e module.
"""
from __future__ import division, absolute_import, print_function
import numpy as np
import numpy.polynomial.hermite_e as herme
from numpy.polynomial.polynomial import polyval
from numpy.testing import (
TestCase, assert_almost_equal, assert_raises,
assert_equal, assert_, run... |
import imp
import codecs
script = imp.load_source('tamkin-driver', '../tamkin/driver.py')
with codecs.open('reference/tamkin-driver.rst', 'w', 'utf-8') as f:
f.write(script.__doc__) |
#!/usr/bin/env python
'''
OWASP ZSC
https://www.owasp.org/index.php/OWASP_ZSC_Tool_Project
https://github.com/zscproject/OWASP-ZSC
http://api.z3r0d4y.com/
https://groups.google.com/d/forum/owasp-zsc [ owasp-zsc[at]googlegroups[dot]com ]
'''
import random, binascii, string
from core.compatible import version
_version = ... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('mi_tienda', '0003_auto_20170327_1558'),
]
operations = [
migrations.AddField(
model_name='bici',
nam... |
import xbmc, xbmcaddon, xbmcgui, xbmcplugin,os,base64,sys
import urllib2,urllib
import time
import downloader
import common as Common
import wipe
import zipfile
import hashlib
AddonTitle="[COLOR ghostwhite]Project X[/COLOR] [COLOR lightsteelblue]Wizard[/COLOR]"
USERDATA = xbmc.translatePath(os.path.join('special:... |
import requests
import os
API_KEY = os.environ.get('REACTOR_API_KEY')
REACTOR_API_GATEWAY = os.environ.get('REACTOR_API_GATEWAY')
NAMESPACE = os.environ.get('REACTOR_NAMESPACE')
def get_request_to_reactor_api(endpoint, query_params=None, api_key=API_KEY, host=REACTOR_API_GATEWAY,
api_p... |
import sahara.plugins.mapr.domain.node_process as np
import sahara.plugins.mapr.domain.service as s
import sahara.plugins.mapr.util.validation_utils as vu
HTTP_FS = np.NodeProcess(
name='httpfs',
ui_name='HTTPFS',
package='mapr-httpfs',
open_ports=[14000]
)
class HttpFS(s.Service):
def __init__(... |
import os
import sys
import queue
from tumbly.confighandler import put_config
from tumbly.database import create_check_database
from tumbly.scrape import scrape_tumblr
from tumbly.download import download_images
from PyQt5.QtCore import pyqtSignal, pyqtSlot, QObject, QThread
from PyQt5.QtGui import QIcon
from PyQt5.Q... |
import os
import uuid
try:
import ujson as json_lib
except ImportError:
try:
import simplejson as json_lib
except ImportError:
import json as json_lib
class Container(object):
"""
Manages file i/o for a set of objects.
"""
def __init__(self):
self._path = None
... |
"""DRFES views."""
# Copyright 2015 Solinea, Inc.
#
# 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 a... |
import logging
import os
from django.shortcuts import get_object_or_404
from rest_framework.decorators import api_view, permission_classes
from rest_framework.exceptions import NotFound
from rest_framework.permissions import AllowAny, IsAuthenticated
from rest_framework.status import HTTP_200_OK, HTTP_201_CREATED, \
... |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# S.D.G
# Imports
from .baseLayer import baseLayer
from icyTorpedo.linearities import Linear
__author__ = 'Ben Johnston'
__revision__ = '0.1'
__date__ = 'Wednesday 21 September 20:56:50 AEST 2016'
__license__ = 'MPL v2.0'
class InputLayer(baseLayer):
"""Input Laye... |
# -*- coding: utf-8 -*-
from django.db import models, transaction
from django.utils.translation import ugettext_lazy as _
from django_markdown.models import MarkdownField
from reversion import revisions
from asylum.models import AsylumModel
class TokenType(AsylumModel):
label = models.CharField(_("Label"), max_l... |
import copy
import os
import re
import sys
#
# Find the WebKit python directories and add them to the PYTHONPATH
#
try:
f = __file__
except NameError:
f = sys.argv[0]
this_file = os.path.abspath(f)
base_dir = this_file[0:this_file.find('webkit'+ os.sep + 'tools')]
webkitpy_dir = os.path.join(base_dir, 'third_... |
import logging
import couchdb
import urlparse
import json
import urllib2
import threading
import re
from pylons import request, response, session, tmpl_context as c, url
from pylons.controllers.util import abort, redirect
from lr.model import LRNode as sourceLRNode, \
NodeServiceModel, ResourceDataModel, L... |
import climt
from sympl import (
get_constant, AdamsBashforth,
TendencyComponent, TendencyStepper)
from datetime import timedelta
import numpy as np
class ConservationTestBase(object):
def get_model_state(self, component):
state = climt.get_default_state([component])
return self.modify_st... |
# -*- coding: utf-8 -*-
"""
Display if files or directories exists.
Configuration parameters:
cache_timeout: refresh interval for this module (default 10)
format: display format for this module
(default '\?color=path [\?if=path ●|■]')
format_path: format for paths (default '{basename}')
format_... |
import threading
class DeviceHandler():
def __init__(self):
self.devices = []
self.deviceLock = threading.Lock()
def addDevice( self, device ):
for item in self.devices:
if item.id == device.id:
print( "device ", device.id, " already registered" ... |
# Django settings for testsite project.
import os
PROJECT_ROOT = os.path.abspath(os.path.dirname(__file__))
DEBUG = True
TEMPLATE_DEBUG = DEBUG
ADMINS = (
# ('Your Name', '<EMAIL>'),
)
MANAGERS = ADMINS
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(P... |
import re
import datetime
import isodate
import math
import requests
from dateutil.parser import parse
from shapely.geometry import box
def is_range_common_era(start, end):
"""
does the range contains CE dates.
BCE and CE are not compatible at the moment.
:param start:
:param end:
:return: F... |
#!/usr/bin/env python
import numpy as np
import copy,sys
__doc__ = """This module defines the basic functionality to define a dataset with history features in it.
The central component of this module is the DataSet class. It is meant to be a base class for data sets
that can be used in the analysis of history feature... |
KS_SPOT = "00"
KS_DEFER = "10"
KS_FUTURES = "11"
KS_FORWARD = "01"
KS_DELIVERY = "AP"
KS_MIDDLE = "MD"
KS_I_INITING = '0'
KS_I_INIT = '1'
KS_I_BEGIN = '2'
KS_I_GRP_ORDER = '3'
KS_I_GRP_MATCH = '4'
KS_I_NORMAL = '5'
KS_I_PAUSE = '6'
KS_I_DERY_APP = '7'
KS_I_DERY_MATCH = '8'
KS_I_MID_APP = '9'
KS_I_MID_MATCH = 'A'
KS_I_E... |
import pytest
from selenium import webdriver
@pytest.fixture
def driver(request):
wd = webdriver.Chrome()
request.addfinalizer(wd.quit)
return wd
def find_selected_option(select):
idx = select.get_property("selectedIndex")
option = select.find_element_by_css_selector("option:nth-child(%s)" % (id... |
import numpy
from prpy.tsr.tsrlibrary import TSRFactory
from prpy.tsr.tsr import *
@TSRFactory('herb', 'plastic_glass', 'grasp')
def glass_grasp(robot, glass, manip=None, **kw_args):
'''
@param robot The robot performing the grasp
@param glass The glass to grasp
@param manip The manipulator to perform ... |
#####################################
# join_inflits
# Input: infobj_transformed(inflit).txt
# filtered_inflit.txt
# Output: literals_final.txt (joined list of literals, contains all literals used later)
# Description:
# Join the original infobox literal list with the extracted literals from the infobox objects
#... |
#!/usr/bin/env python
"""
Flock of birds Python driver.
@author: Michael Hausenblas, http://mhausenblas.info/#i
@since: 2016-04-02
@status: init
"""
import logging
import os
import json
import tornado.ioloop
import tornado.web
import fobfun
from tornado.escape import json_encode
DEBUG = False
FOB_DRIVER_PORT = 808... |
import json
import xbmc
import xbmcaddon
import xbmcgui
addon = xbmcaddon.Addon()
def get_search_history():
search_history = addon.getSetting('SEARCH_HISTORY')
if search_history == '':
addon.setSetting('SEARCH_HISTORY', json.dumps([]))
return []
json_data = json.loads(search_history)
... |
"""Contains various command utils and a global command dict.
Module attributes:
cmd_dict: A mapping from command-strings to command objects.
"""
from qutebrowser.utils import usertypes, qtutils, log
from qutebrowser.commands import command, cmdexc
cmd_dict = {}
aliases = []
def check_overflow(arg, ctype):
... |
import os
import pytest
import fuzzinator
from common_formatter import mock_issue, mock_templates_dir
@pytest.mark.parametrize('formatter_kwargs, exp_key', [
({'format': 'short'}, 'short'),
({'format': 'long'}, 'long'),
({}, 'long'),
])
@pytest.mark.parametrize('issue, formatter_init_kwargs, exp_dict', ... |
#!/usr/bin/env python3
import requests
import argparse
import code
import getpass
import re
import itertools
import json
import operator
import os
import time
HOST = 'https://edstem.com.au'
#props to http://stackoverflow.com/a/16090640
def natural_sort_key(s, _nsre=re.compile('([0-9]+)')):
return [int(text) if t... |
# -*- coding: utf-8 -*-
# ------------------------------------------------------------
# streamondemand.- XBMC Plugin
# Canal para guardaserie - Thank you robalo!
# http://blog.tvalacarta.info/plugin-xbmc/streamondemand.
# ------------------------------------------------------------
import re
import urlparse
from core... |
import re
from sanic import Blueprint
from sanic.response import json, redirect
from sanic.views import HTTPMethodView
from utils.decorators import login_required, login_optional
from utils import tools
from ssr_panel.exceptions import BadRequest
from ssr_panel import app, render
from ssr_panel.models import User
auth... |
"""
@author: <EMAIL>
@copyright: 2017 Englesh.org. All rights reserved.
@license: https://github.com/Fyzel/weather-data-flaskapi/blob/master/LICENSE
@contact: <EMAIL>
@deffield updated: 2017-06-14
"""
from os import path
import logging.config
from flask import Flask, Blueprint
from api.restplus impo... |
import subprocess as sp
import re
import os
from collections import OrderedDict
import time
from ..util.iterstuff import grouper
from .drm import DRM
def convert_size_to_kb(size_str):
if size_str.endswith('G'):
return float(size_str[:-1]) * 1024 * 1024
elif size_str.endswith('M'):
return floa... |
r"""Electronic Voting Example.
In this example we use DeepSets to estimate the winner of an election.
Each vote is represented by a one-hot encoded vector.
It goes without saying, but don't use this in a real election!
Seriously, don't!
"""
import collections
import logging
import random
from absl import app
import... |
# -*- coding: utf-8 -*-
"""
flask-sentinel
~~~~~~~~~~~~~~
:copyright: (c) 2015 by Nicola Iarocci.
:license: BSD, see LICENSE for more details.
"""
from flask import Blueprint
from . import views
from .core import oauth, mongo, redis
from .utils import Config
from .validator import MyRequestValidator
f... |
from hyperspyui.plugins.plugin import Plugin
import numpy as np
from hyperspyui.util import win2sig
class EnsureLt2D(object):
def __init__(self, ui):
self.ui = ui
def __call__(self, win, action):
sig = win2sig(win, self.ui.signals, self.ui._plotting_signal)
valid = sig is not None a... |
import StringIO
import zipfile
from django.core.cache import cache
from corehq.apps.hqmedia.models import CommCareImage, CommCareAudio, CommCareVideo
from django.utils.translation import ugettext as _
from soil import DownloadBase
class BaseMultimediaStatusCache(object):
upload_type = None
cache_expiry = 60 *... |
"""
This module provides wrapper function for transparently handling files regardless of location (local, cloud, etc).
"""
__all__ = ['uri_open', 'uri_to_tempfile', 'uri_read', 'uri_dump', 'uri_exists', 'get_uri_metadata', 'uri_exists_wait', 'URIFileType', 'URIType']
import functools
import warnings
import uriutils
... |
# -*- coding: utf-8 -*-
"""
***************************************************************************
RunAlgTest.py
---------------------
Date : March 2013
Copyright : (C) 2013 by Victor Olaya
Email : volayaf at gmail dot com
*****************************... |
"""This example illustrates how to download a report file."""
import argparse
import sys
from apiclient import sample_tools
from oauth2client import client
# Declare command-line flags.
argparser = argparse.ArgumentParser(add_help=False)
argparser.add_argument(
'report_id', type=int,
help='The ID of the repo... |
#!/usr/bin/python
#--------------------------------------
# ___ ___ _ ____
# / _ \/ _ \(_) __/__ __ __
# / , _/ ___/ /\ \/ _ \/ // /
# /_/|_/_/ /_/___/ .__/\_, /
# /_/ /___/
#
# bme280.py
# Read data from a digital pressure sensor.
#
# Official datasheet available from :
# https:... |
import random
import unittest
from testlib import mox
from google.appengine.ext import ndb
from google.appengine.api import datastore
from google.appengine.ext import db
from mapreduce import context
from testlib import testutil
from google.appengine.runtime import apiproxy_errors
# pylint: disable=g-bad-name
clas... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.